diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..757fee31c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea \ No newline at end of file diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 000000000..f2ec9fa02 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +angular-express-seed \ No newline at end of file diff --git a/.idea/angular-express-seed.iml b/.idea/angular-express-seed.iml new file mode 100644 index 000000000..8cd1fbc15 --- /dev/null +++ b/.idea/angular-express-seed.iml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 000000000..e206d70d8 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.idea/jsLibraryMappings.xml b/.idea/jsLibraryMappings.xml new file mode 100644 index 000000000..8d0aa3a83 --- /dev/null +++ b/.idea/jsLibraryMappings.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/.idea/libraries/angular_express_seed_node_modules.xml b/.idea/libraries/angular_express_seed_node_modules.xml new file mode 100644 index 000000000..a5126a559 --- /dev/null +++ b/.idea/libraries/angular_express_seed_node_modules.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 000000000..1162f4382 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 000000000..215d55ab4 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.idea/scopes/scope_settings.xml b/.idea/scopes/scope_settings.xml new file mode 100644 index 000000000..922003b84 --- /dev/null +++ b/.idea/scopes/scope_settings.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 000000000..c80f2198b --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 000000000..e853aecc6 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,392 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1410293658690 + 1410293658690 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app.js b/app.js index f09e09d96..05f2bd183 100644 --- a/app.js +++ b/app.js @@ -1,66 +1,57 @@ - -/** - * Module dependencies - */ +/*** Module dependencies ***/ var express = require('express'), - bodyParser = require('body-parser'), - methodOverride = require('method-override'), - errorHandler = require('error-handler'), - morgan = require('morgan'), - routes = require('./routes'), - api = require('./routes/api'), - http = require('http'), - path = require('path'); - -var app = module.exports = express(); + bodyParser = require('body-parser'), + methodOverride = require('method-override'), + errorHandler = require('express-error-handler'), + morgan = require('morgan'), + http = require('http'), + path = require('path'); + lessMiddleware = require('less-middleware'); +/*** VARs ***/ +var app = express(); +var port = 3001; -/** - * Configuration - */ +/*** Configuration ***/ // all environments -app.set('port', process.env.PORT || 3000); +app.set('port', process.env.PORT || 3001); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(morgan('dev')); -app.use(bodyParser()); +app.use(bodyParser.json()); app.use(methodOverride()); -app.use(express.static(path.join(__dirname, 'public'))); - -var env = process.env.NODE_ENV || 'development'; - -// development only -if (env === 'development') { - app.use(express.errorHandler()); -} +app.use(lessMiddleware(path.join(__dirname + '/public'))); +app.use(express.static(path.join(__dirname + '/public'))); +app.use(errorHandler()); -// production only -if (env === 'production') { - // TODO -} +/*** Routes ***/ -/** - * Routes - */ - -// serve index and view partials -app.get('/', routes.index); -app.get('/partials/:name', routes.partials); - -// JSON API -app.get('/api/name', api.name); - +app.get('/', function(req,res) { + res.render('index'); +}); +app.get('/client', function(req,res) { + res.render('client'); +}); +app.get('/partials/:name', function(req,res){ + var name = req.params.name; + res.render('partials/' + name); +}); // redirect all others to the index (HTML5 history) -app.get('*', routes.index); - +app.get('*', function(req,res) { + res.render('index'); +}); +// JSON API +app.get('/api/name', function (req, res) { + res.json({ + name: 'Bob' + }); +}); -/** - * Start Server - */ +/*** HTTP Server ***/ -http.createServer(app).listen(app.get('port'), function () { - console.log('Express server listening on port ' + app.get('port')); +app.listen(port, function(){ + console.log('HTTP Server listening on port '+ port); }); diff --git a/node_modules/.bin/jade b/node_modules/.bin/jade new file mode 100644 index 000000000..7de066b9b --- /dev/null +++ b/node_modules/.bin/jade @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../jade/bin/jade" "$@" + ret=$? +else + node "$basedir/../jade/bin/jade" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/jade.cmd b/node_modules/.bin/jade.cmd new file mode 100644 index 000000000..cb2dede99 --- /dev/null +++ b/node_modules/.bin/jade.cmd @@ -0,0 +1,5 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\jade\bin\jade" %* +) ELSE ( + node "%~dp0\..\jade\bin\jade" %* +) \ No newline at end of file diff --git a/node_modules/body-parser/.npmignore b/node_modules/body-parser/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/body-parser/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md new file mode 100644 index 000000000..5d6fd1f14 --- /dev/null +++ b/node_modules/body-parser/HISTORY.md @@ -0,0 +1,155 @@ +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 000000000..53e49a382 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 000000000..7891eceb2 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,125 @@ +# body-parser + +[![NPM version](https://badge.fury.io/js/body-parser.svg)](https://badge.fury.io/js/body-parser) +[![Build Status](https://travis-ci.org/expressjs/body-parser.svg?branch=master)](https://travis-ci.org/expressjs/body-parser) +[![Coverage Status](https://img.shields.io/coveralls/expressjs/body-parser.svg?branch=master)](https://coveralls.io/r/expressjs/body-parser) +[![Gittip](http://img.shields.io/gittip/dougwilson.svg)](https://www.gittip.com/dougwilson/) + +Node.js body parsing middleware. + +This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: + +- [busboy](https://www.npmjs.org/package/busboy#readme) and [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) +- [multiparty](https://www.npmjs.org/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) +- [formidable](https://www.npmjs.org/package/formidable#readme) +- [multer](https://www.npmjs.org/package/multer#readme) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +// parse application/vnd.api+json as json +app.use(bodyParser.json({ type: 'application/vnd.api+json' })) + +app.use(function (req, res, next) { + console.log(req.body) // populated! + next() +}) +``` + +### bodyParser.json(options) + +Returns middleware that only parses `json`. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. + +The options are: + +- `strict` - only parse objects and arrays. (default: `true`) +- `inflate` - if deflated bodies will be inflated. (default: `true`) +- `limit` - maximum request body size. (default: `<100kb>`) +- `reviver` - passed to `JSON.parse()` +- `type` - request content-type to parse (default: `json`) +- `verify` - function to verify body content + +The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `json`), a mime type (like `application/json`), or a mime time with a wildcard (like `*/json`). + +The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. + +The `reviver` argument is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +### bodyParser.raw(options) + +Returns middleware that parses all bodies as a `Buffer`. This parser supports automatic inflation of `gzip` and `deflate` encodings. + +The options are: + +- `inflate` - if deflated bodies will be inflated. (default: `true`) +- `limit` - maximum request body size. (default: `<100kb>`) +- `type` - request content-type to parse (default: `application/octet-stream`) +- `verify` - function to verify body content + +The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime time with a wildcard (like `application/*`). + +The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text(options) + +Returns middleware that parses all bodies as a string. This parser supports automatic inflation of `gzip` and `deflate` encodings. + +The options are: + +- `defaultCharset` - the default charset to parse as, if not specified in content-type. (default: `utf-8`) +- `inflate` - if deflated bodies will be inflated. (default: `true`) +- `limit` - maximum request body size. (default: `<100kb>`) +- `type` - request content-type to parse (default: `text/plain`) +- `verify` - function to verify body content + +The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime time with a wildcard (like `text/*`). + +The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded(options) + +Returns middleware that only parses `urlencoded` bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. + +The options are: + +- `extended` - parse extended syntax with the [qs](https://www.npmjs.org/package/qs#readme) module. (default: `true`) +- `inflate` - if deflated bodies will be inflated. (default: `true`) +- `limit` - maximum request body size. (default: `<100kb>`) +- `type` - request content-type to parse (default: `urlencoded`) +- `verify` - function to verify body content + +The `extended` argument allows to choose between parsing the urlencoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the urlencoded format, allowing for a JSON-like experience with urlencoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). + +The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime time with a wildcard (like `*/x-www-form-urlencoded`). + +The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. + +### req.body + +A new `body` object containing the parsed data is populated on the `request` object after the middleware. + +## License + +[MIT](LICENSE) diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 000000000..7c87204b8 --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,84 @@ +/*! + * body-parser + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var deprecate = require('depd')('body-parser') +var fs = require('fs') +var path = require('path') + +/** + * Module exports. + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * Path to the parser modules. + */ + +var parsersDir = path.join(__dirname, 'lib', 'types') + +/** + * Auto-load bundled parsers with getters. + */ + +fs.readdirSync(parsersDir).forEach(function onfilename(filename) { + if (!/\.js$/.test(filename)) return + + var loc = path.resolve(parsersDir, filename) + var mod + var name = path.basename(filename, '.js') + + function load() { + if (mod) { + return mod + } + + return mod = require(loc) + } + + Object.defineProperty(exports, name, { + configurable: true, + enumerable: true, + get: load + }) +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @api public + */ + +function bodyParser(options){ + var opts = {} + + options = options || {} + + // exclude type option + for (var prop in options) { + if ('type' !== prop) { + opts[prop] = options[prop] + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser(req, res, next) { + _json(req, res, function(err){ + if (err) return next(err); + _urlencoded(req, res, next); + }); + } +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 000000000..3cbf235a9 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,143 @@ +/*! + * body-parser + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var typer = require('media-typer') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {object} options + * @api private + */ + +function read(req, res, next, parse, options) { + var length + var stream + + // flag as parsed + req._body = true + + try { + stream = contentstream(req, options.inflate) + length = stream.length + delete stream.length + } catch (err) { + return next(err) + } + + options = options || {} + options.length = length + + var encoding = options.encoding !== null + ? options.encoding || 'utf-8' + : null + var verify = options.verify + + options.encoding = verify + ? null + : encoding + + // read body + getBody(stream, options, function (err, body) { + if (err) { + if (!err.status) { + err.status = 400 + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished() { + next(err) + }) + return + } + + // verify + if (verify) { + try { + verify(req, res, body, encoding) + } catch (err) { + if (!err.status) err.status = 403 + return next(err) + } + } + + // parse + try { + body = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(body) + } catch (err){ + err.body = body + err.status = 400 + return next(err) + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream(req, inflate) { + var encoding = req.headers['content-encoding'] || 'identity' + var err + var length = req.headers['content-length'] + var stream + + if (inflate === false && encoding !== 'identity') { + err = new Error('content encoding unsupported') + err.status = 415 + throw err + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + err = new Error('unsupported content encoding') + err.status = 415 + throw err + } + + return stream +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 000000000..73d351240 --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,107 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var read = require('../read') +var typer = require('media-typer') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + */ + +var firstcharRegExp = /^\s*(.)/ + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function json(options) { + options = options || {} + + var limit = typeof options.limit !== 'number' + ? bytes(options.limit || '100kb') + : options.limit + var inflate = options.inflate !== false + var reviver = options.reviver + var strict = options.strict !== false + var type = options.type || 'json' + var verify = options.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + function parse(body) { + if (0 === body.length) { + throw new Error('invalid json, empty body') + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + throw new Error('invalid json') + } + } + + return JSON.parse(body, reviver) + } + + return function jsonParser(req, res, next) { + if (req._body) return next() + req.body = req.body || {} + + if (!typeis(req, type)) return next() + + // RFC 7159 sec 8.1 + var charset = typer.parse(req).parameters.charset || 'utf-8' + if (charset.substr(0, 4).toLowerCase() !== 'utf-') { + var err = new Error('unsupported charset') + err.status = 415 + next(err) + return + } + + // read + read(req, res, next, parse, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @api public + */ + + +function firstchar(str) { + if (!str) return '' + var match = firstcharRegExp.exec(str) + return match ? match[1] : '' +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 000000000..9d7e49a6f --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,61 @@ +/*! + * body-parser + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw(options) { + options = options || {}; + + var inflate = options.inflate !== false + var limit = typeof options.limit !== 'number' + ? bytes(options.limit || '100kb') + : options.limit + var type = options.type || 'application/octet-stream' + var verify = options.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + function parse(buf) { + return buf + } + + return function rawParser(req, res, next) { + if (req._body) return next() + req.body = req.body || {} + + if (!typeis(req, type)) return next() + + // read + read(req, res, next, parse, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 000000000..2330b5bab --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,66 @@ +/*! + * body-parser + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var read = require('../read') +var typeis = require('type-is') +var typer = require('media-typer') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text(options) { + options = options || {}; + + var defaultCharset = options.defaultCharset || 'utf-8' + var inflate = options.inflate !== false + var limit = typeof options.limit !== 'number' + ? bytes(options.limit || '100kb') + : options.limit + var type = options.type || 'text/plain' + var verify = options.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + function parse(buf) { + return buf + } + + return function textParser(req, res, next) { + if (req._body) return next() + req.body = req.body || {} + + if (!typeis(req, type)) return next() + + // get charset + var charset = typer.parse(req).parameters.charset || defaultCharset + + // read + read(req, res, next, parse, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 000000000..9a9d3b1ba --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,111 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typer = require('media-typer') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function urlencoded(options){ + options = options || {}; + + // notice because option default will flip in next major + if (options.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = options.extended !== false + var inflate = options.inflate !== false + var limit = typeof options.limit !== 'number' + ? bytes(options.limit || '100kb') + : options.limit + var type = options.type || 'urlencoded' + var verify = options.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + var queryparse = extended + ? parser('qs') + : parser('querystring') + + function parse(body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser(req, res, next) { + if (req._body) return next(); + req.body = req.body || {} + + if (!typeis(req, type)) return next(); + + var charset = typer.parse(req).parameters.charset || 'utf-8' + if (charset.toLowerCase() !== 'utf-8') { + var err = new Error('unsupported charset') + err.status = 415 + next(err) + return + } + + // read + read(req, res, next, parse, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser(name) { + var mod = parsers[name] + + if (mod) { + return mod.parse + } + + // load module + mod = parsers[name] = require(name) + + return mod.parse +} diff --git a/node_modules/body-parser/node_modules/bytes/.npmignore b/node_modules/body-parser/node_modules/bytes/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/body-parser/node_modules/bytes/History.md b/node_modules/body-parser/node_modules/bytes/History.md new file mode 100644 index 000000000..5097352ec --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/History.md @@ -0,0 +1,25 @@ + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/body-parser/node_modules/bytes/Makefile b/node_modules/body-parser/node_modules/bytes/Makefile new file mode 100644 index 000000000..8e8640f2e --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --reporter spec \ + --require should + +.PHONY: test \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/bytes/Readme.md b/node_modules/body-parser/node_modules/bytes/Readme.md new file mode 100644 index 000000000..5591b28fb --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/Readme.md @@ -0,0 +1,54 @@ +# node-bytes + + Byte string parser / formatter. + +## Example: + +```js +bytes('1kb') +// => 1024 + +bytes('2mb') +// => 2097152 + +bytes('1gb') +// => 1073741824 + +bytes(1073741824) +// => 1gb + +bytes(1099511627776) +// => 1tb +``` + +## Installation + +``` +$ npm install bytes +$ component install visionmedia/bytes.js +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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/body-parser/node_modules/bytes/component.json b/node_modules/body-parser/node_modules/bytes/component.json new file mode 100644 index 000000000..2929c25d6 --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/component.json @@ -0,0 +1,7 @@ +{ + "name": "bytes", + "description": "byte size string parser / serializer", + "keywords": ["bytes", "utility"], + "version": "0.2.1", + "scripts": ["index.js"] +} diff --git a/node_modules/body-parser/node_modules/bytes/index.js b/node_modules/body-parser/node_modules/bytes/index.js new file mode 100644 index 000000000..c1da2fe40 --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/index.js @@ -0,0 +1,41 @@ + +/** + * Parse byte `size` string. + * + * @param {String} size + * @return {Number} + * @api public + */ + +module.exports = function(size) { + if ('number' == typeof size) return convert(size); + var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb|tb)$/) + , n = parseFloat(parts[1]) + , type = parts[2]; + + var map = { + kb: 1 << 10 + , mb: 1 << 20 + , gb: 1 << 30 + , tb: ((1 << 30) * 1024) + }; + + return map[type] * n; +}; + +/** + * convert bytes into string. + * + * @param {Number} b - bytes to convert + * @return {String} + * @api public + */ + +function convert (b) { + var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10, abs = Math.abs(b); + if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb'; + if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; + if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; + if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; + return b + 'b'; +} diff --git a/node_modules/body-parser/node_modules/bytes/package.json b/node_modules/body-parser/node_modules/bytes/package.json new file mode 100644 index 000000000..61a79a5f8 --- /dev/null +++ b/node_modules/body-parser/node_modules/bytes/package.json @@ -0,0 +1,50 @@ +{ + "name": "bytes", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "byte size string parser / serializer", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/bytes.js.git" + }, + "version": "1.0.0", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "component": { + "scripts": { + "bytes/index.js": "index.js" + } + }, + "bugs": { + "url": "https://github.com/visionmedia/bytes.js/issues" + }, + "homepage": "https://github.com/visionmedia/bytes.js", + "_id": "bytes@1.0.0", + "dist": { + "shasum": "3569ede8ba34315fab99c3e92cb04c7220de1fa8", + "tarball": "http://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz" + }, + "_from": "bytes@1.0.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "3569ede8ba34315fab99c3e92cb04c7220de1fa8", + "_resolved": "https://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/depd/.npmignore b/node_modules/body-parser/node_modules/depd/.npmignore new file mode 100644 index 000000000..0c7e391fd --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/.npmignore @@ -0,0 +1,4 @@ +coverage/ +files/ +test/ +.travis.yml diff --git a/node_modules/body-parser/node_modules/depd/History.md b/node_modules/body-parser/node_modules/depd/History.md new file mode 100644 index 000000000..ba1af12ee --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/History.md @@ -0,0 +1,56 @@ +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/body-parser/node_modules/depd/LICENSE b/node_modules/body-parser/node_modules/depd/LICENSE new file mode 100644 index 000000000..b7dce6cf9 --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/body-parser/node_modules/depd/Readme.md b/node_modules/body-parser/node_modules/depd/Readme.md new file mode 100644 index 000000000..47a53a179 --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/Readme.md @@ -0,0 +1,272 @@ +# depd + +[![NPM version](https://badge.fury.io/js/depd.svg)](http://badge.fury.io/js/depd) +[![Build Status](https://travis-ci.org/dougwilson/nodejs-depd.svg?branch=master)](https://travis-ci.org/dougwilson/nodejs-depd) +[![Coverage Status](https://img.shields.io/coveralls/dougwilson/nodejs-depd.svg?branch=master)](https://coveralls.io/r/dougwilson/nodejs-depd) +[![Gittip](http://img.shields.io/gittip/dougwilson.svg)](https://www.gittip.com/dougwilson/) + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +```sh +$ npm install depd +``` + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspecting the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations. + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations. + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/body-parser/node_modules/depd/index.js b/node_modules/body-parser/node_modules/depd/index.js new file mode 100644 index 000000000..a6fb37288 --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/index.js @@ -0,0 +1,520 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Get listener count on event emitter. + */ + +/*istanbul ignore next*/ +var eventListenerCount = EventEmitter.listenerCount + || function (emitter, type) { return emitter.listeners(type).length } + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + var typeName = callSite.getTypeName() + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + // make useful type name + if (typeName === 'Function') { + typeName = callSite.getThis().name || typeName + } + + return callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/body-parser/node_modules/depd/package.json b/node_modules/body-parser/node_modules/depd/package.json new file mode 100644 index 000000000..6935dc5f1 --- /dev/null +++ b/node_modules/body-parser/node_modules/depd/package.json @@ -0,0 +1,56 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "0.4.4", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git://github.com/dougwilson/nodejs-depd" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.20.1", + "should": "~4.0.4" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --require should test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" + }, + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@0.4.4", + "dist": { + "shasum": "07091fae75f97828d89b4a02a2d4778f0e7c0662", + "tarball": "http://registry.npmjs.org/depd/-/depd-0.4.4.tgz" + }, + "_from": "depd@0.4.4", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "directories": {}, + "_shasum": "07091fae75f97828d89b4a02a2d4778f0e7c0662", + "_resolved": "https://registry.npmjs.org/depd/-/depd-0.4.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/iconv-lite/.npmignore b/node_modules/body-parser/node_modules/iconv-lite/.npmignore new file mode 100644 index 000000000..6c69ea06f --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/.npmignore @@ -0,0 +1,5 @@ +*~ +*sublime-* +generation +test +wiki diff --git a/node_modules/body-parser/node_modules/iconv-lite/.travis.yml b/node_modules/body-parser/node_modules/iconv-lite/.travis.yml new file mode 100644 index 000000000..9169b9f66 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/.travis.yml @@ -0,0 +1,5 @@ + language: node_js + node_js: + - 0.8 + - 0.10 + - 0.11 diff --git a/node_modules/body-parser/node_modules/iconv-lite/Changelog.md b/node_modules/body-parser/node_modules/iconv-lite/Changelog.md new file mode 100644 index 000000000..75db5f9e4 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,29 @@ + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/node_modules/body-parser/node_modules/iconv-lite/LICENSE b/node_modules/body-parser/node_modules/iconv-lite/LICENSE new file mode 100644 index 000000000..d518d8376 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/body-parser/node_modules/iconv-lite/README.md b/node_modules/body-parser/node_modules/iconv-lite/README.md new file mode 100644 index 000000000..f8d084500 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/README.md @@ -0,0 +1,137 @@ +## Pure JS character encoding conversion + + + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### Extend Node.js own encodings +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2313, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.10.26). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.0 + ---------------------------------------------------------- + encode('win1251') ~130 Mb/s ~380 Mb/s + decode('win1251') ~127 Mb/s ~210 Mb/s + + +## Notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js +``` + +## Adoption +[![NPM](https://nodei.co/npm-dl/iconv-lite.png)](https://nodei.co/npm/iconv-lite/) + diff --git a/node_modules/body-parser/node_modules/iconv-lite/README.md~ b/node_modules/body-parser/node_modules/iconv-lite/README.md~ new file mode 100644 index 000000000..5f575615e --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/README.md~ @@ -0,0 +1,54 @@ +iconv-lite - native javascript conversion between character encodings. +====================================================================== + +## Usage + + var iconv = require('iconv-lite'); + + // Convert from an encoded buffer to string. + str = iconv.fromEncoding(buf, 'win-1251'); + // Or + str = iconv.decode(buf, 'win-1251'); + + // Convert from string to an encoded buffer. + buf = iconv.toEncoding("Sample input string", 'win-1251'); + // Or + buf = iconv.encode("Sample input string", 'win-1251'); + +## Supported encodings + +Currently only a small part of encodings supported: + +* All node.js native encodings: 'utf8', 'ucs2', 'ascii', 'binary', 'base64'. +* 'latin1' +* Cyrillic encodings: 'windows-1251', 'koi8-r', 'iso 8859-5'. + +Other encodings are easy to add, see the source. Please, participate. + + +## Encoding/decoding speed + +Comparison with iconv module (1000 times 256kb, on Core i5/2.5 GHz). + + Operation\module iconv iconv-lite (this) + toEncoding('win1251') 19.57 mb/s 49.04 mb/s + fromEncoding('win1251') 16.39 mb/s 24.11 mb/s + + +## Notes + +This module is JavaScript-only, thus can be used in a sandboxed environment like [Cloud9](http://c9.io). + +Untranslatable characters are set to '?'. No transliteration is currently supported, pull requests are welcome. + +## Testing + + npm install --dev iconv-lite + vows + +## TODO + +* Support streaming character conversion, something like util.pipe(req, iconv.fromEncodingStream('latin1')). +* Add more encodings. +* Add transliteration (best fit char). +* Add tests and correct support of variable-byte encodings (currently work is delegated to node). diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 000000000..fd3681c80 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,564 @@ + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = function(options) { + return new DBCSCodec(options); +} + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(options) { + this.options = options; + if (!options) + throw new Error("DBCS codec is called without the data.") + if (!options.table) + throw new Error("Encoding '" + options.encodingName + "' has no data."); + + // Load tables. + var mappingTable = options.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = options.iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (options.encodeSkipVals) + for (var i = 0; i < options.encodeSkipVals.length; i++) { + var range = options.encodeSkipVals[i]; + for (var j = range.from; j <= range.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + for (var uChar in options.encodeAdd || {}) + this._setEncodeChar(uChar.charCodeAt(0), options.encodeAdd[uChar]); + + this.defCharSB = this.encodeTable[0][options.iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof options.gb18030 === 'function') { + this.gb18030 = options.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +// Public interface: create encoder and decoder objects. +// The methods (write, end) are simple functions to not inhibit optimizations. +DBCSCodec.prototype.encoder = function encoderDBCS(options) { + return { + // Methods + write: encoderDBCSWrite, + end: encoderDBCSEnd, + + // Encoder state + leadSurrogate: -1, + seqObj: undefined, + + // Static data + encodeTable: this.encodeTable, + encodeTableSeq: this.encodeTableSeq, + defaultCharSingleByte: this.defCharSB, + gb18030: this.gb18030, + + // Export for testing + findIdx: findIdx, + } +} + +DBCSCodec.prototype.decoder = function decoderDBCS(options) { + return { + // Methods + write: decoderDBCSWrite, + end: decoderDBCSEnd, + + // Decoder state + nodeIdx: 0, + prevBuf: new Buffer(0), + + // Static data + decodeTables: this.decodeTables, + decodeTableSeq: this.decodeTableSeq, + defaultCharUnicode: this.defaultCharUnicode, + gb18030: this.gb18030, + } +} + + + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.options.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.options.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.options.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.options.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Actual Encoding ========================================================== + + +function encoderDBCSWrite(str) { + var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +function encoderDBCSEnd() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = new Buffer(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + + +// == Actual Decoding ========================================================== + + +function decoderDBCSWrite(buf) { + var newBuf = new Buffer(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("Unknown table value when decoding: " + val); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +function decoderDBCSEnd() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = new Buffer(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += decoderDBCSWrite.call(this, buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 000000000..44be66c44 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,168 @@ + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows-31j': 'shiftjis', + 'x-sjis': 'shiftjis', + 'windows932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + 'isoir58': 'gbk', + + // Microsoft's CP936 is a subset and approximation of GBK. + // TODO: Euro = 0x80 in cp936, but not in GBK (where it's valid but undefined) + 'windows936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + }, + + 'chinese': 'gb18030', + + // TODO: Support GB18030 (~27000 chars + whole unicode mapping, cp54936) + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', + +}; \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 000000000..2cda91831 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,20 @@ + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + exports[enc] = module[enc]; +} diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 000000000..396f5800e --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,81 @@ + +// Export Node.js internal encodings. + +var utf16lebom = new Buffer([0xFF, 0xFE]); + +module.exports = { + // Encodings + utf8: { type: "_internal", enc: "utf8" }, + cesu8: { type: "_internal", enc: "utf8" }, + unicode11utf8: { type: "_internal", enc: "utf8" }, + ucs2: { type: "_internal", enc: "ucs2", bom: utf16lebom }, + utf16le:{ type: "_internal", enc: "ucs2", bom: utf16lebom }, + binary: { type: "_internal", enc: "binary" }, + base64: { type: "_internal", enc: "base64" }, + hex: { type: "_internal", enc: "hex" }, + + // Codec. + _internal: function(options) { + if (!options || !options.enc) + throw new Error("Internal codec is called without encoding type.") + + return { + encoder: options.enc == "base64" ? encoderBase64 : encoderInternal, + decoder: decoderInternal, + + enc: options.enc, + bom: options.bom, + }; + }, +}; + +// We use node.js internal decoder. It's signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + +function decoderInternal() { + return new StringDecoder(this.enc); +} + +// Encoder is mostly trivial + +function encoderInternal() { + return { + write: encodeInternal, + end: function() {}, + + enc: this.enc, + } +} + +function encodeInternal(str) { + return new Buffer(str, this.enc); +} + + +// Except base64 encoder, which must keep its state. + +function encoderBase64() { + return { + write: encodeBase64Write, + end: encodeBase64End, + + prevStr: '', + }; +} + +function encodeBase64Write(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return new Buffer(str, "base64"); +} + +function encodeBase64End() { + return new Buffer(this.prevStr, "base64"); +} + diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 000000000..c79defb83 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,76 @@ + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = function(options) { + if (!options) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256)) + throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (options.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + options.chars = asciiString + options.chars; + } + + var decodeBuf = new Buffer(options.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = new Buffer(65536); + encodeBuf.fill(options.iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < options.chars.length; i++) + encodeBuf[options.chars.charCodeAt(i)] = i; + + return { + encoder: encoderSBCS, + decoder: decoderSBCS, + + encodeBuf: encodeBuf, + decodeBuf: decodeBuf, + }; +} + +function encoderSBCS(options) { + return { + write: encoderSBCSWrite, + end: function() {}, + + encodeBuf: this.encodeBuf, + }; +} + +function encoderSBCSWrite(str) { + var buf = new Buffer(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + + +function decoderSBCS(options) { + return { + write: decoderSBCSWrite, + end: function() {}, + + decodeBuf: this.decodeBuf, + }; +} + +function decoderSBCSWrite(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = new Buffer(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0, _len = buf.length; i < _len; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 000000000..38082606f --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,450 @@ + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹ�ֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 000000000..74fb34bed --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,168 @@ + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix3.4": "ascii", + "ansix3.41968": "ascii", + "ansix3.41986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646.irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis620.25291": "tis620", + "tis620.25330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 000000000..3c3d3c2f7 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 000000000..49ddb9a1d --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 000000000..2022a007f --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 000000000..d8bc87178 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 000000000..4fa61ca11 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 000000000..85c693475 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 000000000..8abfa9f7b --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 000000000..5a3a43cf8 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 000000000..4cd425d62 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,202 @@ + + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = function(options) { + return { + encoder: utf16beEncoder, + decoder: utf16beDecoder, + + bom: new Buffer([0xFE, 0xFF]), + }; +}; + + +// -- Encoding + +function utf16beEncoder(options) { + return { + write: utf16beEncoderWrite, + end: function() {}, + } +} + +function utf16beEncoderWrite(str) { + var buf = new Buffer(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + + +// -- Decoding + +function utf16beDecoder(options) { + return { + write: utf16beDecoderWrite, + end: function() {}, + + overflowByte: -1, + }; +} + +function utf16beDecoderWrite(buf) { + if (buf.length == 0) + return ''; + + var buf2 = new Buffer(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16BE, according to RFC 2781, although it is against some industry practices, see +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {default: 'utf-16le'}); + +// Encoder prepends BOM and uses UTF-16BE. +// Endianness can also be changed: iconv.encode(str, 'utf16', {use: 'utf-16le'}); + +exports.utf16 = function(options) { + return { + encoder: utf16Encoder, + decoder: utf16Decoder, + + getCodec: options.iconv.getCodec, + }; +}; + +// -- Encoding + +function utf16Encoder(options) { + options = options || {}; + var codec = this.getCodec(options.use || 'utf-16be'); + if (!codec.bom) + throw new Error("iconv-lite: in UTF-16 encoder, 'use' parameter should be either UTF-16BE or UTF16-LE."); + + return { + write: utf16EncoderWrite, + end: utf16EncoderEnd, + + bom: codec.bom, + internalEncoder: codec.encoder(options), + }; +} + +function utf16EncoderWrite(str) { + var buf = this.internalEncoder.write(str); + + if (this.bom) { + buf = Buffer.concat([this.bom, buf]); + this.bom = null; + } + + return buf; +} + +function utf16EncoderEnd() { + return this.internalEncoder.end(); +} + + +// -- Decoding + +function utf16Decoder(options) { + return { + write: utf16DecoderWrite, + end: utf16DecoderEnd, + + internalDecoder: null, + initialBytes: [], + initialBytesLen: 0, + + options: options || {}, + getCodec: this.getCodec, + }; +} + +function utf16DecoderWrite(buf) { + if (this.internalDecoder) + return this.internalDecoder.write(buf); + + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need > 2 bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> decide endianness. + return utf16DecoderDecideEndianness.call(this); +} + +function utf16DecoderEnd() { + if (this.internalDecoder) + return this.internalDecoder.end(); + + var res = utf16DecoderDecideEndianness.call(this); + var trail; + + if (this.internalDecoder) + trail = this.internalDecoder.end(); + + return (trail && trail.length > 0) ? (res + trail) : res; +} + +function utf16DecoderDecideEndianness() { + var buf = Buffer.concat(this.initialBytes); + this.initialBytes.length = this.initialBytesLen = 0; + + if (buf.length < 2) + return ''; // Not a valid UTF-16 sequence anyway. + + // Default encoding. + var enc = this.options.default || 'utf-16be'; + + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) { // UTF-16BE BOM + enc = 'utf-16be'; buf = buf.slice(2); + } + else if (buf[0] == 0xFF && buf[1] == 0xFE) { // UTF-16LE BOM + enc = 'utf-16le'; buf = buf.slice(2); + } + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has spaces (U+0020), but the opposite (U+2000) is very uncommon. + // So, we count spaces as if it was LE or BE, and decide from that. + var spaces = [0, 0], // Counts of space chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] == 0x00 && buf[i+1] == 0x20) spaces[0]++; + if (buf[i] == 0x20 && buf[i+1] == 0x00) spaces[1]++; + } + + if (spaces[0] > 0 && spaces[1] == 0) + enc = 'utf-16be'; + else if (spaces[0] == 0 && spaces[1] > 0) + enc = 'utf-16le'; + } + + this.internalDecoder = this.getCodec(enc).decoder(this.options); + return this.internalDecoder.write(buf); +} + + diff --git a/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js b/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 000000000..740f766b3 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,284 @@ + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// Below is UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = function(options) { + return { + encoder: function utf7Encoder() { + return { + write: utf7EncoderWrite, + end: function() {}, + + iconv: options.iconv, + }; + }, + decoder: function utf7Decoder() { + return { + write: utf7DecoderWrite, + end: utf7DecoderEnd, + + iconv: options.iconv, + inBase64: false, + base64Accum: '', + }; + }, + }; +}; + + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function utf7EncoderWrite(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return new Buffer(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +function utf7DecoderWrite(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +function utf7DecoderEnd() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = function(options) { + return { + encoder: function utf7ImapEncoder() { + return { + write: utf7ImapEncoderWrite, + end: utf7ImapEncoderEnd, + + iconv: options.iconv, + inBase64: false, + base64Accum: new Buffer(6), + base64AccumIdx: 0, + }; + }, + decoder: function utf7ImapDecoder() { + return { + write: utf7ImapDecoderWrite, + end: utf7ImapDecoderEnd, + + iconv: options.iconv, + inBase64: false, + base64Accum: '', + }; + }, + }; +}; + + +function utf7ImapEncoderWrite(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = new Buffer(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +function utf7ImapEncoderEnd() { + var buf = new Buffer(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +function utf7ImapDecoderWrite(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +function utf7ImapDecoderEnd() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js b/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 000000000..000cee245 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,210 @@ + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return nodeNativeEncodings[enc && enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + start = +start || 0; + if (typeof end !== 'number') end = this.length; + + // Fastpath empty strings + if (+end == start) + return ''; + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Try to use original function when possible. + if (Buffer.isNativeEncoding(enc)) + return original.ReadableSetEncoding.call(this, enc); + + // Try to use our own decoder, it has the same interface. + this._readableState.decoder = iconv.getCodec(enc).decoder(options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/node_modules/body-parser/node_modules/iconv-lite/lib/index.js b/node_modules/body-parser/node_modules/iconv-lite/lib/index.js new file mode 100644 index 000000000..077558987 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,122 @@ + +var iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getCodec(encoding).encoder(options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getCodec(encoding).decoder(options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return (trail && trail.length > 0) ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); + + // Traverse iconv.encodings to find actual codec. + var codecData, codecOptions; + while (true) { + codecData = iconv._codecDataCache[enc]; + if (codecData) + return codecData; + + var codec = iconv.encodings[enc]; + + switch (typeof codec) { + case "string": // Direct alias to other encoding. + enc = codec; + break; + + case "object": // Alias with options. Can be layered. + if (!codecOptions) { + codecOptions = codec; + codecOptions.encodingName = enc; + } + else { + for (var key in codec) + codecOptions[key] = codec[key]; + } + + enc = codec.type; + break; + + case "function": // Codec itself. + if (!codecOptions) + codecOptions = { encodingName: enc }; + codecOptions.iconv = iconv; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codecData = codec.call(iconv.encodings, codecOptions); + + iconv._codecDataCache[codecOptions.encodingName] = codecData; // Save it to be reused later. + return codecData; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + diff --git a/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js b/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 000000000..0563731a1 --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,118 @@ +var Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getCodec(encoding).encoder(options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getCodec(encoding).decoder(options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/node_modules/body-parser/node_modules/iconv-lite/package.json b/node_modules/body-parser/node_modules/iconv-lite/package.json new file mode 100644 index 000000000..d51c931bc --- /dev/null +++ b/node_modules/body-parser/node_modules/iconv-lite/package.json @@ -0,0 +1,111 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.4", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": { + "name": "Alexander Shtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "contributors": [ + { + "name": "Jinwu Zhan", + "url": "https://github.com/jenkinv" + }, + { + "name": "Adamansky Anton", + "url": "https://github.com/adamansky" + }, + { + "name": "George Stagas", + "url": "https://github.com/stagas" + }, + { + "name": "Mike D Pilsbury", + "url": "https://github.com/pekim" + }, + { + "name": "Niggler", + "url": "https://github.com/Niggler" + }, + { + "name": "wychi", + "url": "https://github.com/wychi" + }, + { + "name": "David Kuo", + "url": "https://github.com/david50407" + }, + { + "name": "ChangZhuo Chen", + "url": "https://github.com/czchen" + }, + { + "name": "Lee Treveil", + "url": "https://github.com/leetreveil" + }, + { + "name": "Brian White", + "url": "https://github.com/mscdex" + }, + { + "name": "Mithgol", + "url": "https://github.com/Mithgol" + } + ], + "main": "./lib/index.js", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": { + "url": "https://github.com/ashtuchkin/iconv-lite/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./extend-node": false, + "./streams": false + }, + "devDependencies": { + "mocha": "*", + "request": "*", + "unorm": "*", + "errto": "*", + "async": "*", + "iconv": "~2.1.4" + }, + "gitHead": "9f0b0a7631d167322f47c2202aa3e5b090945131", + "_id": "iconv-lite@0.4.4", + "_shasum": "e95f2e41db0735fc21652f7827a5ee32e63c83a8", + "_from": "iconv-lite@0.4.4", + "_npmVersion": "1.4.14", + "_npmUser": { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "maintainers": [ + { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + } + ], + "dist": { + "shasum": "e95f2e41db0735fc21652f7827a5ee32e63c83a8", + "tarball": "http://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/media-typer/.npmignore b/node_modules/body-parser/node_modules/media-typer/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/body-parser/node_modules/media-typer/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/body-parser/node_modules/media-typer/HISTORY.md b/node_modules/body-parser/node_modules/media-typer/HISTORY.md new file mode 100644 index 000000000..215cc22d7 --- /dev/null +++ b/node_modules/body-parser/node_modules/media-typer/HISTORY.md @@ -0,0 +1,16 @@ +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/body-parser/node_modules/media-typer/README.md b/node_modules/body-parser/node_modules/media-typer/README.md new file mode 100644 index 000000000..338b7ce6c --- /dev/null +++ b/node_modules/body-parser/node_modules/media-typer/README.md @@ -0,0 +1,88 @@ +# media-typer + +[![NPM version](https://badge.fury.io/js/media-typer.svg)](https://badge.fury.io/js/media-typer) +[![Build Status](https://travis-ci.org/expressjs/media-typer.svg?branch=master)](https://travis-ci.org/expressjs/media-typer) +[![Coverage Status](https://img.shields.io/coveralls/expressjs/media-typer.svg?branch=master)](https://coveralls.io/r/expressjs/media-typer) + +Simple RFC 6838 media type parser + +## Installation + +```sh +$ npm install media-typer +``` + +## API + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + +```js +var obj = typer.parse('image/svg+xml; charset=utf-8') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` + +### typer.parse(req) + +```js +var obj = typer.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`typer.parse(req.headers['content-type'])`. + +### typer.parse(res) + +```js +var obj = typer.parse(req) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`typer.parse(res.getHeader('content-type'))`. + +### typer.format(obj) + +```js +var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/body-parser/node_modules/media-typer/index.js b/node_modules/body-parser/node_modules/media-typer/index.js new file mode 100644 index 000000000..cbf2e1780 --- /dev/null +++ b/node_modules/body-parser/node_modules/media-typer/index.js @@ -0,0 +1,261 @@ +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * SHT = + * CTL = + * OCTET = + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @api public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!tokenRegExp.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @api public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string + + var key + var match + var obj = splitType(type) + var params = {} + var value + + paramRegExp.lastIndex = index + + while (match = paramRegExp.exec(string)) { + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } + + params[key] = value + } + + obj.parameters = params + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @api private + */ + +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } + + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str + } + + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Simply "type/subtype+siffx" into parts. + * + * @param {string} string + * @return {Object} + * @api private + */ + +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + var obj = { + type: type, + subtype: subtype, + suffix: suffix + } + + return obj +} diff --git a/node_modules/body-parser/node_modules/media-typer/package.json b/node_modules/body-parser/node_modules/media-typer/package.json new file mode 100644 index 000000000..7ba61f98e --- /dev/null +++ b/node_modules/body-parser/node_modules/media-typer/package.json @@ -0,0 +1,52 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "0.2.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/media-typer" + }, + "devDependencies": { + "istanbul": "0.2.10", + "mocha": "~1.20.1", + "should": "~4.0.4" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "bugs": { + "url": "https://github.com/expressjs/media-typer/issues" + }, + "homepage": "https://github.com/expressjs/media-typer", + "_id": "media-typer@0.2.0", + "dist": { + "shasum": "d8a065213adfeaa2e76321a2b6dda36ff6335984", + "tarball": "http://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz" + }, + "_from": "media-typer@0.2.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "directories": {}, + "_shasum": "d8a065213adfeaa2e76321a2b6dda36ff6335984", + "_resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/on-finished/HISTORY.md b/node_modules/body-parser/node_modules/on-finished/HISTORY.md new file mode 100644 index 000000000..0aa241b19 --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/HISTORY.md @@ -0,0 +1,66 @@ +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/body-parser/node_modules/on-finished/LICENSE b/node_modules/body-parser/node_modules/on-finished/LICENSE new file mode 100644 index 000000000..5931fd23e --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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/body-parser/node_modules/on-finished/README.md b/node_modules/body-parser/node_modules/on-finished/README.md new file mode 100644 index 000000000..887b5c389 --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/README.md @@ -0,0 +1,90 @@ +# on-finished + +[![NPM Version](http://img.shields.io/npm/v/on-finished.svg?style=flat)](https://www.npmjs.org/package/on-finished) +[![Node.js Version](http://img.shields.io/badge/node.js->=_0.8-brightgreen.svg?style=flat)](http://nodejs.org/download/) +[![Build Status](http://img.shields.io/travis/jshttp/on-finished.svg?style=flat)](https://travis-ci.org/jshttp/on-finished) +[![Coverage Status](https://img.shields.io/coveralls/jshttp/on-finished.svg?style=flat)](https://coveralls.io/r/jshttp/on-finished) + +Execute a callback when a request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to to an error, the first argument will contain the error. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +```js +onFinished(res, function (err) { + // clean up open fds, etc. +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to to an error, the first argument will contain the error. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +```js +var data = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +### Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) diff --git a/node_modules/body-parser/node_modules/on-finished/index.js b/node_modules/body-parser/node_modules/on-finished/index.js new file mode 100644 index 000000000..a5055610b --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/index.js @@ -0,0 +1,127 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = onFinished; +module.exports.isFinished = isFinished; + +/** +* Module dependencies. +*/ + +var first = require('ee-first') + +/** +* Variables. +*/ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @api public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine is message is already finished. + * + * @param {object} msg + * @return {boolean} + * @api public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(!socket || msg.finished || !socket.writable) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(!socket || msg.complete || !socket.readable) + } + + // don't know + return undefined +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @api private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + var socket = msg.socket + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + + // finished on first event + first([ + [socket, 'error', 'close'], + [msg, 'end', 'finish'], + ], attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @api private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err) + } + } + + listener.queue = [] + + return listener +} diff --git a/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 000000000..a7ae8ee9b --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +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/body-parser/node_modules/on-finished/node_modules/ee-first/README.md b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 000000000..0ebc0aa4f --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,63 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 000000000..d0c48c994 --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,60 @@ + +module.exports = function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, cleanup) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + return function (fn) { + done = fn + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + done.apply(null, arguments) + } +} + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 000000000..54d04e1f6 --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.0.5", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/jonathanong/ee-first" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "1" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "c9d9a6881863c0d2fcc2e4ac99a170088c205304", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.0.5", + "_shasum": "8c9b212898d8cd9f1a9436650ce7be202c9e9ff0", + "_from": "ee-first@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "8c9b212898d8cd9f1a9436650ce7be202c9e9ff0", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.0.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/on-finished/package.json b/node_modules/body-parser/node_modules/on-finished/package.json new file mode 100644 index 000000000..b842572e9 --- /dev/null +++ b/node_modules/body-parser/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/jshttp/on-finished" + }, + "dependencies": { + "ee-first": "1.0.5" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.21.4" + }, + "engine": { + "node": ">= 0.8.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "1ad808e704e2aeda3a7464b78cacead2fb453727", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.1.0", + "_shasum": "0c539f09291e8ffadde0c8a25850fb2cedc7022d", + "_from": "on-finished@2.1.0", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "0c539f09291e8ffadde0c8a25850fb2cedc7022d", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/qs/.jshintignore b/node_modules/body-parser/node_modules/qs/.jshintignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/.jshintignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/body-parser/node_modules/qs/.jshintrc b/node_modules/body-parser/node_modules/qs/.jshintrc new file mode 100644 index 000000000..997b3f7d4 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/.jshintrc @@ -0,0 +1,10 @@ +{ + "node": true, + + "curly": true, + "latedef": true, + "quotmark": true, + "undef": true, + "unused": true, + "trailing": true +} diff --git a/node_modules/body-parser/node_modules/qs/.npmignore b/node_modules/body-parser/node_modules/qs/.npmignore new file mode 100644 index 000000000..7e1574dc5 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md diff --git a/node_modules/body-parser/node_modules/qs/.travis.yml b/node_modules/body-parser/node_modules/qs/.travis.yml new file mode 100644 index 000000000..c891dd0e0 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/.travis.yml @@ -0,0 +1,4 @@ +language: node_js + +node_js: + - 0.10 \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md b/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 000000000..892836159 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/node_modules/body-parser/node_modules/qs/LICENSE b/node_modules/body-parser/node_modules/qs/LICENSE new file mode 100644 index 000000000..d4569487a --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/node_modules/body-parser/node_modules/qs/Makefile b/node_modules/body-parser/node_modules/qs/Makefile new file mode 100644 index 000000000..600a700ec --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/Makefile @@ -0,0 +1,8 @@ +test: + @node node_modules/lab/bin/lab +test-cov: + @node node_modules/lab/bin/lab -t 100 +test-cov-html: + @node node_modules/lab/bin/lab -r html -o coverage.html + +.PHONY: test test-cov test-cov-html \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/qs/README.md b/node_modules/body-parser/node_modules/qs/README.md new file mode 100644 index 000000000..b8618877c --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/README.md @@ -0,0 +1,192 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [depth], [delimiter]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, depth)`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', 1); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', ';'); +// { a: 'b', c: 'd' } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [delimiter]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, they are always given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, ';'); +// 'a=b;c=d' +``` diff --git a/node_modules/body-parser/node_modules/qs/index.js b/node_modules/body-parser/node_modules/qs/index.js new file mode 100644 index 000000000..bb0a047c4 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/index.js @@ -0,0 +1 @@ +module.exports = require('./lib'); diff --git a/node_modules/body-parser/node_modules/qs/lib/index.js b/node_modules/body-parser/node_modules/qs/lib/index.js new file mode 100644 index 000000000..0e094933d --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/node_modules/body-parser/node_modules/qs/lib/parse.js b/node_modules/body-parser/node_modules/qs/lib/parse.js new file mode 100644 index 000000000..4a3fdd974 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/lib/parse.js @@ -0,0 +1,155 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parametersLimit: 1000 +}; + + +internals.parseValues = function (str, delimiter) { + + delimiter = typeof delimiter === 'string' ? delimiter : internals.delimiter; + + var obj = {}; + var parts = str.split(delimiter, internals.parametersLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!obj[key]) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj = {}; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val)); + } + else { + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + if (!isNaN(index) && + root !== cleanRoot && + index <= internals.arrayLimit) { + + obj = []; + obj[index] = internals.parseObject(chain, val); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, depth) { + + if (!key) { + return; + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Don't allow them to overwrite object prototype properties + + if (Object.prototype.hasOwnProperty(segment[1])) { + return; + } + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < depth) { + + ++i; + if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + keys.push(segment[1]); + } + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val); +}; + + +module.exports = function (str, depth, delimiter) { + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return {}; + } + + if (typeof depth !== 'number') { + delimiter = depth; + depth = internals.depth; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, delimiter) : Utils.clone(str); + var obj = {}; + + // Iterate over the keys and setup the new object + // + for (var key in tempObj) { + if (tempObj.hasOwnProperty(key)) { + var newObj = internals.parseKeys(key, tempObj[key], depth); + obj = Utils.merge(obj, newObj); + } + } + + return Utils.compact(obj); +}; diff --git a/node_modules/body-parser/node_modules/qs/lib/stringify.js b/node_modules/body-parser/node_modules/qs/lib/stringify.js new file mode 100644 index 000000000..1cc3df9fc --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/lib/stringify.js @@ -0,0 +1,55 @@ +// Load modules + + +// Declare internals + +var internals = { + delimiter: '&' +}; + + +internals.stringify = function (obj, prefix) { + + if (Buffer.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)]; + } + + var values = []; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']')); + } + } + + return values; +}; + + +module.exports = function (obj, delimiter) { + + delimiter = typeof delimiter === 'undefined' ? internals.delimiter : delimiter; + + var keys = []; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys = keys.concat(internals.stringify(obj[key], key)); + } + } + + return keys.join(delimiter); +}; diff --git a/node_modules/body-parser/node_modules/qs/lib/utils.js b/node_modules/body-parser/node_modules/qs/lib/utils.js new file mode 100644 index 000000000..3f5c149d5 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/lib/utils.js @@ -0,0 +1,133 @@ +// Load modules + + +// Declare internals + +var internals = {}; + + +exports.arrayToObject = function (source) { + + var obj = {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.clone = function (source) { + + if (typeof source !== 'object' || + source === null) { + + return source; + } + + if (Buffer.isBuffer(source)) { + return source.toString(); + } + + var obj = Array.isArray(source) ? [] : {}; + for (var i in source) { + if (source.hasOwnProperty(i)) { + obj[i] = exports.clone(source[i]); + } + } + + return obj; +}; + + +exports.merge = function (target, source) { + + if (!source) { + return target; + } + + var obj = exports.clone(target); + + if (Array.isArray(source)) { + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + if (typeof obj[i] === 'object') { + obj[i] = exports.merge(obj[i], source[i]); + } + else { + obj[i] = source[i]; + } + } + } + + return obj; + } + + if (Array.isArray(obj)) { + obj = exports.arrayToObject(obj); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (value && + typeof value === 'object') { + + if (!obj[key]) { + obj[key] = exports.clone(value); + } + else { + obj[key] = exports.merge(obj[key], value); + } + } + else { + obj[key] = value; + } + } + + return obj; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + + +exports.compact = function (obj) { + + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + var compacted = {}; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + if (Array.isArray(obj[key])) { + compacted[key] = []; + + for (var i = 0, l = obj[key].length; i < l; i++) { + if (typeof obj[key][i] !== 'undefined') { + compacted[key].push(obj[key][i]); + } + } + } + else { + compacted[key] = exports.compact(obj[key]); + } + } + } + + return compacted; +}; diff --git a/node_modules/body-parser/node_modules/qs/package.json b/node_modules/body-parser/node_modules/qs/package.json new file mode 100644 index 000000000..57164abd4 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/package.json @@ -0,0 +1,61 @@ +{ + "name": "qs", + "version": "1.2.2", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "lab": "3.x.x" + }, + "scripts": { + "test": "make test-cov" + }, + "repository": { + "type": "git", + "url": "https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "author": { + "name": "Nathan LaFreniere", + "email": "quitlahok@gmail.com" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/hapijs/qs/raw/master/LICENSE" + } + ], + "gitHead": "bd9455fea88d1c51a80dbf57ef0f99b4e553177d", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@1.2.2", + "_shasum": "19b57ff24dc2a99ce1f8bdf6afcda59f8ef61f88", + "_from": "qs@1.2.2", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "hueniverse", + "email": "eran@hueniverse.com" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "dist": { + "shasum": "19b57ff24dc2a99ce1f8bdf6afcda59f8ef61f88", + "tarball": "http://registry.npmjs.org/qs/-/qs-1.2.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-1.2.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/qs/test/parse.js b/node_modules/body-parser/node_modules/qs/test/parse.js new file mode 100644 index 000000000..c00e7becf --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/test/parse.js @@ -0,0 +1,301 @@ +// Load modules + +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var expect = Lab.expect; +var before = Lab.before; +var after = Lab.after; +var describe = Lab.experiment; +var it = Lab.test; + + +describe('#parse', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', 1)).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', 1)).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({foo: [ {a: 'a', b: 'b'}, {a: 'aa', b: 'bb'} ]}); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot override prototypes', function (done) { + + var obj = Qs.parse('toString=bad&bad[toString]=bad&constructor=bad'); + expect(typeof obj.toString).to.equal('function'); + expect(typeof obj.bad.toString).to.equal('function'); + expect(typeof obj.constructor).to.equal('function'); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]=')).to.deep.equal({ a: ['b', '', 'c', ''] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers to strings', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b.toString() }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', ';')).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-string objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', {})).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + "user[name]": {"pop[bob]": 3}, + "user[email]": null + }; + + var expected = { + "user": { + "name": {"pop[bob]": 3}, + "email": null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + "user[name]": {"pop[bob]": { "test": 3 }}, + "user[email]": null + }; + + var expected = { + "user": { + "name": {"pop[bob]": { "test": 3 }}, + "email": null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); +}); diff --git a/node_modules/body-parser/node_modules/qs/test/stringify.js b/node_modules/body-parser/node_modules/qs/test/stringify.js new file mode 100644 index 000000000..7bf1df4b5 --- /dev/null +++ b/node_modules/body-parser/node_modules/qs/test/stringify.js @@ -0,0 +1,129 @@ +// Load modules + +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var expect = Lab.expect; +var before = Lab.before; +var after = Lab.after; +var describe = Lab.experiment; +var it = Lab.test; + + +describe('#stringify', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('stringifies a complicated object', function (done) { + + expect(Qs.stringify({ a: { b: 'c', d: 'e' } })).to.equal('a%5Bb%5D=c&a%5Bd%5D=e'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null })).to.equal('a='); + expect(Qs.stringify({ a: { b: null } })).to.equal('a%5Bb%5D='); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + expect(Qs.stringify({ a: { b: undefined, c: null } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': 'q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b'})).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, ';')).to.equal('a=b;c=d'); + done(); + }); +}); diff --git a/node_modules/body-parser/node_modules/raw-body/.npmignore b/node_modules/body-parser/node_modules/raw-body/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/body-parser/node_modules/raw-body/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/body-parser/node_modules/raw-body/HISTORY.md b/node_modules/body-parser/node_modules/raw-body/HISTORY.md new file mode 100644 index 000000000..7772dcc67 --- /dev/null +++ b/node_modules/body-parser/node_modules/raw-body/HISTORY.md @@ -0,0 +1,114 @@ +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/node_modules/body-parser/node_modules/raw-body/README.md b/node_modules/body-parser/node_modules/raw-body/README.md new file mode 100644 index 000000000..e95d000bc --- /dev/null +++ b/node_modules/body-parser/node_modules/raw-body/README.md @@ -0,0 +1,103 @@ +# raw-body + +[![NPM version](https://badge.fury.io/js/raw-body.svg)](http://badge.fury.io/js/raw-body) +[![Build Status](https://travis-ci.org/stream-utils/raw-body.svg?branch=master)](https://travis-ci.org/stream-utils/raw-body) +[![Coverage Status](https://img.shields.io/coveralls/stream-utils/raw-body.svg?branch=master)](https://coveralls.io/r/stream-utils/raw-body) + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## API + +```js +var getRawBody = require('raw-body') +var typer = require('media-typer') + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: typer.parse(req.headers['content-type']).parameters.charset + }, function (err, string) { + if (err) + return next(err) + + req.text = string + next() + }) +}) +``` + +or in a Koa generator: + +```js +app.use(function* (next) { + var string = yield getRawBody(this.req, { + length: this.length, + limit: '1mb', + encoding: this.charset + }) +}) +``` + +### getRawBody(stream, [options], [callback]) + +Returns a thunk for yielding with generators. + +Options: + +- `length` - The length length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The requested encoding. + By default, a `Buffer` instance will be returned. + Most likely, you want `utf8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +`callback(err, res)`: + +- `err` - the following attributes will be defined if applicable: + + - `limit` - the limit in bytes + - `length` and `expected` - the expected length of the stream + - `received` - the received bytes + - `encoding` - the invalid encoding + - `status` and `statusCode` - the corresponding status code for the error + - `type` - either `entity.too.large`, `request.size.invalid`, `stream.encoding.set`, or `encoding.unsupported` + +- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, no handling is required if you send a response. +For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. + +## License + +The MIT License (MIT) + +Copyright (c) 2013 Jonathan Ong me@jongleberry.com + +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/body-parser/node_modules/raw-body/index.js b/node_modules/body-parser/node_modules/raw-body/index.js new file mode 100644 index 000000000..c430d2305 --- /dev/null +++ b/node_modules/body-parser/node_modules/raw-body/index.js @@ -0,0 +1,224 @@ +var bytes = require('bytes') +var iconv = require('iconv-lite') + +module.exports = function (stream, options, done) { + if (options === true || typeof options === 'string') { + // short cut for encoding + options = { + encoding: options + } + } + + options = options || {} + + if (typeof options === 'function') { + done = options + options = {} + } + + // get encoding + var encoding = options.encoding !== true + ? options.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = null + if (typeof options.limit === 'number') + limit = options.limit + if (typeof options.limit === 'string') + limit = bytes(options.limit) + + // convert the expected length to an integer + var length = null + if (options.length != null && !isNaN(options.length)) + length = parseInt(options.length, 10) + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + var err = makeError('request entity too large', 'entity.too.large') + err.status = err.statusCode = 413 + err.length = err.expected = length + err.limit = limit + cleanup() + halt(stream) + process.nextTick(function () { + done(err) + }) + return defer + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + var err = makeError('stream encoding should not be set', + 'stream.encoding.set') + err.status = err.statusCode = 500 + cleanup() + halt(stream) + process.nextTick(function () { + done(err) + }) + return defer + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + cleanup() + halt(stream) + process.nextTick(function () { + done(err) + }) + return defer + } + + var buffer = decoder + ? '' + : [] + + stream.on('data', onData) + stream.once('end', onEnd) + stream.once('error', onEnd) + stream.once('close', cleanup) + + return defer + + // yieldable support + function defer(fn) { + done = fn + } + + function onData(chunk) { + received += chunk.length + decoder + ? buffer += decoder.write(chunk) + : buffer.push(chunk) + + if (limit !== null && received > limit) { + var err = makeError('request entity too large', 'entity.too.large') + err.status = err.statusCode = 413 + err.received = received + err.limit = limit + cleanup() + halt(stream) + done(err) + } + } + + function onEnd(err) { + if (err) { + cleanup() + halt(stream) + done(err) + } else if (length !== null && received !== length) { + err = makeError('request size did not match content length', + 'request.size.invalid') + err.status = err.statusCode = 400 + err.received = received + err.length = err.expected = length + cleanup() + done(err) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + cleanup() + done(null, string) + } + } + + function cleanup() { + received = buffer = null + + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} + +function getDecoder(encoding) { + if (!encoding) return null + + try { + return iconv.getCodec(encoding).decoder() + } catch (e) { + var err = makeError('specified encoding unsupported', 'encoding.unsupported') + err.status = err.statusCode = 415 + err.encoding = encoding + throw err + } +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @api private + */ + +function halt(stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +// to create serializable errors you must re-set message so +// that it is enumerable and you must re configure the type +// property so that is writable and enumerable +function makeError(message, type) { + var error = new Error() + error.message = message + Object.defineProperty(error, 'type', { + value: type, + enumerable: true, + writable: true, + configurable: true + }) + return error +} + +/** + * Unpipe everything from a stream. + * + * @param {Object} stream + * @api private + */ + +/* istanbul ignore next: implementation differs between versions */ +function unpipe(stream) { + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/node_modules/body-parser/node_modules/raw-body/package.json b/node_modules/body-parser/node_modules/raw-body/package.json new file mode 100644 index 000000000..bb2130cb8 --- /dev/null +++ b/node_modules/body-parser/node_modules/raw-body/package.json @@ -0,0 +1,72 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "1.3.0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/stream-utils/raw-body" + }, + "dependencies": { + "bytes": "1", + "iconv-lite": "0.4.4" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.20.1", + "readable-stream": "~1.0.17", + "through2": "~0.5.1" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "bugs": { + "url": "https://github.com/stream-utils/raw-body/issues" + }, + "homepage": "https://github.com/stream-utils/raw-body", + "_id": "raw-body@1.3.0", + "dist": { + "shasum": "978230a156a5548f42eef14de22d0f4f610083d1", + "tarball": "http://registry.npmjs.org/raw-body/-/raw-body-1.3.0.tgz" + }, + "_from": "raw-body@1.3.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "directories": {}, + "_shasum": "978230a156a5548f42eef14de22d0f4f610083d1", + "_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-1.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/type-is/.npmignore b/node_modules/body-parser/node_modules/type-is/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/body-parser/node_modules/type-is/HISTORY.md b/node_modules/body-parser/node_modules/type-is/HISTORY.md new file mode 100644 index 000000000..b4c94bea2 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/HISTORY.md @@ -0,0 +1,54 @@ + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/body-parser/node_modules/type-is/README.md b/node_modules/body-parser/node_modules/type-is/README.md new file mode 100644 index 000000000..5d8b1668e --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/README.md @@ -0,0 +1,101 @@ +# type-is + +[![NPM version](https://badge.fury.io/js/type-is.svg)](https://badge.fury.io/js/type-is) +[![Build Status](https://travis-ci.org/expressjs/type-is.svg?branch=master)](https://travis-ci.org/expressjs/type-is) +[![Coverage Status](https://img.shields.io/coveralls/expressjs/type-is.svg?branch=master)](https://coveralls.io/r/expressjs/type-is) + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +#### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/json` or `application/*`. The full mime type will be returned if matched +- A suffix such as `+json`. This can be combined with a wildcard such as `*/vnd+json` or `application/*+json`. The full mime type will be returned if matched. + +`false` will be returned if no type matches. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); +var parse = require('body'); +var busboy = require('busboy'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) return next(); + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + break + case 'json': + // parse json body + break + case 'multipart': + // parse multipart body + break + default: + // 415 error code + } +} +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2013 Jonathan Ong me@jongleberry.com + +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/body-parser/node_modules/type-is/index.js b/node_modules/body-parser/node_modules/type-is/index.js new file mode 100644 index 000000000..315907ab7 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/index.js @@ -0,0 +1,230 @@ + +var typer = require('media-typer') +var mime = require('mime-types') + +module.exports = typeofrequest; +typeofrequest.is = typeis; +typeofrequest.hasBody = hasbody; +typeofrequest.normalize = normalize; +typeofrequest.match = mimeMatch; + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @return String + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + value = typenormalize(value) + + // no type or invalid + if (!value) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) return value; + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), value)) { + return type[0] === '+' || ~type.indexOf('*') + ? value + : type + } + } + + // no matches + return false; +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @api public + */ + +function hasbody(req) { + var headers = req.headers; + if ('transfer-encoding' in headers) return true; + var length = headers['content-length']; + if (!length) return false; + // no idea when this would happen, but `isNaN(null) === false` + if (isNaN(length)) return false; + return !!parseInt(length, 10); +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @api public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types); +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @api private + */ + +function normalize(type) { + switch (type) { + case 'urlencoded': return 'application/x-www-form-urlencoded'; + case 'multipart': + type = 'multipart/*'; + break; + } + + return type[0] === '+' || ~type.indexOf('/') + ? type + : mime.lookup(type) +} + +/** + * Check if `exected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @api private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // exact match + if (expected === actual) { + return true + } + + actual = actual.split('/'); + + if (expected[0] === '+') { + // support +suffix + return Boolean(actual[1]) + && expected.length <= actual[1].length + && expected === actual[1].substr(0 - expected.length) + } + + if (!~expected.indexOf('*')) return false; + + expected = expected.split('/'); + + if (expected[0] === '*') { + // support */yyy + return expected[1] === actual[1] + } + + if (expected[1] === '*') { + // support xxx/* + return expected[0] === actual[0] + } + + if (expected[1][0] === '*' && expected[1][1] === '+') { + // support xxx/*+zzz + return expected[0] === actual[0] + && expected[1].length <= actual[1].length + 1 + && expected[1].substr(1) === actual[1].substr(1 - expected[1].length) + } + + return false +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @api private + */ + +function typenormalize(value) { + try { + var type = typer.parse(value) + delete type.parameters + return typer.format(type) + } catch (err) { + return null + } +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.npmignore b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.npmignore new file mode 100644 index 000000000..919d51b41 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.npmignore @@ -0,0 +1,14 @@ +test +build.js + +# OS generated files # +###################### +.DS_Store* +# Icon? +ehthumbs.db +Thumbs.db + +# Node.js # +########### +node_modules +npm-debug.log diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.travis.yml b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.travis.yml new file mode 100644 index 000000000..73c85c65e --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" +matrix: + allow_failures: + - node_js: "0.11" + fast_finish: true +before_install: + # remove build script deps before install + - node -pe 'f="./package.json";p=require(f);d=p.devDependencies;for(k in d){if("co"===k.substr(0,2))delete d[k]}require("fs").writeFileSync(f,JSON.stringify(p,null,2))' diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 000000000..a7ae8ee9b --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +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/body-parser/node_modules/type-is/node_modules/mime-types/Makefile b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/Makefile new file mode 100644 index 000000000..ceaf011fb --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/Makefile @@ -0,0 +1,9 @@ + +build: + node --harmony-generators build.js + +test: + node test/mime.js + mocha --require should --reporter spec test/test.js + +.PHONY: build test diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 000000000..8e21ee104 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,101 @@ +# mime-types +[![NPM version](https://badge.fury.io/js/mime-types.svg)](https://badge.fury.io/js/mime-types) [![Build Status](https://travis-ci.org/expressjs/mime-types.svg?branch=master)](https://travis-ci.org/expressjs/mime-types) + +The ultimate javascript content-type utility. + +### Install + +```sh +$ npm install mime-types +``` + +#### Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus. Feel free to add more! +- Browser support via Browserify and Component by converting lists to JSON files. + +Otherwise, the API is compatible. + +### Adding Types + +If you'd like to add additional types, +simply create a PR adding the type to `custom.json` and +a reference link to the [sources](SOURCES.md). + +Do __NOT__ edit `mime.json` or `node.json`. +Those are pulled using `build.js`. +You should only touch `custom.json`. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### mime.types[extension] = type + +A map of content-types by extension. + +### mime.extensions[type] = [extensions] + +A map of extensions by content-type. + +### mime.define(types) + +Globally add definitions. +`types` must be an object of the form: + +```js +{ + "": [extensions...], + "": [extensions...] +} +``` + +See the `.json` files in `lib/` for examples. + +## License + +[MIT](LICENSE) diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/SOURCES.md b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/SOURCES.md new file mode 100644 index 000000000..1d650123e --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/SOURCES.md @@ -0,0 +1,17 @@ + +### Sources for custom types + +This is a list of sources for any custom mime types. +When adding custom mime types, please link to where you found the mime type, +even if it's from an unofficial source. + +- `text/coffeescript` - http://coffeescript.org/#scripts +- `text/x-handlebars-template` - https://handlebarsjs.com/#getting-started +- `text/x-sass` & `text/x-scss` - https://github.com/janlelis/rubybuntu-mime/blob/master/sass.xml +- `text.jsx` - http://facebook.github.io/react/docs/getting-started.html [[2]](https://github.com/facebook/react/blob/f230e0a03154e6f8a616e0da1fb3d97ffa1a6472/vendor/browser-transforms.js#L210) + +[Sources for node.json types](https://github.com/broofa/node-mime/blob/master/types/node.types) + +### Notes on weird types + +- `font/opentype` - This type is technically invalid according to the spec. No valid types begin with `font/`. No-one uses the official type of `application/vnd.ms-opentype` as the community standardized `application/x-font-otf`. However, chrome logs nonsense warnings unless opentype fonts are served with `font/opentype`. [[1]](http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts) diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/component.json b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/component.json new file mode 100644 index 000000000..fa67a6d23 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/component.json @@ -0,0 +1,16 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "0.1.0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "repository": "expressjs/mime-types", + "license": "MIT", + "main": "lib/index.js", + "scripts": ["lib/index.js"], + "json": ["mime.json", "node.json", "custom.json"] +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/custom.json b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/custom.json new file mode 100644 index 000000000..6137da34e --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/custom.json @@ -0,0 +1,27 @@ +{ + "text/jade": [ + "jade" + ], + "text/stylus": [ + "stylus", + "styl" + ], + "text/less": [ + "less" + ], + "text/x-sass": [ + "sass" + ], + "text/x-scss": [ + "scss" + ], + "text/coffeescript": [ + "coffee" + ], + "text/x-handlebars-template": [ + "hbs" + ], + "text/jsx": [ + "jsx" + ] +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/index.js b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/index.js new file mode 100644 index 000000000..cc2d15528 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/index.js @@ -0,0 +1,75 @@ + +// types[extension] = type +exports.types = Object.create(null) +// extensions[type] = [extensions] +exports.extensions = Object.create(null) +// define more mime types +exports.define = define + +// store the json files +exports.json = { + mime: require('./mime.json'), + node: require('./node.json'), + custom: require('./custom.json'), +} + +exports.lookup = function (string) { + if (!string || typeof string !== "string") return false + string = string.replace(/.*[\.\/\\]/, '').toLowerCase() + if (!string) return false + return exports.types[string] || false +} + +exports.extension = function (type) { + if (!type || typeof type !== "string") return false + type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/) + if (!type) return false + var exts = exports.extensions[type[1].toLowerCase()] + if (!exts || !exts.length) return false + return exts[0] +} + +// type has to be an exact mime type +exports.charset = function (type) { + // special cases + switch (type) { + case 'application/json': return 'UTF-8' + case 'application/javascript': return 'UTF-8' + } + + // default text/* to utf-8 + if (/^text\//.test(type)) return 'UTF-8' + + return false +} + +// backwards compatibility +exports.charsets = { + lookup: exports.charset +} + +exports.contentType = function (type) { + if (!type || typeof type !== "string") return false + if (!~type.indexOf('/')) type = exports.lookup(type) + if (!type) return false + if (!~type.indexOf('charset')) { + var charset = exports.charset(type) + if (charset) type += '; charset=' + charset.toLowerCase() + } + return type +} + +define(exports.json.mime) +define(exports.json.node) +define(exports.json.custom) + +function define(json) { + Object.keys(json).forEach(function (type) { + var exts = json[type] || [] + exports.extensions[type] = exports.extensions[type] || [] + exts.forEach(function (ext) { + if (!~exports.extensions[type].indexOf(ext)) exports.extensions[type].push(ext) + exports.types[ext] = type + }) + }) +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/mime.json b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/mime.json new file mode 100644 index 000000000..f445a86eb --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/mime.json @@ -0,0 +1,3317 @@ +{ + "application/1d-interleaved-parityfec": [], + "application/3gpp-ims+xml": [], + "application/activemessage": [], + "application/andrew-inset": [ + "ez" + ], + "application/applefile": [], + "application/applixware": [ + "aw" + ], + "application/atom+xml": [ + "atom" + ], + "application/atomcat+xml": [ + "atomcat" + ], + "application/atomicmail": [], + "application/atomsvc+xml": [ + "atomsvc" + ], + "application/auth-policy+xml": [], + "application/batch-smtp": [], + "application/beep+xml": [], + "application/calendar+xml": [], + "application/cals-1840": [], + "application/ccmp+xml": [], + "application/ccxml+xml": [ + "ccxml" + ], + "application/cdmi-capability": [ + "cdmia" + ], + "application/cdmi-container": [ + "cdmic" + ], + "application/cdmi-domain": [ + "cdmid" + ], + "application/cdmi-object": [ + "cdmio" + ], + "application/cdmi-queue": [ + "cdmiq" + ], + "application/cea-2018+xml": [], + "application/cellml+xml": [], + "application/cfw": [], + "application/cnrp+xml": [], + "application/commonground": [], + "application/conference-info+xml": [], + "application/cpl+xml": [], + "application/csta+xml": [], + "application/cstadata+xml": [], + "application/cu-seeme": [ + "cu" + ], + "application/cybercash": [], + "application/davmount+xml": [ + "davmount" + ], + "application/dca-rft": [], + "application/dec-dx": [], + "application/dialog-info+xml": [], + "application/dicom": [], + "application/dns": [], + "application/docbook+xml": [ + "dbk" + ], + "application/dskpp+xml": [], + "application/dssc+der": [ + "dssc" + ], + "application/dssc+xml": [ + "xdssc" + ], + "application/dvcs": [], + "application/ecmascript": [ + "ecma" + ], + "application/edi-consent": [], + "application/edi-x12": [], + "application/edifact": [], + "application/emma+xml": [ + "emma" + ], + "application/epp+xml": [], + "application/epub+zip": [ + "epub" + ], + "application/eshop": [], + "application/example": [], + "application/exi": [ + "exi" + ], + "application/fastinfoset": [], + "application/fastsoap": [], + "application/fits": [], + "application/font-tdpfr": [ + "pfr" + ], + "application/framework-attributes+xml": [], + "application/gml+xml": [ + "gml" + ], + "application/gpx+xml": [ + "gpx" + ], + "application/gxf": [ + "gxf" + ], + "application/h224": [], + "application/held+xml": [], + "application/http": [], + "application/hyperstudio": [ + "stk" + ], + "application/ibe-key-request+xml": [], + "application/ibe-pkg-reply+xml": [], + "application/ibe-pp-data": [], + "application/iges": [], + "application/im-iscomposing+xml": [], + "application/index": [], + "application/index.cmd": [], + "application/index.obj": [], + "application/index.response": [], + "application/index.vnd": [], + "application/inkml+xml": [ + "ink", + "inkml" + ], + "application/iotp": [], + "application/ipfix": [ + "ipfix" + ], + "application/ipp": [], + "application/isup": [], + "application/java-archive": [ + "jar" + ], + "application/java-serialized-object": [ + "ser" + ], + "application/java-vm": [ + "class" + ], + "application/javascript": [ + "js" + ], + "application/json": [ + "json" + ], + "application/jsonml+json": [ + "jsonml" + ], + "application/kpml-request+xml": [], + "application/kpml-response+xml": [], + "application/lost+xml": [ + "lostxml" + ], + "application/mac-binhex40": [ + "hqx" + ], + "application/mac-compactpro": [ + "cpt" + ], + "application/macwriteii": [], + "application/mads+xml": [ + "mads" + ], + "application/marc": [ + "mrc" + ], + "application/marcxml+xml": [ + "mrcx" + ], + "application/mathematica": [ + "ma", + "nb", + "mb" + ], + "application/mathml-content+xml": [], + "application/mathml-presentation+xml": [], + "application/mathml+xml": [ + "mathml" + ], + "application/mbms-associated-procedure-description+xml": [], + "application/mbms-deregister+xml": [], + "application/mbms-envelope+xml": [], + "application/mbms-msk+xml": [], + "application/mbms-msk-response+xml": [], + "application/mbms-protection-description+xml": [], + "application/mbms-reception-report+xml": [], + "application/mbms-register+xml": [], + "application/mbms-register-response+xml": [], + "application/mbms-user-service-description+xml": [], + "application/mbox": [ + "mbox" + ], + "application/media_control+xml": [], + "application/mediaservercontrol+xml": [ + "mscml" + ], + "application/metalink+xml": [ + "metalink" + ], + "application/metalink4+xml": [ + "meta4" + ], + "application/mets+xml": [ + "mets" + ], + "application/mikey": [], + "application/mods+xml": [ + "mods" + ], + "application/moss-keys": [], + "application/moss-signature": [], + "application/mosskey-data": [], + "application/mosskey-request": [], + "application/mp21": [ + "m21", + "mp21" + ], + "application/mp4": [ + "mp4s" + ], + "application/mpeg4-generic": [], + "application/mpeg4-iod": [], + "application/mpeg4-iod-xmt": [], + "application/msc-ivr+xml": [], + "application/msc-mixer+xml": [], + "application/msword": [ + "doc", + "dot" + ], + "application/mxf": [ + "mxf" + ], + "application/nasdata": [], + "application/news-checkgroups": [], + "application/news-groupinfo": [], + "application/news-transmission": [], + "application/nss": [], + "application/ocsp-request": [], + "application/ocsp-response": [], + "application/octet-stream": [ + "bin", + "dms", + "lrf", + "mar", + "so", + "dist", + "distz", + "pkg", + "bpk", + "dump", + "elc", + "deploy" + ], + "application/oda": [ + "oda" + ], + "application/oebps-package+xml": [ + "opf" + ], + "application/ogg": [ + "ogx" + ], + "application/omdoc+xml": [ + "omdoc" + ], + "application/onenote": [ + "onetoc", + "onetoc2", + "onetmp", + "onepkg" + ], + "application/oxps": [ + "oxps" + ], + "application/parityfec": [], + "application/patch-ops-error+xml": [ + "xer" + ], + "application/pdf": [ + "pdf" + ], + "application/pgp-encrypted": [ + "pgp" + ], + "application/pgp-keys": [], + "application/pgp-signature": [ + "asc", + "sig" + ], + "application/pics-rules": [ + "prf" + ], + "application/pidf+xml": [], + "application/pidf-diff+xml": [], + "application/pkcs10": [ + "p10" + ], + "application/pkcs7-mime": [ + "p7m", + "p7c" + ], + "application/pkcs7-signature": [ + "p7s" + ], + "application/pkcs8": [ + "p8" + ], + "application/pkix-attr-cert": [ + "ac" + ], + "application/pkix-cert": [ + "cer" + ], + "application/pkix-crl": [ + "crl" + ], + "application/pkix-pkipath": [ + "pkipath" + ], + "application/pkixcmp": [ + "pki" + ], + "application/pls+xml": [ + "pls" + ], + "application/poc-settings+xml": [], + "application/postscript": [ + "ai", + "eps", + "ps" + ], + "application/prs.alvestrand.titrax-sheet": [], + "application/prs.cww": [ + "cww" + ], + "application/prs.nprend": [], + "application/prs.plucker": [], + "application/prs.rdf-xml-crypt": [], + "application/prs.xsf+xml": [], + "application/pskc+xml": [ + "pskcxml" + ], + "application/qsig": [], + "application/rdf+xml": [ + "rdf" + ], + "application/reginfo+xml": [ + "rif" + ], + "application/relax-ng-compact-syntax": [ + "rnc" + ], + "application/remote-printing": [], + "application/resource-lists+xml": [ + "rl" + ], + "application/resource-lists-diff+xml": [ + "rld" + ], + "application/riscos": [], + "application/rlmi+xml": [], + "application/rls-services+xml": [ + "rs" + ], + "application/rpki-ghostbusters": [ + "gbr" + ], + "application/rpki-manifest": [ + "mft" + ], + "application/rpki-roa": [ + "roa" + ], + "application/rpki-updown": [], + "application/rsd+xml": [ + "rsd" + ], + "application/rss+xml": [ + "rss" + ], + "application/rtf": [ + "rtf" + ], + "application/rtx": [], + "application/samlassertion+xml": [], + "application/samlmetadata+xml": [], + "application/sbml+xml": [ + "sbml" + ], + "application/scvp-cv-request": [ + "scq" + ], + "application/scvp-cv-response": [ + "scs" + ], + "application/scvp-vp-request": [ + "spq" + ], + "application/scvp-vp-response": [ + "spp" + ], + "application/sdp": [ + "sdp" + ], + "application/set-payment": [], + "application/set-payment-initiation": [ + "setpay" + ], + "application/set-registration": [], + "application/set-registration-initiation": [ + "setreg" + ], + "application/sgml": [], + "application/sgml-open-catalog": [], + "application/shf+xml": [ + "shf" + ], + "application/sieve": [], + "application/simple-filter+xml": [], + "application/simple-message-summary": [], + "application/simplesymbolcontainer": [], + "application/slate": [], + "application/smil": [], + "application/smil+xml": [ + "smi", + "smil" + ], + "application/soap+fastinfoset": [], + "application/soap+xml": [], + "application/sparql-query": [ + "rq" + ], + "application/sparql-results+xml": [ + "srx" + ], + "application/spirits-event+xml": [], + "application/srgs": [ + "gram" + ], + "application/srgs+xml": [ + "grxml" + ], + "application/sru+xml": [ + "sru" + ], + "application/ssdl+xml": [ + "ssdl" + ], + "application/ssml+xml": [ + "ssml" + ], + "application/tamp-apex-update": [], + "application/tamp-apex-update-confirm": [], + "application/tamp-community-update": [], + "application/tamp-community-update-confirm": [], + "application/tamp-error": [], + "application/tamp-sequence-adjust": [], + "application/tamp-sequence-adjust-confirm": [], + "application/tamp-status-query": [], + "application/tamp-status-response": [], + "application/tamp-update": [], + "application/tamp-update-confirm": [], + "application/tei+xml": [ + "tei", + "teicorpus" + ], + "application/thraud+xml": [ + "tfi" + ], + "application/timestamp-query": [], + "application/timestamp-reply": [], + "application/timestamped-data": [ + "tsd" + ], + "application/tve-trigger": [], + "application/ulpfec": [], + "application/vcard+xml": [], + "application/vemmi": [], + "application/vividence.scriptfile": [], + "application/vnd.3gpp.bsf+xml": [], + "application/vnd.3gpp.pic-bw-large": [ + "plb" + ], + "application/vnd.3gpp.pic-bw-small": [ + "psb" + ], + "application/vnd.3gpp.pic-bw-var": [ + "pvb" + ], + "application/vnd.3gpp.sms": [], + "application/vnd.3gpp2.bcmcsinfo+xml": [], + "application/vnd.3gpp2.sms": [], + "application/vnd.3gpp2.tcap": [ + "tcap" + ], + "application/vnd.3m.post-it-notes": [ + "pwn" + ], + "application/vnd.accpac.simply.aso": [ + "aso" + ], + "application/vnd.accpac.simply.imp": [ + "imp" + ], + "application/vnd.acucobol": [ + "acu" + ], + "application/vnd.acucorp": [ + "atc", + "acutc" + ], + "application/vnd.adobe.air-application-installer-package+zip": [ + "air" + ], + "application/vnd.adobe.formscentral.fcdt": [ + "fcdt" + ], + "application/vnd.adobe.fxp": [ + "fxp", + "fxpl" + ], + "application/vnd.adobe.partial-upload": [], + "application/vnd.adobe.xdp+xml": [ + "xdp" + ], + "application/vnd.adobe.xfdf": [ + "xfdf" + ], + "application/vnd.aether.imp": [], + "application/vnd.ah-barcode": [], + "application/vnd.ahead.space": [ + "ahead" + ], + "application/vnd.airzip.filesecure.azf": [ + "azf" + ], + "application/vnd.airzip.filesecure.azs": [ + "azs" + ], + "application/vnd.amazon.ebook": [ + "azw" + ], + "application/vnd.americandynamics.acc": [ + "acc" + ], + "application/vnd.amiga.ami": [ + "ami" + ], + "application/vnd.amundsen.maze+xml": [], + "application/vnd.android.package-archive": [ + "apk" + ], + "application/vnd.anser-web-certificate-issue-initiation": [ + "cii" + ], + "application/vnd.anser-web-funds-transfer-initiation": [ + "fti" + ], + "application/vnd.antix.game-component": [ + "atx" + ], + "application/vnd.apple.installer+xml": [ + "mpkg" + ], + "application/vnd.apple.mpegurl": [ + "m3u8" + ], + "application/vnd.arastra.swi": [], + "application/vnd.aristanetworks.swi": [ + "swi" + ], + "application/vnd.astraea-software.iota": [ + "iota" + ], + "application/vnd.audiograph": [ + "aep" + ], + "application/vnd.autopackage": [], + "application/vnd.avistar+xml": [], + "application/vnd.blueice.multipass": [ + "mpm" + ], + "application/vnd.bluetooth.ep.oob": [], + "application/vnd.bmi": [ + "bmi" + ], + "application/vnd.businessobjects": [ + "rep" + ], + "application/vnd.cab-jscript": [], + "application/vnd.canon-cpdl": [], + "application/vnd.canon-lips": [], + "application/vnd.cendio.thinlinc.clientconf": [], + "application/vnd.chemdraw+xml": [ + "cdxml" + ], + "application/vnd.chipnuts.karaoke-mmd": [ + "mmd" + ], + "application/vnd.cinderella": [ + "cdy" + ], + "application/vnd.cirpack.isdn-ext": [], + "application/vnd.claymore": [ + "cla" + ], + "application/vnd.cloanto.rp9": [ + "rp9" + ], + "application/vnd.clonk.c4group": [ + "c4g", + "c4d", + "c4f", + "c4p", + "c4u" + ], + "application/vnd.cluetrust.cartomobile-config": [ + "c11amc" + ], + "application/vnd.cluetrust.cartomobile-config-pkg": [ + "c11amz" + ], + "application/vnd.collection+json": [], + "application/vnd.commerce-battelle": [], + "application/vnd.commonspace": [ + "csp" + ], + "application/vnd.contact.cmsg": [ + "cdbcmsg" + ], + "application/vnd.cosmocaller": [ + "cmc" + ], + "application/vnd.crick.clicker": [ + "clkx" + ], + "application/vnd.crick.clicker.keyboard": [ + "clkk" + ], + "application/vnd.crick.clicker.palette": [ + "clkp" + ], + "application/vnd.crick.clicker.template": [ + "clkt" + ], + "application/vnd.crick.clicker.wordbank": [ + "clkw" + ], + "application/vnd.criticaltools.wbs+xml": [ + "wbs" + ], + "application/vnd.ctc-posml": [ + "pml" + ], + "application/vnd.ctct.ws+xml": [], + "application/vnd.cups-pdf": [], + "application/vnd.cups-postscript": [], + "application/vnd.cups-ppd": [ + "ppd" + ], + "application/vnd.cups-raster": [], + "application/vnd.cups-raw": [], + "application/vnd.curl": [], + "application/vnd.curl.car": [ + "car" + ], + "application/vnd.curl.pcurl": [ + "pcurl" + ], + "application/vnd.cybank": [], + "application/vnd.dart": [ + "dart" + ], + "application/vnd.data-vision.rdz": [ + "rdz" + ], + "application/vnd.dece.data": [ + "uvf", + "uvvf", + "uvd", + "uvvd" + ], + "application/vnd.dece.ttml+xml": [ + "uvt", + "uvvt" + ], + "application/vnd.dece.unspecified": [ + "uvx", + "uvvx" + ], + "application/vnd.dece.zip": [ + "uvz", + "uvvz" + ], + "application/vnd.denovo.fcselayout-link": [ + "fe_launch" + ], + "application/vnd.dir-bi.plate-dl-nosuffix": [], + "application/vnd.dna": [ + "dna" + ], + "application/vnd.dolby.mlp": [ + "mlp" + ], + "application/vnd.dolby.mobile.1": [], + "application/vnd.dolby.mobile.2": [], + "application/vnd.dpgraph": [ + "dpg" + ], + "application/vnd.dreamfactory": [ + "dfac" + ], + "application/vnd.ds-keypoint": [ + "kpxx" + ], + "application/vnd.dvb.ait": [ + "ait" + ], + "application/vnd.dvb.dvbj": [], + "application/vnd.dvb.esgcontainer": [], + "application/vnd.dvb.ipdcdftnotifaccess": [], + "application/vnd.dvb.ipdcesgaccess": [], + "application/vnd.dvb.ipdcesgaccess2": [], + "application/vnd.dvb.ipdcesgpdd": [], + "application/vnd.dvb.ipdcroaming": [], + "application/vnd.dvb.iptv.alfec-base": [], + "application/vnd.dvb.iptv.alfec-enhancement": [], + "application/vnd.dvb.notif-aggregate-root+xml": [], + "application/vnd.dvb.notif-container+xml": [], + "application/vnd.dvb.notif-generic+xml": [], + "application/vnd.dvb.notif-ia-msglist+xml": [], + "application/vnd.dvb.notif-ia-registration-request+xml": [], + "application/vnd.dvb.notif-ia-registration-response+xml": [], + "application/vnd.dvb.notif-init+xml": [], + "application/vnd.dvb.pfr": [], + "application/vnd.dvb.service": [ + "svc" + ], + "application/vnd.dxr": [], + "application/vnd.dynageo": [ + "geo" + ], + "application/vnd.easykaraoke.cdgdownload": [], + "application/vnd.ecdis-update": [], + "application/vnd.ecowin.chart": [ + "mag" + ], + "application/vnd.ecowin.filerequest": [], + "application/vnd.ecowin.fileupdate": [], + "application/vnd.ecowin.series": [], + "application/vnd.ecowin.seriesrequest": [], + "application/vnd.ecowin.seriesupdate": [], + "application/vnd.emclient.accessrequest+xml": [], + "application/vnd.enliven": [ + "nml" + ], + "application/vnd.eprints.data+xml": [], + "application/vnd.epson.esf": [ + "esf" + ], + "application/vnd.epson.msf": [ + "msf" + ], + "application/vnd.epson.quickanime": [ + "qam" + ], + "application/vnd.epson.salt": [ + "slt" + ], + "application/vnd.epson.ssf": [ + "ssf" + ], + "application/vnd.ericsson.quickcall": [], + "application/vnd.eszigno3+xml": [ + "es3", + "et3" + ], + "application/vnd.etsi.aoc+xml": [], + "application/vnd.etsi.cug+xml": [], + "application/vnd.etsi.iptvcommand+xml": [], + "application/vnd.etsi.iptvdiscovery+xml": [], + "application/vnd.etsi.iptvprofile+xml": [], + "application/vnd.etsi.iptvsad-bc+xml": [], + "application/vnd.etsi.iptvsad-cod+xml": [], + "application/vnd.etsi.iptvsad-npvr+xml": [], + "application/vnd.etsi.iptvservice+xml": [], + "application/vnd.etsi.iptvsync+xml": [], + "application/vnd.etsi.iptvueprofile+xml": [], + "application/vnd.etsi.mcid+xml": [], + "application/vnd.etsi.overload-control-policy-dataset+xml": [], + "application/vnd.etsi.sci+xml": [], + "application/vnd.etsi.simservs+xml": [], + "application/vnd.etsi.tsl+xml": [], + "application/vnd.etsi.tsl.der": [], + "application/vnd.eudora.data": [], + "application/vnd.ezpix-album": [ + "ez2" + ], + "application/vnd.ezpix-package": [ + "ez3" + ], + "application/vnd.f-secure.mobile": [], + "application/vnd.fdf": [ + "fdf" + ], + "application/vnd.fdsn.mseed": [ + "mseed" + ], + "application/vnd.fdsn.seed": [ + "seed", + "dataless" + ], + "application/vnd.ffsns": [], + "application/vnd.fints": [], + "application/vnd.flographit": [ + "gph" + ], + "application/vnd.fluxtime.clip": [ + "ftc" + ], + "application/vnd.font-fontforge-sfd": [], + "application/vnd.framemaker": [ + "fm", + "frame", + "maker", + "book" + ], + "application/vnd.frogans.fnc": [ + "fnc" + ], + "application/vnd.frogans.ltf": [ + "ltf" + ], + "application/vnd.fsc.weblaunch": [ + "fsc" + ], + "application/vnd.fujitsu.oasys": [ + "oas" + ], + "application/vnd.fujitsu.oasys2": [ + "oa2" + ], + "application/vnd.fujitsu.oasys3": [ + "oa3" + ], + "application/vnd.fujitsu.oasysgp": [ + "fg5" + ], + "application/vnd.fujitsu.oasysprs": [ + "bh2" + ], + "application/vnd.fujixerox.art-ex": [], + "application/vnd.fujixerox.art4": [], + "application/vnd.fujixerox.hbpl": [], + "application/vnd.fujixerox.ddd": [ + "ddd" + ], + "application/vnd.fujixerox.docuworks": [ + "xdw" + ], + "application/vnd.fujixerox.docuworks.binder": [ + "xbd" + ], + "application/vnd.fut-misnet": [], + "application/vnd.fuzzysheet": [ + "fzs" + ], + "application/vnd.genomatix.tuxedo": [ + "txd" + ], + "application/vnd.geocube+xml": [], + "application/vnd.geogebra.file": [ + "ggb" + ], + "application/vnd.geogebra.tool": [ + "ggt" + ], + "application/vnd.geometry-explorer": [ + "gex", + "gre" + ], + "application/vnd.geonext": [ + "gxt" + ], + "application/vnd.geoplan": [ + "g2w" + ], + "application/vnd.geospace": [ + "g3w" + ], + "application/vnd.globalplatform.card-content-mgt": [], + "application/vnd.globalplatform.card-content-mgt-response": [], + "application/vnd.gmx": [ + "gmx" + ], + "application/vnd.google-earth.kml+xml": [ + "kml" + ], + "application/vnd.google-earth.kmz": [ + "kmz" + ], + "application/vnd.grafeq": [ + "gqf", + "gqs" + ], + "application/vnd.gridmp": [], + "application/vnd.groove-account": [ + "gac" + ], + "application/vnd.groove-help": [ + "ghf" + ], + "application/vnd.groove-identity-message": [ + "gim" + ], + "application/vnd.groove-injector": [ + "grv" + ], + "application/vnd.groove-tool-message": [ + "gtm" + ], + "application/vnd.groove-tool-template": [ + "tpl" + ], + "application/vnd.groove-vcard": [ + "vcg" + ], + "application/vnd.hal+json": [], + "application/vnd.hal+xml": [ + "hal" + ], + "application/vnd.handheld-entertainment+xml": [ + "zmm" + ], + "application/vnd.hbci": [ + "hbci" + ], + "application/vnd.hcl-bireports": [], + "application/vnd.hhe.lesson-player": [ + "les" + ], + "application/vnd.hp-hpgl": [ + "hpgl" + ], + "application/vnd.hp-hpid": [ + "hpid" + ], + "application/vnd.hp-hps": [ + "hps" + ], + "application/vnd.hp-jlyt": [ + "jlt" + ], + "application/vnd.hp-pcl": [ + "pcl" + ], + "application/vnd.hp-pclxl": [ + "pclxl" + ], + "application/vnd.httphone": [], + "application/vnd.hzn-3d-crossword": [], + "application/vnd.ibm.afplinedata": [], + "application/vnd.ibm.electronic-media": [], + "application/vnd.ibm.minipay": [ + "mpy" + ], + "application/vnd.ibm.modcap": [ + "afp", + "listafp", + "list3820" + ], + "application/vnd.ibm.rights-management": [ + "irm" + ], + "application/vnd.ibm.secure-container": [ + "sc" + ], + "application/vnd.iccprofile": [ + "icc", + "icm" + ], + "application/vnd.igloader": [ + "igl" + ], + "application/vnd.immervision-ivp": [ + "ivp" + ], + "application/vnd.immervision-ivu": [ + "ivu" + ], + "application/vnd.informedcontrol.rms+xml": [], + "application/vnd.informix-visionary": [], + "application/vnd.infotech.project": [], + "application/vnd.infotech.project+xml": [], + "application/vnd.innopath.wamp.notification": [], + "application/vnd.insors.igm": [ + "igm" + ], + "application/vnd.intercon.formnet": [ + "xpw", + "xpx" + ], + "application/vnd.intergeo": [ + "i2g" + ], + "application/vnd.intertrust.digibox": [], + "application/vnd.intertrust.nncp": [], + "application/vnd.intu.qbo": [ + "qbo" + ], + "application/vnd.intu.qfx": [ + "qfx" + ], + "application/vnd.iptc.g2.conceptitem+xml": [], + "application/vnd.iptc.g2.knowledgeitem+xml": [], + "application/vnd.iptc.g2.newsitem+xml": [], + "application/vnd.iptc.g2.newsmessage+xml": [], + "application/vnd.iptc.g2.packageitem+xml": [], + "application/vnd.iptc.g2.planningitem+xml": [], + "application/vnd.ipunplugged.rcprofile": [ + "rcprofile" + ], + "application/vnd.irepository.package+xml": [ + "irp" + ], + "application/vnd.is-xpr": [ + "xpr" + ], + "application/vnd.isac.fcs": [ + "fcs" + ], + "application/vnd.jam": [ + "jam" + ], + "application/vnd.japannet-directory-service": [], + "application/vnd.japannet-jpnstore-wakeup": [], + "application/vnd.japannet-payment-wakeup": [], + "application/vnd.japannet-registration": [], + "application/vnd.japannet-registration-wakeup": [], + "application/vnd.japannet-setstore-wakeup": [], + "application/vnd.japannet-verification": [], + "application/vnd.japannet-verification-wakeup": [], + "application/vnd.jcp.javame.midlet-rms": [ + "rms" + ], + "application/vnd.jisp": [ + "jisp" + ], + "application/vnd.joost.joda-archive": [ + "joda" + ], + "application/vnd.kahootz": [ + "ktz", + "ktr" + ], + "application/vnd.kde.karbon": [ + "karbon" + ], + "application/vnd.kde.kchart": [ + "chrt" + ], + "application/vnd.kde.kformula": [ + "kfo" + ], + "application/vnd.kde.kivio": [ + "flw" + ], + "application/vnd.kde.kontour": [ + "kon" + ], + "application/vnd.kde.kpresenter": [ + "kpr", + "kpt" + ], + "application/vnd.kde.kspread": [ + "ksp" + ], + "application/vnd.kde.kword": [ + "kwd", + "kwt" + ], + "application/vnd.kenameaapp": [ + "htke" + ], + "application/vnd.kidspiration": [ + "kia" + ], + "application/vnd.kinar": [ + "kne", + "knp" + ], + "application/vnd.koan": [ + "skp", + "skd", + "skt", + "skm" + ], + "application/vnd.kodak-descriptor": [ + "sse" + ], + "application/vnd.las.las+xml": [ + "lasxml" + ], + "application/vnd.liberty-request+xml": [], + "application/vnd.llamagraphics.life-balance.desktop": [ + "lbd" + ], + "application/vnd.llamagraphics.life-balance.exchange+xml": [ + "lbe" + ], + "application/vnd.lotus-1-2-3": [ + "123" + ], + "application/vnd.lotus-approach": [ + "apr" + ], + "application/vnd.lotus-freelance": [ + "pre" + ], + "application/vnd.lotus-notes": [ + "nsf" + ], + "application/vnd.lotus-organizer": [ + "org" + ], + "application/vnd.lotus-screencam": [ + "scm" + ], + "application/vnd.lotus-wordpro": [ + "lwp" + ], + "application/vnd.macports.portpkg": [ + "portpkg" + ], + "application/vnd.marlin.drm.actiontoken+xml": [], + "application/vnd.marlin.drm.conftoken+xml": [], + "application/vnd.marlin.drm.license+xml": [], + "application/vnd.marlin.drm.mdcf": [], + "application/vnd.mcd": [ + "mcd" + ], + "application/vnd.medcalcdata": [ + "mc1" + ], + "application/vnd.mediastation.cdkey": [ + "cdkey" + ], + "application/vnd.meridian-slingshot": [], + "application/vnd.mfer": [ + "mwf" + ], + "application/vnd.mfmp": [ + "mfm" + ], + "application/vnd.micrografx.flo": [ + "flo" + ], + "application/vnd.micrografx.igx": [ + "igx" + ], + "application/vnd.mif": [ + "mif" + ], + "application/vnd.minisoft-hp3000-save": [], + "application/vnd.mitsubishi.misty-guard.trustweb": [], + "application/vnd.mobius.daf": [ + "daf" + ], + "application/vnd.mobius.dis": [ + "dis" + ], + "application/vnd.mobius.mbk": [ + "mbk" + ], + "application/vnd.mobius.mqy": [ + "mqy" + ], + "application/vnd.mobius.msl": [ + "msl" + ], + "application/vnd.mobius.plc": [ + "plc" + ], + "application/vnd.mobius.txf": [ + "txf" + ], + "application/vnd.mophun.application": [ + "mpn" + ], + "application/vnd.mophun.certificate": [ + "mpc" + ], + "application/vnd.motorola.flexsuite": [], + "application/vnd.motorola.flexsuite.adsi": [], + "application/vnd.motorola.flexsuite.fis": [], + "application/vnd.motorola.flexsuite.gotap": [], + "application/vnd.motorola.flexsuite.kmr": [], + "application/vnd.motorola.flexsuite.ttc": [], + "application/vnd.motorola.flexsuite.wem": [], + "application/vnd.motorola.iprm": [], + "application/vnd.mozilla.xul+xml": [ + "xul" + ], + "application/vnd.ms-artgalry": [ + "cil" + ], + "application/vnd.ms-asf": [], + "application/vnd.ms-cab-compressed": [ + "cab" + ], + "application/vnd.ms-color.iccprofile": [], + "application/vnd.ms-excel": [ + "xls", + "xlm", + "xla", + "xlc", + "xlt", + "xlw" + ], + "application/vnd.ms-excel.addin.macroenabled.12": [ + "xlam" + ], + "application/vnd.ms-excel.sheet.binary.macroenabled.12": [ + "xlsb" + ], + "application/vnd.ms-excel.sheet.macroenabled.12": [ + "xlsm" + ], + "application/vnd.ms-excel.template.macroenabled.12": [ + "xltm" + ], + "application/vnd.ms-fontobject": [ + "eot" + ], + "application/vnd.ms-htmlhelp": [ + "chm" + ], + "application/vnd.ms-ims": [ + "ims" + ], + "application/vnd.ms-lrm": [ + "lrm" + ], + "application/vnd.ms-office.activex+xml": [], + "application/vnd.ms-officetheme": [ + "thmx" + ], + "application/vnd.ms-opentype": [], + "application/vnd.ms-package.obfuscated-opentype": [], + "application/vnd.ms-pki.seccat": [ + "cat" + ], + "application/vnd.ms-pki.stl": [ + "stl" + ], + "application/vnd.ms-playready.initiator+xml": [], + "application/vnd.ms-powerpoint": [ + "ppt", + "pps", + "pot" + ], + "application/vnd.ms-powerpoint.addin.macroenabled.12": [ + "ppam" + ], + "application/vnd.ms-powerpoint.presentation.macroenabled.12": [ + "pptm" + ], + "application/vnd.ms-powerpoint.slide.macroenabled.12": [ + "sldm" + ], + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": [ + "ppsm" + ], + "application/vnd.ms-powerpoint.template.macroenabled.12": [ + "potm" + ], + "application/vnd.ms-printing.printticket+xml": [], + "application/vnd.ms-project": [ + "mpp", + "mpt" + ], + "application/vnd.ms-tnef": [], + "application/vnd.ms-wmdrm.lic-chlg-req": [], + "application/vnd.ms-wmdrm.lic-resp": [], + "application/vnd.ms-wmdrm.meter-chlg-req": [], + "application/vnd.ms-wmdrm.meter-resp": [], + "application/vnd.ms-word.document.macroenabled.12": [ + "docm" + ], + "application/vnd.ms-word.template.macroenabled.12": [ + "dotm" + ], + "application/vnd.ms-works": [ + "wps", + "wks", + "wcm", + "wdb" + ], + "application/vnd.ms-wpl": [ + "wpl" + ], + "application/vnd.ms-xpsdocument": [ + "xps" + ], + "application/vnd.mseq": [ + "mseq" + ], + "application/vnd.msign": [], + "application/vnd.multiad.creator": [], + "application/vnd.multiad.creator.cif": [], + "application/vnd.music-niff": [], + "application/vnd.musician": [ + "mus" + ], + "application/vnd.muvee.style": [ + "msty" + ], + "application/vnd.mynfc": [ + "taglet" + ], + "application/vnd.ncd.control": [], + "application/vnd.ncd.reference": [], + "application/vnd.nervana": [], + "application/vnd.netfpx": [], + "application/vnd.neurolanguage.nlu": [ + "nlu" + ], + "application/vnd.nitf": [ + "ntf", + "nitf" + ], + "application/vnd.noblenet-directory": [ + "nnd" + ], + "application/vnd.noblenet-sealer": [ + "nns" + ], + "application/vnd.noblenet-web": [ + "nnw" + ], + "application/vnd.nokia.catalogs": [], + "application/vnd.nokia.conml+wbxml": [], + "application/vnd.nokia.conml+xml": [], + "application/vnd.nokia.isds-radio-presets": [], + "application/vnd.nokia.iptv.config+xml": [], + "application/vnd.nokia.landmark+wbxml": [], + "application/vnd.nokia.landmark+xml": [], + "application/vnd.nokia.landmarkcollection+xml": [], + "application/vnd.nokia.n-gage.ac+xml": [], + "application/vnd.nokia.n-gage.data": [ + "ngdat" + ], + "application/vnd.nokia.ncd": [], + "application/vnd.nokia.pcd+wbxml": [], + "application/vnd.nokia.pcd+xml": [], + "application/vnd.nokia.radio-preset": [ + "rpst" + ], + "application/vnd.nokia.radio-presets": [ + "rpss" + ], + "application/vnd.novadigm.edm": [ + "edm" + ], + "application/vnd.novadigm.edx": [ + "edx" + ], + "application/vnd.novadigm.ext": [ + "ext" + ], + "application/vnd.ntt-local.file-transfer": [], + "application/vnd.ntt-local.sip-ta_remote": [], + "application/vnd.ntt-local.sip-ta_tcp_stream": [], + "application/vnd.oasis.opendocument.chart": [ + "odc" + ], + "application/vnd.oasis.opendocument.chart-template": [ + "otc" + ], + "application/vnd.oasis.opendocument.database": [ + "odb" + ], + "application/vnd.oasis.opendocument.formula": [ + "odf" + ], + "application/vnd.oasis.opendocument.formula-template": [ + "odft" + ], + "application/vnd.oasis.opendocument.graphics": [ + "odg" + ], + "application/vnd.oasis.opendocument.graphics-template": [ + "otg" + ], + "application/vnd.oasis.opendocument.image": [ + "odi" + ], + "application/vnd.oasis.opendocument.image-template": [ + "oti" + ], + "application/vnd.oasis.opendocument.presentation": [ + "odp" + ], + "application/vnd.oasis.opendocument.presentation-template": [ + "otp" + ], + "application/vnd.oasis.opendocument.spreadsheet": [ + "ods" + ], + "application/vnd.oasis.opendocument.spreadsheet-template": [ + "ots" + ], + "application/vnd.oasis.opendocument.text": [ + "odt" + ], + "application/vnd.oasis.opendocument.text-master": [ + "odm" + ], + "application/vnd.oasis.opendocument.text-template": [ + "ott" + ], + "application/vnd.oasis.opendocument.text-web": [ + "oth" + ], + "application/vnd.obn": [], + "application/vnd.oftn.l10n+json": [], + "application/vnd.oipf.contentaccessdownload+xml": [], + "application/vnd.oipf.contentaccessstreaming+xml": [], + "application/vnd.oipf.cspg-hexbinary": [], + "application/vnd.oipf.dae.svg+xml": [], + "application/vnd.oipf.dae.xhtml+xml": [], + "application/vnd.oipf.mippvcontrolmessage+xml": [], + "application/vnd.oipf.pae.gem": [], + "application/vnd.oipf.spdiscovery+xml": [], + "application/vnd.oipf.spdlist+xml": [], + "application/vnd.oipf.ueprofile+xml": [], + "application/vnd.oipf.userprofile+xml": [], + "application/vnd.olpc-sugar": [ + "xo" + ], + "application/vnd.oma-scws-config": [], + "application/vnd.oma-scws-http-request": [], + "application/vnd.oma-scws-http-response": [], + "application/vnd.oma.bcast.associated-procedure-parameter+xml": [], + "application/vnd.oma.bcast.drm-trigger+xml": [], + "application/vnd.oma.bcast.imd+xml": [], + "application/vnd.oma.bcast.ltkm": [], + "application/vnd.oma.bcast.notification+xml": [], + "application/vnd.oma.bcast.provisioningtrigger": [], + "application/vnd.oma.bcast.sgboot": [], + "application/vnd.oma.bcast.sgdd+xml": [], + "application/vnd.oma.bcast.sgdu": [], + "application/vnd.oma.bcast.simple-symbol-container": [], + "application/vnd.oma.bcast.smartcard-trigger+xml": [], + "application/vnd.oma.bcast.sprov+xml": [], + "application/vnd.oma.bcast.stkm": [], + "application/vnd.oma.cab-address-book+xml": [], + "application/vnd.oma.cab-feature-handler+xml": [], + "application/vnd.oma.cab-pcc+xml": [], + "application/vnd.oma.cab-user-prefs+xml": [], + "application/vnd.oma.dcd": [], + "application/vnd.oma.dcdc": [], + "application/vnd.oma.dd2+xml": [ + "dd2" + ], + "application/vnd.oma.drm.risd+xml": [], + "application/vnd.oma.group-usage-list+xml": [], + "application/vnd.oma.pal+xml": [], + "application/vnd.oma.poc.detailed-progress-report+xml": [], + "application/vnd.oma.poc.final-report+xml": [], + "application/vnd.oma.poc.groups+xml": [], + "application/vnd.oma.poc.invocation-descriptor+xml": [], + "application/vnd.oma.poc.optimized-progress-report+xml": [], + "application/vnd.oma.push": [], + "application/vnd.oma.scidm.messages+xml": [], + "application/vnd.oma.xcap-directory+xml": [], + "application/vnd.omads-email+xml": [], + "application/vnd.omads-file+xml": [], + "application/vnd.omads-folder+xml": [], + "application/vnd.omaloc-supl-init": [], + "application/vnd.openofficeorg.extension": [ + "oxt" + ], + "application/vnd.openxmlformats-officedocument.custom-properties+xml": [], + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": [], + "application/vnd.openxmlformats-officedocument.drawing+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": [], + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": [], + "application/vnd.openxmlformats-officedocument.extended-properties+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.presentation": [ + "pptx" + ], + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.slide": [ + "sldx" + ], + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": [ + "ppsx" + ], + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.template": [ + "potx" + ], + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": [], + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [ + "xlsx" + ], + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": [ + "xltx" + ], + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": [], + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": [], + "application/vnd.openxmlformats-officedocument.theme+xml": [], + "application/vnd.openxmlformats-officedocument.themeoverride+xml": [], + "application/vnd.openxmlformats-officedocument.vmldrawing": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [ + "docx" + ], + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": [ + "dotx" + ], + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": [], + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": [], + "application/vnd.openxmlformats-package.core-properties+xml": [], + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": [], + "application/vnd.openxmlformats-package.relationships+xml": [], + "application/vnd.quobject-quoxdocument": [], + "application/vnd.osa.netdeploy": [], + "application/vnd.osgeo.mapguide.package": [ + "mgp" + ], + "application/vnd.osgi.bundle": [], + "application/vnd.osgi.dp": [ + "dp" + ], + "application/vnd.osgi.subsystem": [ + "esa" + ], + "application/vnd.otps.ct-kip+xml": [], + "application/vnd.palm": [ + "pdb", + "pqa", + "oprc" + ], + "application/vnd.paos.xml": [], + "application/vnd.pawaafile": [ + "paw" + ], + "application/vnd.pg.format": [ + "str" + ], + "application/vnd.pg.osasli": [ + "ei6" + ], + "application/vnd.piaccess.application-licence": [], + "application/vnd.picsel": [ + "efif" + ], + "application/vnd.pmi.widget": [ + "wg" + ], + "application/vnd.poc.group-advertisement+xml": [], + "application/vnd.pocketlearn": [ + "plf" + ], + "application/vnd.powerbuilder6": [ + "pbd" + ], + "application/vnd.powerbuilder6-s": [], + "application/vnd.powerbuilder7": [], + "application/vnd.powerbuilder7-s": [], + "application/vnd.powerbuilder75": [], + "application/vnd.powerbuilder75-s": [], + "application/vnd.preminet": [], + "application/vnd.previewsystems.box": [ + "box" + ], + "application/vnd.proteus.magazine": [ + "mgz" + ], + "application/vnd.publishare-delta-tree": [ + "qps" + ], + "application/vnd.pvi.ptid1": [ + "ptid" + ], + "application/vnd.pwg-multiplexed": [], + "application/vnd.pwg-xhtml-print+xml": [], + "application/vnd.qualcomm.brew-app-res": [], + "application/vnd.quark.quarkxpress": [ + "qxd", + "qxt", + "qwd", + "qwt", + "qxl", + "qxb" + ], + "application/vnd.radisys.moml+xml": [], + "application/vnd.radisys.msml+xml": [], + "application/vnd.radisys.msml-audit+xml": [], + "application/vnd.radisys.msml-audit-conf+xml": [], + "application/vnd.radisys.msml-audit-conn+xml": [], + "application/vnd.radisys.msml-audit-dialog+xml": [], + "application/vnd.radisys.msml-audit-stream+xml": [], + "application/vnd.radisys.msml-conf+xml": [], + "application/vnd.radisys.msml-dialog+xml": [], + "application/vnd.radisys.msml-dialog-base+xml": [], + "application/vnd.radisys.msml-dialog-fax-detect+xml": [], + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": [], + "application/vnd.radisys.msml-dialog-group+xml": [], + "application/vnd.radisys.msml-dialog-speech+xml": [], + "application/vnd.radisys.msml-dialog-transform+xml": [], + "application/vnd.rainstor.data": [], + "application/vnd.rapid": [], + "application/vnd.realvnc.bed": [ + "bed" + ], + "application/vnd.recordare.musicxml": [ + "mxl" + ], + "application/vnd.recordare.musicxml+xml": [ + "musicxml" + ], + "application/vnd.renlearn.rlprint": [], + "application/vnd.rig.cryptonote": [ + "cryptonote" + ], + "application/vnd.rim.cod": [ + "cod" + ], + "application/vnd.rn-realmedia": [ + "rm" + ], + "application/vnd.rn-realmedia-vbr": [ + "rmvb" + ], + "application/vnd.route66.link66+xml": [ + "link66" + ], + "application/vnd.rs-274x": [], + "application/vnd.ruckus.download": [], + "application/vnd.s3sms": [], + "application/vnd.sailingtracker.track": [ + "st" + ], + "application/vnd.sbm.cid": [], + "application/vnd.sbm.mid2": [], + "application/vnd.scribus": [], + "application/vnd.sealed.3df": [], + "application/vnd.sealed.csf": [], + "application/vnd.sealed.doc": [], + "application/vnd.sealed.eml": [], + "application/vnd.sealed.mht": [], + "application/vnd.sealed.net": [], + "application/vnd.sealed.ppt": [], + "application/vnd.sealed.tiff": [], + "application/vnd.sealed.xls": [], + "application/vnd.sealedmedia.softseal.html": [], + "application/vnd.sealedmedia.softseal.pdf": [], + "application/vnd.seemail": [ + "see" + ], + "application/vnd.sema": [ + "sema" + ], + "application/vnd.semd": [ + "semd" + ], + "application/vnd.semf": [ + "semf" + ], + "application/vnd.shana.informed.formdata": [ + "ifm" + ], + "application/vnd.shana.informed.formtemplate": [ + "itp" + ], + "application/vnd.shana.informed.interchange": [ + "iif" + ], + "application/vnd.shana.informed.package": [ + "ipk" + ], + "application/vnd.simtech-mindmapper": [ + "twd", + "twds" + ], + "application/vnd.smaf": [ + "mmf" + ], + "application/vnd.smart.notebook": [], + "application/vnd.smart.teacher": [ + "teacher" + ], + "application/vnd.software602.filler.form+xml": [], + "application/vnd.software602.filler.form-xml-zip": [], + "application/vnd.solent.sdkm+xml": [ + "sdkm", + "sdkd" + ], + "application/vnd.spotfire.dxp": [ + "dxp" + ], + "application/vnd.spotfire.sfs": [ + "sfs" + ], + "application/vnd.sss-cod": [], + "application/vnd.sss-dtf": [], + "application/vnd.sss-ntf": [], + "application/vnd.stardivision.calc": [ + "sdc" + ], + "application/vnd.stardivision.draw": [ + "sda" + ], + "application/vnd.stardivision.impress": [ + "sdd" + ], + "application/vnd.stardivision.math": [ + "smf" + ], + "application/vnd.stardivision.writer": [ + "sdw", + "vor" + ], + "application/vnd.stardivision.writer-global": [ + "sgl" + ], + "application/vnd.stepmania.package": [ + "smzip" + ], + "application/vnd.stepmania.stepchart": [ + "sm" + ], + "application/vnd.street-stream": [], + "application/vnd.sun.xml.calc": [ + "sxc" + ], + "application/vnd.sun.xml.calc.template": [ + "stc" + ], + "application/vnd.sun.xml.draw": [ + "sxd" + ], + "application/vnd.sun.xml.draw.template": [ + "std" + ], + "application/vnd.sun.xml.impress": [ + "sxi" + ], + "application/vnd.sun.xml.impress.template": [ + "sti" + ], + "application/vnd.sun.xml.math": [ + "sxm" + ], + "application/vnd.sun.xml.writer": [ + "sxw" + ], + "application/vnd.sun.xml.writer.global": [ + "sxg" + ], + "application/vnd.sun.xml.writer.template": [ + "stw" + ], + "application/vnd.sun.wadl+xml": [], + "application/vnd.sus-calendar": [ + "sus", + "susp" + ], + "application/vnd.svd": [ + "svd" + ], + "application/vnd.swiftview-ics": [], + "application/vnd.symbian.install": [ + "sis", + "sisx" + ], + "application/vnd.syncml+xml": [ + "xsm" + ], + "application/vnd.syncml.dm+wbxml": [ + "bdm" + ], + "application/vnd.syncml.dm+xml": [ + "xdm" + ], + "application/vnd.syncml.dm.notification": [], + "application/vnd.syncml.ds.notification": [], + "application/vnd.tao.intent-module-archive": [ + "tao" + ], + "application/vnd.tcpdump.pcap": [ + "pcap", + "cap", + "dmp" + ], + "application/vnd.tmobile-livetv": [ + "tmo" + ], + "application/vnd.trid.tpt": [ + "tpt" + ], + "application/vnd.triscape.mxs": [ + "mxs" + ], + "application/vnd.trueapp": [ + "tra" + ], + "application/vnd.truedoc": [], + "application/vnd.ubisoft.webplayer": [], + "application/vnd.ufdl": [ + "ufd", + "ufdl" + ], + "application/vnd.uiq.theme": [ + "utz" + ], + "application/vnd.umajin": [ + "umj" + ], + "application/vnd.unity": [ + "unityweb" + ], + "application/vnd.uoml+xml": [ + "uoml" + ], + "application/vnd.uplanet.alert": [], + "application/vnd.uplanet.alert-wbxml": [], + "application/vnd.uplanet.bearer-choice": [], + "application/vnd.uplanet.bearer-choice-wbxml": [], + "application/vnd.uplanet.cacheop": [], + "application/vnd.uplanet.cacheop-wbxml": [], + "application/vnd.uplanet.channel": [], + "application/vnd.uplanet.channel-wbxml": [], + "application/vnd.uplanet.list": [], + "application/vnd.uplanet.list-wbxml": [], + "application/vnd.uplanet.listcmd": [], + "application/vnd.uplanet.listcmd-wbxml": [], + "application/vnd.uplanet.signal": [], + "application/vnd.vcx": [ + "vcx" + ], + "application/vnd.vd-study": [], + "application/vnd.vectorworks": [], + "application/vnd.verimatrix.vcas": [], + "application/vnd.vidsoft.vidconference": [], + "application/vnd.visio": [ + "vsd", + "vst", + "vss", + "vsw" + ], + "application/vnd.visionary": [ + "vis" + ], + "application/vnd.vividence.scriptfile": [], + "application/vnd.vsf": [ + "vsf" + ], + "application/vnd.wap.sic": [], + "application/vnd.wap.slc": [], + "application/vnd.wap.wbxml": [ + "wbxml" + ], + "application/vnd.wap.wmlc": [ + "wmlc" + ], + "application/vnd.wap.wmlscriptc": [ + "wmlsc" + ], + "application/vnd.webturbo": [ + "wtb" + ], + "application/vnd.wfa.wsc": [], + "application/vnd.wmc": [], + "application/vnd.wmf.bootstrap": [], + "application/vnd.wolfram.mathematica": [], + "application/vnd.wolfram.mathematica.package": [], + "application/vnd.wolfram.player": [ + "nbp" + ], + "application/vnd.wordperfect": [ + "wpd" + ], + "application/vnd.wqd": [ + "wqd" + ], + "application/vnd.wrq-hp3000-labelled": [], + "application/vnd.wt.stf": [ + "stf" + ], + "application/vnd.wv.csp+wbxml": [], + "application/vnd.wv.csp+xml": [], + "application/vnd.wv.ssp+xml": [], + "application/vnd.xara": [ + "xar" + ], + "application/vnd.xfdl": [ + "xfdl" + ], + "application/vnd.xfdl.webform": [], + "application/vnd.xmi+xml": [], + "application/vnd.xmpie.cpkg": [], + "application/vnd.xmpie.dpkg": [], + "application/vnd.xmpie.plan": [], + "application/vnd.xmpie.ppkg": [], + "application/vnd.xmpie.xlim": [], + "application/vnd.yamaha.hv-dic": [ + "hvd" + ], + "application/vnd.yamaha.hv-script": [ + "hvs" + ], + "application/vnd.yamaha.hv-voice": [ + "hvp" + ], + "application/vnd.yamaha.openscoreformat": [ + "osf" + ], + "application/vnd.yamaha.openscoreformat.osfpvg+xml": [ + "osfpvg" + ], + "application/vnd.yamaha.remote-setup": [], + "application/vnd.yamaha.smaf-audio": [ + "saf" + ], + "application/vnd.yamaha.smaf-phrase": [ + "spf" + ], + "application/vnd.yamaha.through-ngn": [], + "application/vnd.yamaha.tunnel-udpencap": [], + "application/vnd.yellowriver-custom-menu": [ + "cmp" + ], + "application/vnd.zul": [ + "zir", + "zirz" + ], + "application/vnd.zzazz.deck+xml": [ + "zaz" + ], + "application/voicexml+xml": [ + "vxml" + ], + "application/vq-rtcpxr": [], + "application/watcherinfo+xml": [], + "application/whoispp-query": [], + "application/whoispp-response": [], + "application/widget": [ + "wgt" + ], + "application/winhlp": [ + "hlp" + ], + "application/wita": [], + "application/wordperfect5.1": [], + "application/wsdl+xml": [ + "wsdl" + ], + "application/wspolicy+xml": [ + "wspolicy" + ], + "application/x-7z-compressed": [ + "7z" + ], + "application/x-abiword": [ + "abw" + ], + "application/x-ace-compressed": [ + "ace" + ], + "application/x-amf": [], + "application/x-apple-diskimage": [ + "dmg" + ], + "application/x-authorware-bin": [ + "aab", + "x32", + "u32", + "vox" + ], + "application/x-authorware-map": [ + "aam" + ], + "application/x-authorware-seg": [ + "aas" + ], + "application/x-bcpio": [ + "bcpio" + ], + "application/x-bittorrent": [ + "torrent" + ], + "application/x-blorb": [ + "blb", + "blorb" + ], + "application/x-bzip": [ + "bz" + ], + "application/x-bzip2": [ + "bz2", + "boz" + ], + "application/x-cbr": [ + "cbr", + "cba", + "cbt", + "cbz", + "cb7" + ], + "application/x-cdlink": [ + "vcd" + ], + "application/x-cfs-compressed": [ + "cfs" + ], + "application/x-chat": [ + "chat" + ], + "application/x-chess-pgn": [ + "pgn" + ], + "application/x-conference": [ + "nsc" + ], + "application/x-compress": [], + "application/x-cpio": [ + "cpio" + ], + "application/x-csh": [ + "csh" + ], + "application/x-debian-package": [ + "deb", + "udeb" + ], + "application/x-dgc-compressed": [ + "dgc" + ], + "application/x-director": [ + "dir", + "dcr", + "dxr", + "cst", + "cct", + "cxt", + "w3d", + "fgd", + "swa" + ], + "application/x-doom": [ + "wad" + ], + "application/x-dtbncx+xml": [ + "ncx" + ], + "application/x-dtbook+xml": [ + "dtb" + ], + "application/x-dtbresource+xml": [ + "res" + ], + "application/x-dvi": [ + "dvi" + ], + "application/x-envoy": [ + "evy" + ], + "application/x-eva": [ + "eva" + ], + "application/x-font-bdf": [ + "bdf" + ], + "application/x-font-dos": [], + "application/x-font-framemaker": [], + "application/x-font-ghostscript": [ + "gsf" + ], + "application/x-font-libgrx": [], + "application/x-font-linux-psf": [ + "psf" + ], + "application/x-font-otf": [ + "otf" + ], + "application/x-font-pcf": [ + "pcf" + ], + "application/x-font-snf": [ + "snf" + ], + "application/x-font-speedo": [], + "application/x-font-sunos-news": [], + "application/x-font-ttf": [ + "ttf", + "ttc" + ], + "application/x-font-type1": [ + "pfa", + "pfb", + "pfm", + "afm" + ], + "application/font-woff": [ + "woff" + ], + "application/x-font-vfont": [], + "application/x-freearc": [ + "arc" + ], + "application/x-futuresplash": [ + "spl" + ], + "application/x-gca-compressed": [ + "gca" + ], + "application/x-glulx": [ + "ulx" + ], + "application/x-gnumeric": [ + "gnumeric" + ], + "application/x-gramps-xml": [ + "gramps" + ], + "application/x-gtar": [ + "gtar" + ], + "application/x-gzip": [], + "application/x-hdf": [ + "hdf" + ], + "application/x-install-instructions": [ + "install" + ], + "application/x-iso9660-image": [ + "iso" + ], + "application/x-java-jnlp-file": [ + "jnlp" + ], + "application/x-latex": [ + "latex" + ], + "application/x-lzh-compressed": [ + "lzh", + "lha" + ], + "application/x-mie": [ + "mie" + ], + "application/x-mobipocket-ebook": [ + "prc", + "mobi" + ], + "application/x-ms-application": [ + "application" + ], + "application/x-ms-shortcut": [ + "lnk" + ], + "application/x-ms-wmd": [ + "wmd" + ], + "application/x-ms-wmz": [ + "wmz" + ], + "application/x-ms-xbap": [ + "xbap" + ], + "application/x-msaccess": [ + "mdb" + ], + "application/x-msbinder": [ + "obd" + ], + "application/x-mscardfile": [ + "crd" + ], + "application/x-msclip": [ + "clp" + ], + "application/x-msdownload": [ + "exe", + "dll", + "com", + "bat", + "msi" + ], + "application/x-msmediaview": [ + "mvb", + "m13", + "m14" + ], + "application/x-msmetafile": [ + "wmf", + "wmz", + "emf", + "emz" + ], + "application/x-msmoney": [ + "mny" + ], + "application/x-mspublisher": [ + "pub" + ], + "application/x-msschedule": [ + "scd" + ], + "application/x-msterminal": [ + "trm" + ], + "application/x-mswrite": [ + "wri" + ], + "application/x-netcdf": [ + "nc", + "cdf" + ], + "application/x-nzb": [ + "nzb" + ], + "application/x-pkcs12": [ + "p12", + "pfx" + ], + "application/x-pkcs7-certificates": [ + "p7b", + "spc" + ], + "application/x-pkcs7-certreqresp": [ + "p7r" + ], + "application/x-rar-compressed": [ + "rar" + ], + "application/x-research-info-systems": [ + "ris" + ], + "application/x-sh": [ + "sh" + ], + "application/x-shar": [ + "shar" + ], + "application/x-shockwave-flash": [ + "swf" + ], + "application/x-silverlight-app": [ + "xap" + ], + "application/x-sql": [ + "sql" + ], + "application/x-stuffit": [ + "sit" + ], + "application/x-stuffitx": [ + "sitx" + ], + "application/x-subrip": [ + "srt" + ], + "application/x-sv4cpio": [ + "sv4cpio" + ], + "application/x-sv4crc": [ + "sv4crc" + ], + "application/x-t3vm-image": [ + "t3" + ], + "application/x-tads": [ + "gam" + ], + "application/x-tar": [ + "tar" + ], + "application/x-tcl": [ + "tcl" + ], + "application/x-tex": [ + "tex" + ], + "application/x-tex-tfm": [ + "tfm" + ], + "application/x-texinfo": [ + "texinfo", + "texi" + ], + "application/x-tgif": [ + "obj" + ], + "application/x-ustar": [ + "ustar" + ], + "application/x-wais-source": [ + "src" + ], + "application/x-x509-ca-cert": [ + "der", + "crt" + ], + "application/x-xfig": [ + "fig" + ], + "application/x-xliff+xml": [ + "xlf" + ], + "application/x-xpinstall": [ + "xpi" + ], + "application/x-xz": [ + "xz" + ], + "application/x-zmachine": [ + "z1", + "z2", + "z3", + "z4", + "z5", + "z6", + "z7", + "z8" + ], + "application/x400-bp": [], + "application/xaml+xml": [ + "xaml" + ], + "application/xcap-att+xml": [], + "application/xcap-caps+xml": [], + "application/xcap-diff+xml": [ + "xdf" + ], + "application/xcap-el+xml": [], + "application/xcap-error+xml": [], + "application/xcap-ns+xml": [], + "application/xcon-conference-info-diff+xml": [], + "application/xcon-conference-info+xml": [], + "application/xenc+xml": [ + "xenc" + ], + "application/xhtml+xml": [ + "xhtml", + "xht" + ], + "application/xhtml-voice+xml": [], + "application/xml": [ + "xml", + "xsl" + ], + "application/xml-dtd": [ + "dtd" + ], + "application/xml-external-parsed-entity": [], + "application/xmpp+xml": [], + "application/xop+xml": [ + "xop" + ], + "application/xproc+xml": [ + "xpl" + ], + "application/xslt+xml": [ + "xslt" + ], + "application/xspf+xml": [ + "xspf" + ], + "application/xv+xml": [ + "mxml", + "xhvml", + "xvml", + "xvm" + ], + "application/yang": [ + "yang" + ], + "application/yin+xml": [ + "yin" + ], + "application/zip": [ + "zip" + ], + "audio/1d-interleaved-parityfec": [], + "audio/32kadpcm": [], + "audio/3gpp": [], + "audio/3gpp2": [], + "audio/ac3": [], + "audio/adpcm": [ + "adp" + ], + "audio/amr": [], + "audio/amr-wb": [], + "audio/amr-wb+": [], + "audio/asc": [], + "audio/atrac-advanced-lossless": [], + "audio/atrac-x": [], + "audio/atrac3": [], + "audio/basic": [ + "au", + "snd" + ], + "audio/bv16": [], + "audio/bv32": [], + "audio/clearmode": [], + "audio/cn": [], + "audio/dat12": [], + "audio/dls": [], + "audio/dsr-es201108": [], + "audio/dsr-es202050": [], + "audio/dsr-es202211": [], + "audio/dsr-es202212": [], + "audio/dv": [], + "audio/dvi4": [], + "audio/eac3": [], + "audio/evrc": [], + "audio/evrc-qcp": [], + "audio/evrc0": [], + "audio/evrc1": [], + "audio/evrcb": [], + "audio/evrcb0": [], + "audio/evrcb1": [], + "audio/evrcwb": [], + "audio/evrcwb0": [], + "audio/evrcwb1": [], + "audio/example": [], + "audio/fwdred": [], + "audio/g719": [], + "audio/g722": [], + "audio/g7221": [], + "audio/g723": [], + "audio/g726-16": [], + "audio/g726-24": [], + "audio/g726-32": [], + "audio/g726-40": [], + "audio/g728": [], + "audio/g729": [], + "audio/g7291": [], + "audio/g729d": [], + "audio/g729e": [], + "audio/gsm": [], + "audio/gsm-efr": [], + "audio/gsm-hr-08": [], + "audio/ilbc": [], + "audio/ip-mr_v2.5": [], + "audio/isac": [], + "audio/l16": [], + "audio/l20": [], + "audio/l24": [], + "audio/l8": [], + "audio/lpc": [], + "audio/midi": [ + "mid", + "midi", + "kar", + "rmi" + ], + "audio/mobile-xmf": [], + "audio/mp4": [ + "mp4a" + ], + "audio/mp4a-latm": [], + "audio/mpa": [], + "audio/mpa-robust": [], + "audio/mpeg": [ + "mpga", + "mp2", + "mp2a", + "mp3", + "m2a", + "m3a" + ], + "audio/mpeg4-generic": [], + "audio/musepack": [], + "audio/ogg": [ + "oga", + "ogg", + "spx" + ], + "audio/opus": [], + "audio/parityfec": [], + "audio/pcma": [], + "audio/pcma-wb": [], + "audio/pcmu-wb": [], + "audio/pcmu": [], + "audio/prs.sid": [], + "audio/qcelp": [], + "audio/red": [], + "audio/rtp-enc-aescm128": [], + "audio/rtp-midi": [], + "audio/rtx": [], + "audio/s3m": [ + "s3m" + ], + "audio/silk": [ + "sil" + ], + "audio/smv": [], + "audio/smv0": [], + "audio/smv-qcp": [], + "audio/sp-midi": [], + "audio/speex": [], + "audio/t140c": [], + "audio/t38": [], + "audio/telephone-event": [], + "audio/tone": [], + "audio/uemclip": [], + "audio/ulpfec": [], + "audio/vdvi": [], + "audio/vmr-wb": [], + "audio/vnd.3gpp.iufp": [], + "audio/vnd.4sb": [], + "audio/vnd.audiokoz": [], + "audio/vnd.celp": [], + "audio/vnd.cisco.nse": [], + "audio/vnd.cmles.radio-events": [], + "audio/vnd.cns.anp1": [], + "audio/vnd.cns.inf1": [], + "audio/vnd.dece.audio": [ + "uva", + "uvva" + ], + "audio/vnd.digital-winds": [ + "eol" + ], + "audio/vnd.dlna.adts": [], + "audio/vnd.dolby.heaac.1": [], + "audio/vnd.dolby.heaac.2": [], + "audio/vnd.dolby.mlp": [], + "audio/vnd.dolby.mps": [], + "audio/vnd.dolby.pl2": [], + "audio/vnd.dolby.pl2x": [], + "audio/vnd.dolby.pl2z": [], + "audio/vnd.dolby.pulse.1": [], + "audio/vnd.dra": [ + "dra" + ], + "audio/vnd.dts": [ + "dts" + ], + "audio/vnd.dts.hd": [ + "dtshd" + ], + "audio/vnd.dvb.file": [], + "audio/vnd.everad.plj": [], + "audio/vnd.hns.audio": [], + "audio/vnd.lucent.voice": [ + "lvp" + ], + "audio/vnd.ms-playready.media.pya": [ + "pya" + ], + "audio/vnd.nokia.mobile-xmf": [], + "audio/vnd.nortel.vbk": [], + "audio/vnd.nuera.ecelp4800": [ + "ecelp4800" + ], + "audio/vnd.nuera.ecelp7470": [ + "ecelp7470" + ], + "audio/vnd.nuera.ecelp9600": [ + "ecelp9600" + ], + "audio/vnd.octel.sbc": [], + "audio/vnd.qcelp": [], + "audio/vnd.rhetorex.32kadpcm": [], + "audio/vnd.rip": [ + "rip" + ], + "audio/vnd.sealedmedia.softseal.mpeg": [], + "audio/vnd.vmx.cvsd": [], + "audio/vorbis": [], + "audio/vorbis-config": [], + "audio/webm": [ + "weba" + ], + "audio/x-aac": [ + "aac" + ], + "audio/x-aiff": [ + "aif", + "aiff", + "aifc" + ], + "audio/x-caf": [ + "caf" + ], + "audio/x-flac": [ + "flac" + ], + "audio/x-matroska": [ + "mka" + ], + "audio/x-mpegurl": [ + "m3u" + ], + "audio/x-ms-wax": [ + "wax" + ], + "audio/x-ms-wma": [ + "wma" + ], + "audio/x-pn-realaudio": [ + "ram", + "ra" + ], + "audio/x-pn-realaudio-plugin": [ + "rmp" + ], + "audio/x-tta": [], + "audio/x-wav": [ + "wav" + ], + "audio/xm": [ + "xm" + ], + "chemical/x-cdx": [ + "cdx" + ], + "chemical/x-cif": [ + "cif" + ], + "chemical/x-cmdf": [ + "cmdf" + ], + "chemical/x-cml": [ + "cml" + ], + "chemical/x-csml": [ + "csml" + ], + "chemical/x-pdb": [], + "chemical/x-xyz": [ + "xyz" + ], + "image/bmp": [ + "bmp" + ], + "image/cgm": [ + "cgm" + ], + "image/example": [], + "image/fits": [], + "image/g3fax": [ + "g3" + ], + "image/gif": [ + "gif" + ], + "image/ief": [ + "ief" + ], + "image/jp2": [], + "image/jpeg": [ + "jpeg", + "jpg", + "jpe" + ], + "image/jpm": [], + "image/jpx": [], + "image/ktx": [ + "ktx" + ], + "image/naplps": [], + "image/png": [ + "png" + ], + "image/prs.btif": [ + "btif" + ], + "image/prs.pti": [], + "image/sgi": [ + "sgi" + ], + "image/svg+xml": [ + "svg", + "svgz" + ], + "image/t38": [], + "image/tiff": [ + "tiff", + "tif" + ], + "image/tiff-fx": [], + "image/vnd.adobe.photoshop": [ + "psd" + ], + "image/vnd.cns.inf2": [], + "image/vnd.dece.graphic": [ + "uvi", + "uvvi", + "uvg", + "uvvg" + ], + "image/vnd.dvb.subtitle": [ + "sub" + ], + "image/vnd.djvu": [ + "djvu", + "djv" + ], + "image/vnd.dwg": [ + "dwg" + ], + "image/vnd.dxf": [ + "dxf" + ], + "image/vnd.fastbidsheet": [ + "fbs" + ], + "image/vnd.fpx": [ + "fpx" + ], + "image/vnd.fst": [ + "fst" + ], + "image/vnd.fujixerox.edmics-mmr": [ + "mmr" + ], + "image/vnd.fujixerox.edmics-rlc": [ + "rlc" + ], + "image/vnd.globalgraphics.pgb": [], + "image/vnd.microsoft.icon": [], + "image/vnd.mix": [], + "image/vnd.ms-modi": [ + "mdi" + ], + "image/vnd.ms-photo": [ + "wdp" + ], + "image/vnd.net-fpx": [ + "npx" + ], + "image/vnd.radiance": [], + "image/vnd.sealed.png": [], + "image/vnd.sealedmedia.softseal.gif": [], + "image/vnd.sealedmedia.softseal.jpg": [], + "image/vnd.svf": [], + "image/vnd.wap.wbmp": [ + "wbmp" + ], + "image/vnd.xiff": [ + "xif" + ], + "image/webp": [ + "webp" + ], + "image/x-3ds": [ + "3ds" + ], + "image/x-cmu-raster": [ + "ras" + ], + "image/x-cmx": [ + "cmx" + ], + "image/x-freehand": [ + "fh", + "fhc", + "fh4", + "fh5", + "fh7" + ], + "image/x-icon": [ + "ico" + ], + "image/x-mrsid-image": [ + "sid" + ], + "image/x-pcx": [ + "pcx" + ], + "image/x-pict": [ + "pic", + "pct" + ], + "image/x-portable-anymap": [ + "pnm" + ], + "image/x-portable-bitmap": [ + "pbm" + ], + "image/x-portable-graymap": [ + "pgm" + ], + "image/x-portable-pixmap": [ + "ppm" + ], + "image/x-rgb": [ + "rgb" + ], + "image/x-tga": [ + "tga" + ], + "image/x-xbitmap": [ + "xbm" + ], + "image/x-xpixmap": [ + "xpm" + ], + "image/x-xwindowdump": [ + "xwd" + ], + "message/cpim": [], + "message/delivery-status": [], + "message/disposition-notification": [], + "message/example": [], + "message/external-body": [], + "message/feedback-report": [], + "message/global": [], + "message/global-delivery-status": [], + "message/global-disposition-notification": [], + "message/global-headers": [], + "message/http": [], + "message/imdn+xml": [], + "message/news": [], + "message/partial": [], + "message/rfc822": [ + "eml", + "mime" + ], + "message/s-http": [], + "message/sip": [], + "message/sipfrag": [], + "message/tracking-status": [], + "message/vnd.si.simp": [], + "model/example": [], + "model/iges": [ + "igs", + "iges" + ], + "model/mesh": [ + "msh", + "mesh", + "silo" + ], + "model/vnd.collada+xml": [ + "dae" + ], + "model/vnd.dwf": [ + "dwf" + ], + "model/vnd.flatland.3dml": [], + "model/vnd.gdl": [ + "gdl" + ], + "model/vnd.gs-gdl": [], + "model/vnd.gs.gdl": [], + "model/vnd.gtw": [ + "gtw" + ], + "model/vnd.moml+xml": [], + "model/vnd.mts": [ + "mts" + ], + "model/vnd.parasolid.transmit.binary": [], + "model/vnd.parasolid.transmit.text": [], + "model/vnd.vtu": [ + "vtu" + ], + "model/vrml": [ + "wrl", + "vrml" + ], + "model/x3d+binary": [ + "x3db", + "x3dbz" + ], + "model/x3d+vrml": [ + "x3dv", + "x3dvz" + ], + "model/x3d+xml": [ + "x3d", + "x3dz" + ], + "multipart/alternative": [], + "multipart/appledouble": [], + "multipart/byteranges": [], + "multipart/digest": [], + "multipart/encrypted": [], + "multipart/example": [], + "multipart/form-data": [], + "multipart/header-set": [], + "multipart/mixed": [], + "multipart/parallel": [], + "multipart/related": [], + "multipart/report": [], + "multipart/signed": [], + "multipart/voice-message": [], + "text/1d-interleaved-parityfec": [], + "text/cache-manifest": [ + "appcache" + ], + "text/calendar": [ + "ics", + "ifb" + ], + "text/css": [ + "css" + ], + "text/csv": [ + "csv" + ], + "text/directory": [], + "text/dns": [], + "text/ecmascript": [], + "text/enriched": [], + "text/example": [], + "text/fwdred": [], + "text/html": [ + "html", + "htm" + ], + "text/javascript": [], + "text/n3": [ + "n3" + ], + "text/parityfec": [], + "text/plain": [ + "txt", + "text", + "conf", + "def", + "list", + "log", + "in" + ], + "text/prs.fallenstein.rst": [], + "text/prs.lines.tag": [ + "dsc" + ], + "text/vnd.radisys.msml-basic-layout": [], + "text/red": [], + "text/rfc822-headers": [], + "text/richtext": [ + "rtx" + ], + "text/rtf": [], + "text/rtp-enc-aescm128": [], + "text/rtx": [], + "text/sgml": [ + "sgml", + "sgm" + ], + "text/t140": [], + "text/tab-separated-values": [ + "tsv" + ], + "text/troff": [ + "t", + "tr", + "roff", + "man", + "me", + "ms" + ], + "text/turtle": [ + "ttl" + ], + "text/ulpfec": [], + "text/uri-list": [ + "uri", + "uris", + "urls" + ], + "text/vcard": [ + "vcard" + ], + "text/vnd.abc": [], + "text/vnd.curl": [ + "curl" + ], + "text/vnd.curl.dcurl": [ + "dcurl" + ], + "text/vnd.curl.scurl": [ + "scurl" + ], + "text/vnd.curl.mcurl": [ + "mcurl" + ], + "text/vnd.dmclientscript": [], + "text/vnd.dvb.subtitle": [ + "sub" + ], + "text/vnd.esmertec.theme-descriptor": [], + "text/vnd.fly": [ + "fly" + ], + "text/vnd.fmi.flexstor": [ + "flx" + ], + "text/vnd.graphviz": [ + "gv" + ], + "text/vnd.in3d.3dml": [ + "3dml" + ], + "text/vnd.in3d.spot": [ + "spot" + ], + "text/vnd.iptc.newsml": [], + "text/vnd.iptc.nitf": [], + "text/vnd.latex-z": [], + "text/vnd.motorola.reflex": [], + "text/vnd.ms-mediapackage": [], + "text/vnd.net2phone.commcenter.command": [], + "text/vnd.si.uricatalogue": [], + "text/vnd.sun.j2me.app-descriptor": [ + "jad" + ], + "text/vnd.trolltech.linguist": [], + "text/vnd.wap.si": [], + "text/vnd.wap.sl": [], + "text/vnd.wap.wml": [ + "wml" + ], + "text/vnd.wap.wmlscript": [ + "wmls" + ], + "text/x-asm": [ + "s", + "asm" + ], + "text/x-c": [ + "c", + "cc", + "cxx", + "cpp", + "h", + "hh", + "dic" + ], + "text/x-fortran": [ + "f", + "for", + "f77", + "f90" + ], + "text/x-java-source": [ + "java" + ], + "text/x-opml": [ + "opml" + ], + "text/x-pascal": [ + "p", + "pas" + ], + "text/x-nfo": [ + "nfo" + ], + "text/x-setext": [ + "etx" + ], + "text/x-sfv": [ + "sfv" + ], + "text/x-uuencode": [ + "uu" + ], + "text/x-vcalendar": [ + "vcs" + ], + "text/x-vcard": [ + "vcf" + ], + "text/xml": [], + "text/xml-external-parsed-entity": [], + "video/1d-interleaved-parityfec": [], + "video/3gpp": [ + "3gp" + ], + "video/3gpp-tt": [], + "video/3gpp2": [ + "3g2" + ], + "video/bmpeg": [], + "video/bt656": [], + "video/celb": [], + "video/dv": [], + "video/example": [], + "video/h261": [ + "h261" + ], + "video/h263": [ + "h263" + ], + "video/h263-1998": [], + "video/h263-2000": [], + "video/h264": [ + "h264" + ], + "video/h264-rcdo": [], + "video/h264-svc": [], + "video/jpeg": [ + "jpgv" + ], + "video/jpeg2000": [], + "video/jpm": [ + "jpm", + "jpgm" + ], + "video/mj2": [ + "mj2", + "mjp2" + ], + "video/mp1s": [], + "video/mp2p": [], + "video/mp2t": [], + "video/mp4": [ + "mp4", + "mp4v", + "mpg4" + ], + "video/mp4v-es": [], + "video/mpeg": [ + "mpeg", + "mpg", + "mpe", + "m1v", + "m2v" + ], + "video/mpeg4-generic": [], + "video/mpv": [], + "video/nv": [], + "video/ogg": [ + "ogv" + ], + "video/parityfec": [], + "video/pointer": [], + "video/quicktime": [ + "qt", + "mov" + ], + "video/raw": [], + "video/rtp-enc-aescm128": [], + "video/rtx": [], + "video/smpte292m": [], + "video/ulpfec": [], + "video/vc1": [], + "video/vnd.cctv": [], + "video/vnd.dece.hd": [ + "uvh", + "uvvh" + ], + "video/vnd.dece.mobile": [ + "uvm", + "uvvm" + ], + "video/vnd.dece.mp4": [], + "video/vnd.dece.pd": [ + "uvp", + "uvvp" + ], + "video/vnd.dece.sd": [ + "uvs", + "uvvs" + ], + "video/vnd.dece.video": [ + "uvv", + "uvvv" + ], + "video/vnd.directv.mpeg": [], + "video/vnd.directv.mpeg-tts": [], + "video/vnd.dlna.mpeg-tts": [], + "video/vnd.dvb.file": [ + "dvb" + ], + "video/vnd.fvt": [ + "fvt" + ], + "video/vnd.hns.video": [], + "video/vnd.iptvforum.1dparityfec-1010": [], + "video/vnd.iptvforum.1dparityfec-2005": [], + "video/vnd.iptvforum.2dparityfec-1010": [], + "video/vnd.iptvforum.2dparityfec-2005": [], + "video/vnd.iptvforum.ttsavc": [], + "video/vnd.iptvforum.ttsmpeg2": [], + "video/vnd.motorola.video": [], + "video/vnd.motorola.videop": [], + "video/vnd.mpegurl": [ + "mxu", + "m4u" + ], + "video/vnd.ms-playready.media.pyv": [ + "pyv" + ], + "video/vnd.nokia.interleaved-multimedia": [], + "video/vnd.nokia.videovoip": [], + "video/vnd.objectvideo": [], + "video/vnd.sealed.mpeg1": [], + "video/vnd.sealed.mpeg4": [], + "video/vnd.sealed.swf": [], + "video/vnd.sealedmedia.softseal.mov": [], + "video/vnd.uvvu.mp4": [ + "uvu", + "uvvu" + ], + "video/vnd.vivo": [ + "viv" + ], + "video/webm": [ + "webm" + ], + "video/x-f4v": [ + "f4v" + ], + "video/x-fli": [ + "fli" + ], + "video/x-flv": [ + "flv" + ], + "video/x-m4v": [ + "m4v" + ], + "video/x-matroska": [ + "mkv", + "mk3d", + "mks" + ], + "video/x-mng": [ + "mng" + ], + "video/x-ms-asf": [ + "asf", + "asx" + ], + "video/x-ms-vob": [ + "vob" + ], + "video/x-ms-wm": [ + "wm" + ], + "video/x-ms-wmv": [ + "wmv" + ], + "video/x-ms-wmx": [ + "wmx" + ], + "video/x-ms-wvx": [ + "wvx" + ], + "video/x-msvideo": [ + "avi" + ], + "video/x-sgi-movie": [ + "movie" + ], + "video/x-smv": [ + "smv" + ], + "x-conference/x-cooltalk": [ + "ice" + ] +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/node.json b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/node.json new file mode 100644 index 000000000..ad50d6134 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/lib/node.json @@ -0,0 +1,55 @@ +{ + "text/vtt": [ + "vtt" + ], + "application/x-chrome-extension": [ + "crx" + ], + "text/x-component": [ + "htc" + ], + "text/cache-manifest": [ + "manifest" + ], + "application/octet-stream": [ + "buffer" + ], + "application/mp4": [ + "m4p" + ], + "audio/mp4": [ + "m4a" + ], + "video/MP2T": [ + "ts" + ], + "application/x-web-app-manifest+json": [ + "webapp" + ], + "text/x-lua": [ + "lua" + ], + "application/x-lua-bytecode": [ + "luac" + ], + "text/x-markdown": [ + "markdown", + "md", + "mkd" + ], + "text/plain": [ + "ini" + ], + "application/dash+xml": [ + "mdp" + ], + "font/opentype": [ + "otf" + ], + "application/json": [ + "map" + ], + "application/xml": [ + "xsd" + ] +} diff --git a/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 000000000..baa79a956 --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,69 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "1.0.2", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/expressjs/mime-types" + }, + "license": "MIT", + "main": "lib", + "devDependencies": { + "co": "3", + "cogent": "0", + "mocha": "1", + "should": "3" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "make test" + }, + "gitHead": "e82b23836eb42003b8346fb31769da2fb7eb54e8", + "bugs": { + "url": "https://github.com/expressjs/mime-types/issues" + }, + "homepage": "https://github.com/expressjs/mime-types", + "_id": "mime-types@1.0.2", + "_shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", + "_from": "mime-types@~1.0.1", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/node_modules/type-is/package.json b/node_modules/body-parser/node_modules/type-is/package.json new file mode 100644 index 000000000..c0222af7c --- /dev/null +++ b/node_modules/body-parser/node_modules/type-is/package.json @@ -0,0 +1,84 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.3.2", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/type-is" + }, + "dependencies": { + "media-typer": "0.2.0", + "mime-types": "~1.0.1" + }, + "devDependencies": { + "istanbul": "0.2.11", + "mocha": "*", + "should": "*" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --require should --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d76790909638d4cf1785e09858db5576f91f710f", + "bugs": { + "url": "https://github.com/expressjs/type-is/issues" + }, + "homepage": "https://github.com/expressjs/type-is", + "_id": "type-is@1.3.2", + "_shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", + "_from": "type-is@~1.3.2", + "_npmVersion": "1.4.16", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 000000000..08141399f --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,91 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.6.5", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/body-parser" + }, + "dependencies": { + "bytes": "1.0.0", + "depd": "0.4.4", + "iconv-lite": "0.4.4", + "media-typer": "0.2.0", + "on-finished": "2.1.0", + "qs": "1.2.2", + "raw-body": "1.3.0", + "type-is": "~1.3.2" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.21.4", + "should": "~4.0.4", + "supertest": "~0.13.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --require should --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + }, + "gitHead": "0d42013b30a6784a7e86dd387a2aa5d17b5b01cb", + "bugs": { + "url": "https://github.com/expressjs/body-parser/issues" + }, + "homepage": "https://github.com/expressjs/body-parser", + "_id": "body-parser@1.6.5", + "_shasum": "536f01e08ee2b6df6a941d6c8c9647ee99ee4de7", + "_from": "body-parser@^1.0.2", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "536f01e08ee2b6df6a941d6c8c9647ee99ee4de7", + "tarball": "http://registry.npmjs.org/body-parser/-/body-parser-1.6.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.6.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/express-error-handler/.npmignore b/node_modules/express-error-handler/.npmignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/express-error-handler/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/express-error-handler/LICENSE b/node_modules/express-error-handler/LICENSE new file mode 100644 index 000000000..c71e82de0 --- /dev/null +++ b/node_modules/express-error-handler/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Eric Elliott + +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/express-error-handler/README.md b/node_modules/express-error-handler/README.md new file mode 100644 index 000000000..878fdebaf --- /dev/null +++ b/node_modules/express-error-handler/README.md @@ -0,0 +1,153 @@ +express-error-handler +===================== + +A graceful error handler for Express applications. + +## Quick start: + +```js +var express = require('express'), + errorHandler = require('../error-handler.js'), + app = express(), + env = process.env, + port = env.myapp_port || 3000, + http = require('http'), + server; + +// Route that triggers a sample error: +app.get('/error', function createError(req, + res, next) { + var err = new Error('Sample error'); + err.status = 500; + next(err); +}); + +// Create the server object that we can pass +// in to the error handler: +server = http.createServer(app); + +// Log the error +app.use(function (err, req, res, next) { + console.log(err); + next(err); +}); + +// Respond to errors and conditionally shut +// down the server. Pass in the server object +// so the error handler can shut it down +// gracefully: +app.use( errorHandler({server: server}) ); + +server.listen(port, function () { + console.log('Listening on port ' + port); +}); +``` + +## Configuration errorHandler(options) + +Here are the parameters you can pass into the `errorHandler()` middleware: + +* @param {object} [options] + +* @param {object} [options.handlers] Custom handlers for specific status codes. +* @param {object} [options.views] View files to render in response to specific status codes. Specify a default with `options.views.default` +* @param {object} [options.static] Static files to send in response to specific status codes. Specify a default with options.static.default. +* @param {number} [options.timeout] Delay between the graceful shutdown attempt and the forced shutdown timeout. +* @param {number} [options.exitStatus] Custom process exit status code. +* @param {object} [options.server] The app server object for graceful shutdowns. +* @param {function} [options.shutdown] An alternative shutdown function if the graceful shutdown fails. +* @param {function} serializer a function to customize the JSON error object. Usage: serializer(err) return errObj +* @return {function} errorHandler Express error handling middleware. + +### Examples: + +`express-error-handler` lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for: + + +```js + var errorHandler = require('express-error-handler'), + handler = errorHandler({ + handlers: { + '404': function err404() { + // do some custom thing here... + } + } + }); + + // After all your routes... + // Pass a 404 into next(err) + app.use( errorHandler.httpError(404) ); + + // Handle all unhandled errors: + app.use( handler ); + +Or for a static page: + + handler = errorHandler({ + static: { + '404': function err404() { + // do some custom thing here... + } + } + }); + +Or for a custom view: + + handler = errorHandler({ + views: { + '404': function err404() { + // do some custom thing here... + } + } + }); +``` + +[More examples](https://github.com/dilvie/express-error-handler/tree/master/examples) are available in the examples folder. + +## errorHandler.isClientError(status) + +Return true if the error status represents a client error that should not trigger a restart. + +* @param {number} status +* @return {boolean} + + +### Example + +```js +errorHandler.isClientError(404); // returns true +errorHandler.isClientError(500); // returns false +``` + + +## errorHandler.httpError(status, [message]) + +Take an error status and return a route that sends an error with the appropriate status and message to an error handler via `next(err)`. + +* @param {number} status +* @param {string} message +* @return {function} Express route handler + +```js +// Define supported routes +app.get( '/foo', handleFoo() ); +// 405 for unsupported methods. +app.all( '/foo', createHandler.httpError(405) ); +``` + +## Restify support + +Restify error handling works different from +Express. + +First, `next(err)` is synonymous with `res.send(status, error)`. This means that you should *only use `next(err)` to report errors to users*, and not as a way to aggregate errors to a common error handler. Instead, you can invoke an error handler directly to aggregate your error handling in one place. + +* There is no error handling middleware. Instead, use `server.on(`uncaughtException`, handleError)` + +See the examples in `./examples/restify.js` + + +## Thanks + +* [Nam Nguyen](https://github.com/gdbtek) for bringing the Express DOS exploit to my attention. +* [Samuel Reed](https://github.com/strml) for helpful suggestions. diff --git a/node_modules/express-error-handler/error-handler.js b/node_modules/express-error-handler/error-handler.js new file mode 100644 index 000000000..721b1b1e1 --- /dev/null +++ b/node_modules/express-error-handler/error-handler.js @@ -0,0 +1,318 @@ +/** + * express-error-handler + * + * A graceful error handler for Express + * applications. + * + * Copyright (C) 2013 Eric Elliott + * + * Written for + * "Programming JavaScript Applications" + * (O'Reilly) + * + * MIT License + **/ + +'use strict'; + +var mixIn = require('mout/object/mixIn'), + path = require('path'), + fs = require('fs'), + statusCodes = require('http').STATUS_CODES, + + /** + * Return true if the error status represents + * a client error that should not trigger a + * restart. + * + * @param {number} status + * @return {boolean} + */ + isClientError = function isClientError(status) { + return (status >= 400 && status <= 499); + }, + + /** + * Attempt a graceful shutdown, and then time + * out if the connections fail to drain in time. + * + * @param {object} o options + * @param {object} o.server server object + * @param {object} o.timeout timeout in ms + * @param {function} exit - force kill function + */ + close = function close(o, exit) { + // We need to kill the server process so + // the app can repair itself. Your process + // should be monitored in production and + // restarted when it shuts down. + // + // That can be accomplished with modules + // like forever, forky, etc... + // + // First, try a graceful shutdown: + if (o.server && typeof o.server.close === + 'function') { + o.server.close(function () { + process.exit(o.exitStatus); + }); + } + + // Just in case the server.close() callback + // never fires, this will wait for a timeout + // and then terminate. Users can override + // this function by passing options.shutdown: + exit(o); + }, + + /** + * Take an error status and return a route that + * sends an error with the appropriate status + * and message to an error handler via + * `next(err)`. + * + * @param {number} status + * @param {string} message + * @return {function} Express route handler + */ + httpError = function httpError (status, message) { + var err = new Error(); + err.status = status; + err.message = message || + statusCodes[status] || + 'Internal server error'; + + return function httpErr(req, res, next) { + next(err); + }; + }, + + sendFile = function sendFile (staticFile, res) { + var filePath = path.resolve(staticFile), + stream = fs.createReadStream(filePath); + stream.pipe(res); + }, + + send = function send(statusCode, err, res, o) { + var body = mixIn({}, { + status: statusCode, + message: err.message || + statusCodes[statusCode] + }); + + body = (o.serializer) ? + o.serializer(body) : + body; + + res.send(statusCode, body); + }, + + defaults = { + handlers: {}, + views: {}, + static: {}, + timeout: 3 * 1000, + exitStatus: 1, + server: undefined, + shutdown: undefined, + serializer: undefined, + framework: 'express' + }, + createHandler; + +/** + * A graceful error handler for Express + * applications. + * + * @param {object} [options] + * + * @param {object} [options.handlers] Custom + * handlers for specific status codes. + * + * @param {object} [options.views] View files to + * render in response to specific status + * codes. Specify a default with + * options.views.default. + * + * @param {object} [options.static] Static files + * to send in response to specific status + * codes. Specify a default with + * options.static.default. + * + * @param {number} [options.timeout] Delay + * between the graceful shutdown + * attempt and the forced shutdown + * timeout. + * + * @param {number} [options.exitStatus] Custom + * process exit status code. + * + * @param {object} [options.server] The app server + * object for graceful shutdowns. + * + * @param {function} [options.shutdown] An + * alternative shutdown function if the + * graceful shutdown fails. + * + * @param {function} serializer A function to + * customize the JSON error object. + * Usage: serializer(err) return errObj + * + * @param {function} framework Either 'express' + * (default) or 'restify'. + * + * @return {function} errorHandler Express error + * handling middleware. + */ +createHandler = function createHandler(options) { + + var o = mixIn({}, defaults, options), + + /** + * In case of an error, wait for a timer to + * elapse, and then terminate. + * @param {object} options + * @param {number} o.exitStatus + * @param {number} o.timeout + */ + exit = o.shutdown || function exit(o){ + + // Give the app time for graceful shutdown. + setTimeout(function () { + process.exit(o.exitStatus); + }, o.timeout); + + }, + express = o.framework === 'express', + restify = o.framework === 'restify', + errorHandler; + + /** + * Express error handler to handle any + * uncaught express errors. For error logging, + * see bunyan-request-logger. + * + * @param {object} err + * @param {object} req + * @param {object} res + * @param {function} next + */ + errorHandler = function errorHandler(err, req, + res, next) { + + var defaultView = o.views['default'], + defaultStatic = o.static['default'], + status = err && err.status || + res && res.statusCode, + handler = o.handlers[status], + view = o.views[status], + staticFile = o.static[status], + + renderDefault = function + renderDefault(statusCode) { + + res.statusCode = statusCode; + + if (defaultView) { + return res.render(defaultView, err); + } + + if (defaultStatic) { + return sendFile(defaultStatic, res); + } + + if (restify) { + send(statusCode, err, res, o); + } + + if (express) { + return res.format({ + json: function () { + send(statusCode, err, res, o); + }, + text: function () { + res.send(statusCode); + }, + html: function () { + res.send(statusCode); + } + }); + } + }, + + resumeOrClose = function + resumeOrClose(status) { + if (!isClientError(status)) { + return close(o, exit); + } + }; + + if (!res) { + return resumeOrClose(status); + } + + // If there's a custom handler defined, + // use it and return. + if (typeof handler === 'function') { + handler(err, req, res, next); + return resumeOrClose(status); + } + + // If there's a custom view defined, + // render it. + if (view) { + res.render(view, err); + return resumeOrClose(status); + } + + // If there's a custom static file defined, + // render it. + if (staticFile) { + sendFile(staticFile, res); + return resumeOrClose(status); + } + + // If the error is user generated, send + // a helpful error message, and don't shut + // down. + // + // If we shutdown on user errors, + // attackers can send malformed requests + // for the purpose of creating a Denial + // Of Service (DOS) attack. + if (isClientError(status)) { + return renderDefault(status); + } + + // For all other errors, deliver a 500 + // error and shut down. + renderDefault(500); + + close(o, exit); + }; + + if (express) { + return errorHandler; + } + + if (restify) { + return function (req, res, route, err) { + return errorHandler(err, req, res); + }; + } +}; + +createHandler.isClientError = isClientError; +createHandler.clientError = function () { + var args = [].slice.call(arguments); + + console.log('WARNING: .clientError() is ' + + 'deprecated. Use isClientError() instead.'); + + return this.isClientError.apply(this, args); +}; + +// HTTP error generating route. +createHandler.httpError = httpError; + +module.exports = createHandler; diff --git a/node_modules/express-error-handler/examples/app.js b/node_modules/express-error-handler/examples/app.js new file mode 100644 index 000000000..535e75775 --- /dev/null +++ b/node_modules/express-error-handler/examples/app.js @@ -0,0 +1,63 @@ +'use strict'; + +var express = require('express'), + logger = require('bunyan-request-logger'), + noCache = require('connect-cache-control'), + errorHandler = require('../error-handler.js'), + log = logger(), + app = express(), + env = process.env, + port = env.myapp_port || 3000, + http = require('http'), + server; + +app.use( log.requestLogger() ); + +// Route to handle client side log messages. +// +// Counter to intuition, client side logging +// works best with GET requests. +// +// AJAX POST sends headers and body in two steps, +// which slows it down. +// +// This route prepends the cache-control +// middleware so that the browser always logs +// to the server instead of fetching a useless +// OK message from its cache. +app.get('/log', noCache, + function logHandler(req, res) { + + // Since all requests are automatically logged, + // all you need to do is send the response: + res.send(200); +}); + +// Route that triggers a sample error: +app.get('/error', function createError(req, + res, next) { + var err = new Error('Sample error'); + err.status = 500; + next(err); +}); + + +// Route that triggers a sample error: +app.all('/*', errorHandler.httpError(404)); + +// Log request errors: +app.use( log.errorLogger() ); + +// Create the server object that we can pass +// in to the error handler: +server = http.createServer(app); + +// Respond to errors and conditionally shut +// down the server. Pass in the server object +// so the error handler can shut it down +// gracefully: +app.use( errorHandler({server: server}) ); + +server.listen(port, function () { + log.info('Listening on port ' + port); +}); diff --git a/node_modules/express-error-handler/examples/restify.js b/node_modules/express-error-handler/examples/restify.js new file mode 100644 index 000000000..0d671cd9f --- /dev/null +++ b/node_modules/express-error-handler/examples/restify.js @@ -0,0 +1,100 @@ +'use strict'; + +var restify = require('restify'), + server = restify.createServer(), + errorHandler = require('../error-handler.js'), + + handleError = errorHandler({ + server: server, + + // Put the errorHandler in restify error + // handling mode. + framework: 'restify' + }), + + // Since restify error handlers take error + // last, and process 'uncaughtError' sends + // error first, you'll need another one for + // process exceptions. Don't pass the + // framework: 'restify' setting this time: + handleProcessError = errorHandler({ + server: server + }), + + middlewareError = + function middlewareError() { + throw new Error('Random middleware error.'); + }; + +// Don't do this: +server.get('/brokenError', function (req, res, next) { + var err = new Error('Random, possibly ' + + 'unrecoverable error. Server is now running ' + + 'in undefined state!'); + + err.status = 500; + + // Warning! This error will go directly to the + // user, and you won't have any opportunity to + // examine it and possibly shut down the system. + next(err); +}); + +// Instead, do this: +server.get('/err', function (req, res) { + var err = new Error('Random, possibly ' + + 'unrecoverable error. Server is now running ' + + 'in undefined state!'); + + err.status = 500; + + // You should invoke handleError directly in your + // route instead of sending it to next() or + // throwing. Note that the restify error handler + // has the call signature: req, res, route, err. + // Normally, route is an object. + handleError(req, res, '/err', err); +}); + + +// This route demonstrates what happens when your +// routes throw. Never do this on +// purpose. Instead, invoke the +// error handler as described above. +server.get('/thrower', function () { + var err = new Error('Random, possibly ' + + 'unrecoverable error. Server is now running ' + + 'in undefined state!'); + + throw err; +}); + +// This demonstrates what happens when your +// middleware throws. As with routes, never do +// this on purpose. Instead, invoke the +// error handler as described above. +server.use(middlewareError); + +server.get('/middleware', function () { + // Placeholder to invoke middlewareError. +}); + +// This is called when an error is accidentally +// thrown. Under the hood, it uses Node's domain +// module for error handling, which limits the +// scope of the domain to the request / response +// cycle. Restify hooks up the domain for you, +// so you don't have to worry about binding +// request and response to the domain. +server.on('uncaughtException', handleError); + +// We should still listen for process errors +// and shut down if we catch them. This handler +// will try to let server connections drain, first, +// and invoke your custom handlers if you have +// any defined. +process.on('uncaughtException', handleProcessError); + +server.listen(3000, function () { + console.log('Listening on port 3000'); +}); diff --git a/node_modules/express-error-handler/gruntfile.js b/node_modules/express-error-handler/gruntfile.js new file mode 100644 index 000000000..607bd2dfa --- /dev/null +++ b/node_modules/express-error-handler/gruntfile.js @@ -0,0 +1,32 @@ +'use strict'; +/*global module*/ +module.exports = function(grunt) { + grunt.initConfig({ + jshint: { + all: ['./gruntfile.js', './test/*.js', + './examples/*.js', './error-handler.js'], + options: { + curly: true, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + nonew: true, + noarg: true, + sub: true, + undef: true, + unused: true, + eqnull: true, + node: true, + strict: true, + boss: false + } + } + + }); + + grunt.loadNpmTasks('grunt-contrib-jshint'); + + grunt.registerTask('hint', ['jshint']); + grunt.registerTask('default', ['jshint']); +}; \ No newline at end of file diff --git a/node_modules/express-error-handler/node_modules/connect-domain/.npmignore b/node_modules/express-error-handler/node_modules/connect-domain/.npmignore new file mode 100644 index 000000000..77ba66de4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/.npmignore @@ -0,0 +1,6 @@ +.git* +test/ +lib-cov/ +coverage.html +.travis.yml +Makefile \ No newline at end of file diff --git a/node_modules/express-error-handler/node_modules/connect-domain/LICENSE b/node_modules/express-error-handler/node_modules/connect-domain/LICENSE new file mode 100644 index 000000000..6de4986b8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 Vadim M. Baryshev + +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. \ No newline at end of file diff --git a/node_modules/express-error-handler/node_modules/connect-domain/README.md b/node_modules/express-error-handler/node_modules/connect-domain/README.md new file mode 100644 index 000000000..08a2c58ba --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/README.md @@ -0,0 +1,35 @@ +# About + +Asynchronous error handler for Connect + +# Installation + + npm install connect-domain + +# Usage + +```js +var + connect = require('connect'), + connectDomain = require('connect-domain'); + +var app = connect() + .use(connectDomain()) + .use(function(req, res){ + if (Math.random() > 0.5) { + throw new Error('Simple error'); + } + setTimeout(function() { + if (Math.random() > 0.5) { + throw new Error('Asynchronous error from timeout'); + } else { + res.end('Hello from Connect!'); + } + }, 1000); + }) + .use(function(err, req, res, next) { + res.end(err.message); + }); + +app.listen(3000); +``` \ No newline at end of file diff --git a/node_modules/express-error-handler/node_modules/connect-domain/index.js b/node_modules/express-error-handler/node_modules/connect-domain/index.js new file mode 100644 index 000000000..d02df199a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/index.js @@ -0,0 +1 @@ +module.exports = process.env.CONNECT_DOMAIN_COV ? require('./lib-cov/connect-domain') : require('./lib/connect-domain'); diff --git a/node_modules/express-error-handler/node_modules/connect-domain/lib/connect-domain.js b/node_modules/express-error-handler/node_modules/connect-domain/lib/connect-domain.js new file mode 100644 index 000000000..5f25d49d7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/lib/connect-domain.js @@ -0,0 +1,23 @@ +var domain = require('domain'); + +module.exports = function () { + return function domainMiddleware(req, res, next) { + var reqDomain = domain.create(); + + res.on('close', function () { + reqDomain.dispose(); + }); + + res.on('finish', function () { + reqDomain.dispose(); + }); + + reqDomain.on('error', function (err) { + // Once a domain is disposed, further errors from the emitters in that set will be ignored. + reqDomain.dispose(); + next(err); + }); + + reqDomain.run(next); + }; +}; diff --git a/node_modules/express-error-handler/node_modules/connect-domain/package.json b/node_modules/express-error-handler/node_modules/connect-domain/package.json new file mode 100644 index 000000000..92f2a6912 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/connect-domain/package.json @@ -0,0 +1,55 @@ +{ + "name": "connect-domain", + "version": "0.5.0", + "description": "Asynchronous error handler for Connect", + "keywords": [ + "domain", + "error", + "connect" + ], + "author": { + "name": "Vadim M. Baryshev", + "email": "vadimbaryshev@gmail.com" + }, + "main": "index", + "repository": { + "type": "git", + "url": "git://github.com/baryshev/connect-domain.git" + }, + "devDependencies": { + "should": "*", + "connect": "*", + "jscover": "*", + "supertest": "*", + "mocha": "*" + }, + "engines": { + "node": ">= 0.8.0" + }, + "readme": "# About \n\nAsynchronous error handler for Connect\n\n# Installation\n\n\tnpm install connect-domain\n\n# Usage\n\n```js\nvar\n\tconnect = require('connect'),\n\tconnectDomain = require('connect-domain');\n\nvar app = connect()\n\t.use(connectDomain())\n\t.use(function(req, res){\n\t\tif (Math.random() > 0.5) {\n\t\t\tthrow new Error('Simple error');\n\t\t}\n\t\tsetTimeout(function() {\n\t\t\tif (Math.random() > 0.5) {\n\t\t\t\tthrow new Error('Asynchronous error from timeout');\n\t\t\t} else {\n\t\t\t\tres.end('Hello from Connect!');\n\t\t\t}\n\t\t}, 1000);\n\t})\n\t.use(function(err, req, res, next) {\n\t\tres.end(err.message);\n\t});\n\napp.listen(3000);\n```", + "readmeFilename": "README.md", + "_id": "connect-domain@0.5.0", + "dist": { + "shasum": "8b6e46cc7b33e57bcf9e3fe789a3185c3eaa3868", + "tarball": "http://registry.npmjs.org/connect-domain/-/connect-domain-0.5.0.tgz" + }, + "_from": "connect-domain@~0.5.0", + "_npmVersion": "1.2.11", + "_npmUser": { + "name": "baryshev", + "email": "vadimbaryshev@gmail.com" + }, + "maintainers": [ + { + "name": "baryshev", + "email": "vadimbaryshev@gmail.com" + } + ], + "directories": {}, + "_shasum": "8b6e46cc7b33e57bcf9e3fe789a3185c3eaa3868", + "_resolved": "https://registry.npmjs.org/connect-domain/-/connect-domain-0.5.0.tgz", + "bugs": { + "url": "https://github.com/baryshev/connect-domain/issues" + }, + "homepage": "https://github.com/baryshev/connect-domain" +} diff --git a/node_modules/express-error-handler/node_modules/mout/.editorconfig b/node_modules/express-error-handler/node_modules/mout/.editorconfig new file mode 100644 index 000000000..e036e2477 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/.editorconfig @@ -0,0 +1,20 @@ +; EditorConfig is awesome: http://EditorConfig.org + +; top-most EditorConfig file +root = true + +; base rules +[*] +end_of_line = lf +insert_final_newline = false +indent_style = space +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true + +; The default indent on package.json is 2 spaces, better to keep it so we can +; use `npm install --save` and other features that rewrites the package.json +; file automatically +[package.json] +indent_style = space +indent_size = 2 diff --git a/node_modules/express-error-handler/node_modules/mout/.jshintrc b/node_modules/express-error-handler/node_modules/mout/.jshintrc new file mode 100644 index 000000000..bbdb29cf6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/.jshintrc @@ -0,0 +1,69 @@ +{ + // Settings + "passfail" : false, // Stop on first error. + "maxerr" : 50, // Maximum error before stopping. + + + // Predefined globals whom JSHint will ignore. + "browser" : true, // Standard browser globals e.g. `window`, `document`. + "couch" : false, + "dojo" : false, + "jquery" : true, + "mootools" : false, + "node" : false, + "prototypejs" : false, + "rhino" : false, + "wsh" : false, + + // Custom globals. + "predef" : [ + "define", + "require" + ], + + + // Development. + "debug" : false, // Allow debugger statements e.g. browser breakpoints. + "devel" : false, // Allow developments statements e.g. `console.log();`. + + + // EcmaScript 5. + "es5" : false, // Allow EcmaScript 5 syntax. + "globalstrict" : false, // Allow global "use strict" (also enables 'strict'). + "strict" : false, // Require `use strict` pragma in every file. + + + // The Good Parts. + "asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons). + "bitwise" : false, // Prohibit bitwise operators (&, |, ^, etc.). + "boss" : true, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments. + "curly" : false, // Require {} for every new block or scope. + "eqeqeq" : true, // Require triple equals i.e. `===`. + "eqnull" : true, // Tolerate use of `== null`. + "evil" : false, // Tolerate use of `eval`. + "expr" : false, // Tolerate `ExpressionStatement` as Programs. + "forin" : false, // Tolerate `for in` loops without `hasOwnPrototype`. + "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` + "latedef" : false, // Prohibit variable use before definition. + "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons. + "loopfunc" : false, // Allow functions to be defined within loops. + "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`. + "regexdash" : true, // Tolerate unescaped last dash i.e. `[-...]`. + "regexp" : false, // Prohibit `.` and `[^...]` in regular expressions. + "scripturl" : false, // Tolerate script-targeted URLs. + "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`. + "supernew" : false, // Tolerate `new function () { ... };` and `new Object;`. + "undef" : false, // Require all non-global variables be declared before they are used. + + + // Personal styling prefrences. + "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`. + "noempty" : true, // Prohipit use of empty blocks. + "nomen" : false, // Prohibit use of initial or trailing underbars in names. + "nonew" : true, // Prohibit use of constructors for side-effects. + "onevar" : false, // Allow only one `var` statement per function. + "plusplus" : false, // Prohibit use of `++` & `--`. + "sub" : false, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`. + "trailing" : true, // Prohibit trailing whitespaces. + "white" : false // Check against strict whitespace and indentation rules. +} diff --git a/node_modules/express-error-handler/node_modules/mout/.npmignore b/node_modules/express-error-handler/node_modules/mout/.npmignore new file mode 100644 index 000000000..1341acd9e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/.npmignore @@ -0,0 +1,30 @@ +# dumb files +# ========== + +.tmp* +.project +.settings/ +.livereload +.DS_Store? +ehthumbs.db +Icon? +Thumbs.db + + +# stuff not needed by node +# ======================== + +node_modules/ +tests/ +_build/ +doc_html/ +coverage/ + +# we keep the doc/ folder in case npm decides to display it in the future +# also good in case user is using an old version or working offline + +# we also keep the src/ folder in case the user still needs the AMD modules +# after build (see issue #102) + +bower.json +build.js diff --git a/node_modules/express-error-handler/node_modules/mout/.travis.yml b/node_modules/express-error-handler/node_modules/mout/.travis.yml new file mode 100644 index 000000000..324041b4a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/.travis.yml @@ -0,0 +1,15 @@ + language: node_js + node_js: + - "0.8" + script: + - "npm test --coverage" + - "jshint src" + notifications: + irc: + channels: + - "irc.freenode.org#moutjs" + on_success: always + on_failure: always + use_notice: true + skip_join: true + diff --git a/node_modules/express-error-handler/node_modules/mout/CHANGELOG.md b/node_modules/express-error-handler/node_modules/mout/CHANGELOG.md new file mode 100644 index 000000000..6ce1d6f3f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/CHANGELOG.md @@ -0,0 +1,116 @@ +mout changelog +============== + +v0.7.1 (2013/09/18) +------------------- + + - fix `null` value handling in object/get. + +v0.7.0 (2013/09/05) +------------------- + + - add bower ignores. + - add german translation for date localization. + - alias `function` package as `fn` since "function" is a reserved keyword. + - allow second argument on `array/pick`. + - improve `string/makePath` to not remove "//" after protocol. + - make sure methods inside `number` package works with mixed types. + - support arrays on `queryString/encode`. + - support multiple values for same property on `queryString/decode`. + - add `cancel()` method to `throttled/debounced` functions. + - add `function/times`. + - add `lang/toNumber`. + - add `string/insert`. + - add `super_` to constructor on `lang/inheritPrototype`. + + +v0.6.0 (2013/05/22) +------------------- + + - add optional delimeter to `string/unCamelCase` + - allow custom char on `number/pad` + - allow underscore characters in `string/removeNonWord` + - accept `level` on `array/flatten` instead of a flag + - convert underscores to camelCase in `string/camelCase` + - remove `create()` from number/currencyFormat + - add `date/dayOfTheYear` + - add `date/diff` + - add `date/isSame` + - add `date/startOf` + - add `date/strftime` + - add `date/timezoneAbbr` + - add `date/timezoneOffset` + - add `date/totalDaysInYear` + - add `date/weekOfTheYear` + - add `function/timeout` + - add `object/bindAll` + - add `object/functions` + - add `time/convert` + + +v0.5.0 (2013/04/04) +------------------- + + - add `array/collect` + - add `callback` parameter to `object/equals` and `object/deepEquals` to allow + custom compare operations. + - normalize behavior in `array/*` methods to treat `null` values as empty + arrays when reading from array + - add `date/parseIso` + - add `date/isLeapYear` + - add `date/totalDaysInMonth` + - add `object/deepMatches` + - change `function/makeIterator_` to use `deepMatches` (affects nearly all + iteration methods) + - add `thisObj` parameter to `array/min` and `array/max` + + +v0.4.0 (2013/02/26) +------------------- + + - add `object/equals` + - add `object/deepEquals` + - add `object/matches`. + - add `lang/is` and `lang/isnt`. + - add `lang/isInteger`. + - add `array/findIndex`. + - add shorthand syntax to `array/*`, `object/*` and `collection/*` methods. + - improve `number/sign` behavior when value is NaN or +0 or -0. + - improve `lang/isNaN` to actually check if value *is not a number* without + coercing value; so `[]`, `""`, `null` and `"12"` are considered NaN (#39). + - improve `string/contains` to match ES6 behavior (add fromIndex argument). + + +v0.3.0 (2013/02/01) +------------------- + + - add `lang/clone`. + - add `lang/toString`. + - add `string/replace`. + - add `string/WHITE_SPACES` + - rename `function/curry` to `function/partial`. + - allow custom chars in `string/trim`, `ltrim`, and `rtrim`. + - convert values to strings in the `string/*` functions. + + +v0.2.0 (2013/01/13) +------------------- + + - fix bug in `math/ceil` for negative radixes. + - change `object/deepFillIn` and `object/deepMixIn` to recurse only if both + existing and new values are plain objects. Will not recurse into arrays + or objects not created by the Object constructor. + - add `lang/isPlainObject` to check if a file is a valid object and is created + by the Object constructor + - change `lang/clone` behavior when dealing with custom types (avoid cloning + it by default) and add second argument to allow custom behavior if needed. + - rename `lang/clone` to `lang/deepClone`. + - add VERSION property to index.js + - simplify `math/floor`, `math/round`, `math/ceil` and `math/countSteps`. + + +v0.1.0 (2013/01/09) +------------------- + +- Rename project from "amd-utils" to "mout" + diff --git a/node_modules/express-error-handler/node_modules/mout/CONTRIBUTING.md b/node_modules/express-error-handler/node_modules/mout/CONTRIBUTING.md new file mode 100644 index 000000000..65d9add1f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing + +Fork the repo at https://github.com/mout/mout + + > "Write clearly, don't be too clever" - The Elements of Programming Style + +Avoid unnamed functions and follow the other modules structure. By only using named functions it will be easier to extract the code from the AMD module if needed and it will also give better error messages, JavaScript minifiers like [Google Closure Compiler](http://code.google.com/closure/compiler/) and [UglifyJS](https://github.com/mishoo/UglifyJS) will make sure code is as small/optimized as possible. + + > "Make it clear before you make it faster." - The Elements of Programming Style + +Be sure to always create tests for each proposed module. Features will only be merged if they contain proper tests and documentation. + + > "Good code is its own best documentation." - Steve McConnell + +We should do a code review before merging to make sure names makes sense and implementation is as good as possible. + +Try to split your pull requests into logical groups, the smaller the easier to be reviewed/merged. + + + +## Tests & Code Coverage ## + +Tests can be found inside the `tests` folder, to execute them in the browser open the `tests/runner.html`. The same tests also work on node.js by running `npm test`. + +We should have tests for all methods and ensure we have a high code coverage through our continuous integration server ([travis](https://travis-ci.org/mout/mout)). When you ask for a pull request Travis will automatically run the tests on node.js and check the code coverage as well. + +We run `node build pkg` automatically before any `npm test`, so specs and packages should always be in sync. (will avoid human mistakes) + +To check code coverage run `npm test --coverage`, it will generate the reports inside the `coverage` folder and also log the results. Please note that node.js doesn't execute all code branches since we have some conditionals that are only met on old JavaScript engines (eg. IE 7-8), so we will never have 100% code coverage (but should be close to it). + + + +## Build Script ## + +The [build script](https://github.com/mout/mout/wiki/Build-Script) can be extremely helpful and can avoid human mistakes, use it. + + + +## Admins / Pull Requests ## + +Even if you are an admin (have commit rights) please do pull requests when adding new features or changing current behavior, that way we can review the work and discuss. Feel free to push changes that doesn't affect behavior without asking for a pull request (readme, changelog, build script, typos, refactoring, ...). + + + +## Large changes ## + +If you are proposing some major change, please create an issue to discuss it first. (maybe it's outside the scope of the project) + + + +## Questions / IRC / Wiki / Issue Tracker ## + +When in doubt ask someone on IRC to help you ([#moutjs on irc.freenode.net](http://webchat.freenode.net/?channels=moutjs)) or create a [new issue](http://github.com/mout/mout/issues). + +The [project wiki](https://github.com/mout/mout/wiki) can also be a good resource of information. + + +--- + +Check the [contributors list at github](https://github.com/mout/mout/contributors). + diff --git a/node_modules/express-error-handler/node_modules/mout/LICENSE.md b/node_modules/express-error-handler/node_modules/mout/LICENSE.md new file mode 100644 index 000000000..e9ccc2bea --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) +## Copyright (c) 2012, 2013 moutjs team and contributors (http://moutjs.com) + +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/express-error-handler/node_modules/mout/README.md b/node_modules/express-error-handler/node_modules/mout/README.md new file mode 100644 index 000000000..872943bd1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/README.md @@ -0,0 +1,63 @@ +![mout](http://moutjs.com/logo.png "Modular JavaScript Utilties") + +http://moutjs.com/ + +[![Build Status](https://travis-ci.org/mout/mout.png?branch=master)](https://travis-ci.org/mout/mout) + +All code is library agnostic and consist mostly of helper methods that aren't +directly related with the DOM, the purpose of this library isn't to replace +Dojo, jQuery, YUI, Mootools, etc, but to provide modular solutions for common +problems that aren't solved by most of them. Consider it as a crossbrowser +JavaScript standard library. + + + +## Main goals ## + + - increase code reuse; + - be clear (code should be clean/readable); + - be easy to debug; + - be easy to maintain; + - follow best practices; + - follow standards when possible; + - **don't convert JavaScript into another language!** + - be compatible with other frameworks; + - be modular; + - have unit tests for all modules; + - work on multiple environments (IE7+, modern browsers, node.js); + + + +## What shouldn't be here ## + + - UI components; + - CSS selector engine; + - Event system - pub/sub; + - Template engine; + - Anything that isn't generic enough to be on a standard library; + - Anything that could be a separate library and/or isn't a modular utility... + + + +## API Documentation ## + +Online documentation can be found at http://moutjs.com/ or inside the +`doc` folder. + + + +## FAQ / Wiki / IRC ## + +For more info about project structure, design decisions, tips, how to +contribute, build system, etc, please check the [project +wiki](https://github.com/mout/mout/wiki). + +We also have an IRC channel [#moutjs on +irc.freenode.net](http://webchat.freenode.net/?channels=moutjs) + + + +## License ## + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). + diff --git a/node_modules/express-error-handler/node_modules/mout/array.js b/node_modules/express-error-handler/node_modules/mout/array.js new file mode 100644 index 000000000..89d388ba1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array.js @@ -0,0 +1,46 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'append' : require('./array/append'), + 'collect' : require('./array/collect'), + 'combine' : require('./array/combine'), + 'compact' : require('./array/compact'), + 'contains' : require('./array/contains'), + 'difference' : require('./array/difference'), + 'every' : require('./array/every'), + 'filter' : require('./array/filter'), + 'find' : require('./array/find'), + 'findIndex' : require('./array/findIndex'), + 'flatten' : require('./array/flatten'), + 'forEach' : require('./array/forEach'), + 'indexOf' : require('./array/indexOf'), + 'insert' : require('./array/insert'), + 'intersection' : require('./array/intersection'), + 'invoke' : require('./array/invoke'), + 'join' : require('./array/join'), + 'lastIndexOf' : require('./array/lastIndexOf'), + 'map' : require('./array/map'), + 'max' : require('./array/max'), + 'min' : require('./array/min'), + 'pick' : require('./array/pick'), + 'pluck' : require('./array/pluck'), + 'range' : require('./array/range'), + 'reduce' : require('./array/reduce'), + 'reduceRight' : require('./array/reduceRight'), + 'reject' : require('./array/reject'), + 'remove' : require('./array/remove'), + 'removeAll' : require('./array/removeAll'), + 'shuffle' : require('./array/shuffle'), + 'some' : require('./array/some'), + 'sort' : require('./array/sort'), + 'split' : require('./array/split'), + 'toLookup' : require('./array/toLookup'), + 'union' : require('./array/union'), + 'unique' : require('./array/unique'), + 'xor' : require('./array/xor'), + 'zip' : require('./array/zip') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/append.js b/node_modules/express-error-handler/node_modules/mout/array/append.js new file mode 100644 index 000000000..bf74037e2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/append.js @@ -0,0 +1,21 @@ + + + /** + * Appends an array to the end of another. + * The first array will be modified. + */ + function append(arr1, arr2) { + if (arr2 == null) { + return arr1; + } + + var pad = arr1.length, + i = -1, + len = arr2.length; + while (++i < len) { + arr1[pad + i] = arr2[i]; + } + return arr1; + } + module.exports = append; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/collect.js b/node_modules/express-error-handler/node_modules/mout/array/collect.js new file mode 100644 index 000000000..586374938 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/collect.js @@ -0,0 +1,27 @@ +var append = require('./append'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Maps the items in the array and concatenates the result arrays. + */ + function collect(arr, callback, thisObj){ + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length; + while (++i < len) { + var value = callback(arr[i], i, arr); + if (value != null) { + append(results, value); + } + } + + return results; + } + + module.exports = collect; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/combine.js b/node_modules/express-error-handler/node_modules/mout/array/combine.js new file mode 100644 index 000000000..d66e6212d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/combine.js @@ -0,0 +1,22 @@ +var indexOf = require('./indexOf'); + + /** + * Combines an array with all the items of another. + * Does not allow duplicates and is case and type sensitive. + */ + function combine(arr1, arr2) { + if (arr2 == null) { + return arr1; + } + + var i = -1, len = arr2.length; + while (++i < len) { + if (indexOf(arr1, arr2[i]) === -1) { + arr1.push(arr2[i]); + } + } + + return arr1; + } + module.exports = combine; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/compact.js b/node_modules/express-error-handler/node_modules/mout/array/compact.js new file mode 100644 index 000000000..74c176edf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/compact.js @@ -0,0 +1,13 @@ +var filter = require('./filter'); + + /** + * Remove all null/undefined items from array. + */ + function compact(arr) { + return filter(arr, function(val){ + return (val != null); + }); + } + + module.exports = compact; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/contains.js b/node_modules/express-error-handler/node_modules/mout/array/contains.js new file mode 100644 index 000000000..92bb6ad9a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/contains.js @@ -0,0 +1,10 @@ +var indexOf = require('./indexOf'); + + /** + * If array contains values. + */ + function contains(arr, val) { + return indexOf(arr, val) !== -1; + } + module.exports = contains; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/difference.js b/node_modules/express-error-handler/node_modules/mout/array/difference.js new file mode 100644 index 000000000..d05705104 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/difference.js @@ -0,0 +1,22 @@ +var unique = require('./unique'); +var filter = require('./filter'); +var some = require('./some'); +var contains = require('./contains'); + + + /** + * Return a new Array with elements that aren't present in the other Arrays. + */ + function difference(arr) { + var arrs = Array.prototype.slice.call(arguments, 1), + result = filter(unique(arr), function(needle){ + return !some(arrs, function(haystack){ + return contains(haystack, needle); + }); + }); + return result; + } + + module.exports = difference; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/every.js b/node_modules/express-error-handler/node_modules/mout/array/every.js new file mode 100644 index 000000000..ac5988325 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/every.js @@ -0,0 +1,27 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Array every + */ + function every(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = true; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (!callback(arr[i], i, arr) ) { + result = false; + break; + } + } + + return result; + } + + module.exports = every; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/filter.js b/node_modules/express-error-handler/node_modules/mout/array/filter.js new file mode 100644 index 000000000..f0e74199f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/filter.js @@ -0,0 +1,26 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Array filter + */ + function filter(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + if (callback(value, i, arr)) { + results.push(value); + } + } + + return results; + } + + module.exports = filter; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/find.js b/node_modules/express-error-handler/node_modules/mout/array/find.js new file mode 100644 index 000000000..b4a73131a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/find.js @@ -0,0 +1,13 @@ +var findIndex = require('./findIndex'); + + /** + * Returns first item that matches criteria + */ + function find(arr, iterator, thisObj){ + var idx = findIndex(arr, iterator, thisObj); + return idx >= 0? arr[idx] : void(0); + } + + module.exports = find; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/findIndex.js b/node_modules/express-error-handler/node_modules/mout/array/findIndex.js new file mode 100644 index 000000000..53f22a5f6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/findIndex.js @@ -0,0 +1,23 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Returns the index of the first item that matches criteria + */ + function findIndex(arr, iterator, thisObj){ + iterator = makeIterator(iterator, thisObj); + if (arr == null) { + return -1; + } + + var i = -1, len = arr.length; + while (++i < len) { + if (iterator(arr[i], i, arr)) { + return i; + } + } + + return -1; + } + + module.exports = findIndex; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/flatten.js b/node_modules/express-error-handler/node_modules/mout/array/flatten.js new file mode 100644 index 000000000..aa9757abe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/flatten.js @@ -0,0 +1,43 @@ +var isArray = require('../lang/isArray'); +var append = require('./append'); + + /* + * Helper function to flatten to a destination array. + * Used to remove the need to create intermediate arrays while flattening. + */ + function flattenTo(arr, result, level) { + if (arr == null) { + return result; + } else if (level === 0) { + append(result, arr); + return result; + } + + var value, + i = -1, + len = arr.length; + while (++i < len) { + value = arr[i]; + if (isArray(value)) { + flattenTo(value, result, level - 1); + } else { + result.push(value); + } + } + return result; + } + + /** + * Recursively flattens an array. + * A new array containing all the elements is returned. + * If `shallow` is true, it will only flatten one level. + */ + function flatten(arr, level) { + level = level == null? -1 : level; + return flattenTo(arr, [], level); + } + + module.exports = flatten; + + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/forEach.js b/node_modules/express-error-handler/node_modules/mout/array/forEach.js new file mode 100644 index 000000000..268e506fa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/forEach.js @@ -0,0 +1,23 @@ + + + /** + * Array forEach + */ + function forEach(arr, callback, thisObj) { + if (arr == null) { + return; + } + var i = -1, + len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if ( callback.call(thisObj, arr[i], i, arr) === false ) { + break; + } + } + } + + module.exports = forEach; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/indexOf.js b/node_modules/express-error-handler/node_modules/mout/array/indexOf.js new file mode 100644 index 000000000..6a9ac8329 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/indexOf.js @@ -0,0 +1,28 @@ + + + /** + * Array.indexOf + */ + function indexOf(arr, item, fromIndex) { + fromIndex = fromIndex || 0; + if (arr == null) { + return -1; + } + + var len = arr.length, + i = fromIndex < 0 ? len + fromIndex : fromIndex; + while (i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (arr[i] === item) { + return i; + } + + i++; + } + + return -1; + } + + module.exports = indexOf; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/insert.js b/node_modules/express-error-handler/node_modules/mout/array/insert.js new file mode 100644 index 000000000..f1f95b752 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/insert.js @@ -0,0 +1,15 @@ +var difference = require('./difference'); +var toArray = require('../lang/toArray'); + + /** + * Insert item into array if not already present. + */ + function insert(arr, rest_items) { + var diff = difference(toArray(arguments).slice(1), arr); + if (diff.length) { + Array.prototype.push.apply(arr, diff); + } + return arr.length; + } + module.exports = insert; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/intersection.js b/node_modules/express-error-handler/node_modules/mout/array/intersection.js new file mode 100644 index 000000000..e61700628 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/intersection.js @@ -0,0 +1,23 @@ +var unique = require('./unique'); +var filter = require('./filter'); +var every = require('./every'); +var contains = require('./contains'); + + + /** + * Return a new Array with elements common to all Arrays. + * - based on underscore.js implementation + */ + function intersection(arr) { + var arrs = Array.prototype.slice.call(arguments, 1), + result = filter(unique(arr), function(needle){ + return every(arrs, function(haystack){ + return contains(haystack, needle); + }); + }); + return result; + } + + module.exports = intersection; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/invoke.js b/node_modules/express-error-handler/node_modules/mout/array/invoke.js new file mode 100644 index 000000000..d7be6cdc0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/invoke.js @@ -0,0 +1,23 @@ + + + /** + * Call `methodName` on each item of the array passing custom arguments if + * needed. + */ + function invoke(arr, methodName, var_args){ + if (arr == null) { + return arr; + } + + var args = Array.prototype.slice.call(arguments, 2); + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + value[methodName].apply(value, args); + } + + return arr; + } + + module.exports = invoke; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/join.js b/node_modules/express-error-handler/node_modules/mout/array/join.js new file mode 100644 index 000000000..71d8bd20f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/join.js @@ -0,0 +1,17 @@ +var filter = require('./filter'); + + function isValidString(val) { + return (val != null && val !== ''); + } + + /** + * Joins strings with the specified separator inserted between each value. + * Null values and empty strings will be excluded. + */ + function join(items, separator) { + separator = separator || ''; + return filter(items, isValidString).join(separator); + } + + module.exports = join; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/lastIndexOf.js b/node_modules/express-error-handler/node_modules/mout/array/lastIndexOf.js new file mode 100644 index 000000000..ee44a25bf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/lastIndexOf.js @@ -0,0 +1,28 @@ + + + /** + * Array lastIndexOf + */ + function lastIndexOf(arr, item, fromIndex) { + if (arr == null) { + return -1; + } + + var len = arr.length; + fromIndex = (fromIndex == null || fromIndex >= len)? len - 1 : fromIndex; + fromIndex = (fromIndex < 0)? len + fromIndex : fromIndex; + + while (fromIndex >= 0) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (arr[fromIndex] === item) { + return fromIndex; + } + fromIndex--; + } + + return -1; + } + + module.exports = lastIndexOf; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/map.js b/node_modules/express-error-handler/node_modules/mout/array/map.js new file mode 100644 index 000000000..7b7fb3318 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/map.js @@ -0,0 +1,22 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Array map + */ + function map(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null){ + return results; + } + + var i = -1, len = arr.length; + while (++i < len) { + results[i] = callback(arr[i], i, arr); + } + + return results; + } + + module.exports = map; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/max.js b/node_modules/express-error-handler/node_modules/mout/array/max.js new file mode 100644 index 000000000..0b8f25942 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/max.js @@ -0,0 +1,34 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Return maximum value inside array + */ + function max(arr, iterator, thisObj){ + if (arr == null || !arr.length) { + return Infinity; + } else if (arr.length && !iterator) { + return Math.max.apply(Math, arr); + } else { + iterator = makeIterator(iterator, thisObj); + var result, + compare = -Infinity, + value, + temp; + + var i = -1, len = arr.length; + while (++i < len) { + value = arr[i]; + temp = iterator(value, i, arr); + if (temp > compare) { + compare = temp; + result = value; + } + } + + return result; + } + } + + module.exports = max; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/min.js b/node_modules/express-error-handler/node_modules/mout/array/min.js new file mode 100644 index 000000000..ed6cc6a14 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/min.js @@ -0,0 +1,34 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Return minimum value inside array + */ + function min(arr, iterator, thisObj){ + if (arr == null || !arr.length) { + return -Infinity; + } else if (arr.length && !iterator) { + return Math.min.apply(Math, arr); + } else { + iterator = makeIterator(iterator, thisObj); + var result, + compare = Infinity, + value, + temp; + + var i = -1, len = arr.length; + while (++i < len) { + value = arr[i]; + temp = iterator(value, i, arr); + if (temp < compare) { + compare = temp; + result = value; + } + } + + return result; + } + } + + module.exports = min; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/pick.js b/node_modules/express-error-handler/node_modules/mout/array/pick.js new file mode 100644 index 000000000..64086784f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/pick.js @@ -0,0 +1,31 @@ +var randInt = require('../random/randInt'); + + /** + * Remove random item(s) from the Array and return it. + * Returns an Array of items if [nItems] is provided or a single item if + * it isn't specified. + */ + function pick(arr, nItems){ + if (nItems != null) { + var result = []; + if (nItems > 0 && arr && arr.length) { + nItems = nItems > arr.length? arr.length : nItems; + while (nItems--) { + result.push( pickOne(arr) ); + } + } + return result; + } + return (arr && arr.length)? pickOne(arr) : void(0); + } + + + function pickOne(arr){ + var idx = randInt(0, arr.length - 1); + return arr.splice(idx, 1)[0]; + } + + + module.exports = pick; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/pluck.js b/node_modules/express-error-handler/node_modules/mout/array/pluck.js new file mode 100644 index 000000000..fef4043bb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/pluck.js @@ -0,0 +1,12 @@ +var map = require('./map'); + + /** + * Extract a list of property values. + */ + function pluck(arr, propName){ + return map(arr, propName); + } + + module.exports = pluck; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/range.js b/node_modules/express-error-handler/node_modules/mout/array/range.js new file mode 100644 index 000000000..31d3c7702 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/range.js @@ -0,0 +1,27 @@ +var countSteps = require('../math/countSteps'); + + /** + * Returns an Array of numbers inside range. + */ + function range(start, stop, step) { + if (stop == null) { + stop = start; + start = 0; + } + step = step || 1; + + var result = [], + nSteps = countSteps(stop - start, step), + i = start; + + while (i <= stop) { + result.push(i); + i += step; + } + + return result; + } + + module.exports = range; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/reduce.js b/node_modules/express-error-handler/node_modules/mout/array/reduce.js new file mode 100644 index 000000000..827f428fe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/reduce.js @@ -0,0 +1,33 @@ + + + /** + * Array reduce + */ + function reduce(arr, fn, initVal) { + // check for args.length since initVal might be "undefined" see #gh-57 + var hasInit = arguments.length > 2, + result = initVal; + + if (arr == null || !arr.length) { + if (!hasInit) { + throw new Error('reduce of empty array with no initial value'); + } else { + return initVal; + } + } + + var i = -1, len = arr.length; + while (++i < len) { + if (!hasInit) { + result = arr[i]; + hasInit = true; + } else { + result = fn(result, arr[i], i, arr); + } + } + + return result; + } + + module.exports = reduce; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/reduceRight.js b/node_modules/express-error-handler/node_modules/mout/array/reduceRight.js new file mode 100644 index 000000000..e36fd4aac --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/reduceRight.js @@ -0,0 +1,34 @@ + + + /** + * Array reduceRight + */ + function reduceRight(arr, fn, initVal) { + // check for args.length since initVal might be "undefined" see #gh-57 + var hasInit = arguments.length > 2; + + if (arr == null || !arr.length) { + if (hasInit) { + return initVal; + } else { + throw new Error('reduce of empty array with no initial value'); + } + } + + var i = arr.length, result = initVal, value; + while (--i >= 0) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + value = arr[i]; + if (!hasInit) { + result = value; + hasInit = true; + } else { + result = fn(result, value, i, arr); + } + } + return result; + } + + module.exports = reduceRight; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/reject.js b/node_modules/express-error-handler/node_modules/mout/array/reject.js new file mode 100644 index 000000000..0cfc8b1a8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/reject.js @@ -0,0 +1,25 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Array reject + */ + function reject(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + if (!callback(value, i, arr)) { + results.push(value); + } + } + + return results; + } + + module.exports = reject; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/remove.js b/node_modules/express-error-handler/node_modules/mout/array/remove.js new file mode 100644 index 000000000..aa6517dbe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/remove.js @@ -0,0 +1,13 @@ +var indexOf = require('./indexOf'); + + /** + * Remove a single item from the array. + * (it won't remove duplicates, just a single item) + */ + function remove(arr, item){ + var idx = indexOf(arr, item); + if (idx !== -1) arr.splice(idx, 1); + } + + module.exports = remove; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/removeAll.js b/node_modules/express-error-handler/node_modules/mout/array/removeAll.js new file mode 100644 index 000000000..d5f7f3b61 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/removeAll.js @@ -0,0 +1,15 @@ +var indexOf = require('./indexOf'); + + /** + * Remove all instances of an item from array. + */ + function removeAll(arr, item){ + var idx = indexOf(arr, item); + while (idx !== -1) { + arr.splice(idx, 1); + idx = indexOf(arr, item, idx); + } + } + + module.exports = removeAll; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/shuffle.js b/node_modules/express-error-handler/node_modules/mout/array/shuffle.js new file mode 100644 index 000000000..99d0660fb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/shuffle.js @@ -0,0 +1,28 @@ +var randInt = require('../random/randInt'); + + /** + * Shuffle array items. + */ + function shuffle(arr) { + var results = [], + rnd; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + if (!i) { + results[0] = arr[0]; + } else { + rnd = randInt(0, i); + results[i] = results[rnd]; + results[rnd] = arr[i]; + } + } + + return results; + } + + module.exports = shuffle; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/some.js b/node_modules/express-error-handler/node_modules/mout/array/some.js new file mode 100644 index 000000000..8d17772b2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/some.js @@ -0,0 +1,27 @@ +var makeIterator = require('../function/makeIterator_'); + + /** + * Array some + */ + function some(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = false; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if ( callback(arr[i], i, arr) ) { + result = true; + break; + } + } + + return result; + } + + module.exports = some; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/sort.js b/node_modules/express-error-handler/node_modules/mout/array/sort.js new file mode 100644 index 000000000..7807339b3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/sort.js @@ -0,0 +1,55 @@ + + + /** + * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) + */ + function mergeSort(arr, compareFn) { + if (arr == null) { + return []; + } else if (arr.length < 2) { + return arr; + } + + if (compareFn == null) { + compareFn = defaultCompare; + } + + var mid, left, right; + + mid = ~~(arr.length / 2); + left = mergeSort( arr.slice(0, mid), compareFn ); + right = mergeSort( arr.slice(mid, arr.length), compareFn ); + + return merge(left, right, compareFn); + } + + function defaultCompare(a, b) { + return a < b ? -1 : (a > b? 1 : 0); + } + + function merge(left, right, compareFn) { + var result = []; + + while (left.length && right.length) { + if (compareFn(left[0], right[0]) <= 0) { + // if 0 it should preserve same order (stable) + result.push(left.shift()); + } else { + result.push(right.shift()); + } + } + + if (left.length) { + result.push.apply(result, left); + } + + if (right.length) { + result.push.apply(result, right); + } + + return result; + } + + module.exports = mergeSort; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/split.js b/node_modules/express-error-handler/node_modules/mout/array/split.js new file mode 100644 index 000000000..4f3ba50c9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/split.js @@ -0,0 +1,35 @@ + + + /** + * Split array into a fixed number of segments. + */ + function split(array, segments) { + segments = segments || 2; + var results = []; + if (array == null) { + return results; + } + + var minLength = Math.floor(array.length / segments), + remainder = array.length % segments, + i = 0, + len = array.length, + segmentIndex = 0, + segmentLength; + + while (i < len) { + segmentLength = minLength; + if (segmentIndex < remainder) { + segmentLength++; + } + + results.push(array.slice(i, i + segmentLength)); + + segmentIndex++; + i += segmentLength; + } + + return results; + } + module.exports = split; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/toLookup.js b/node_modules/express-error-handler/node_modules/mout/array/toLookup.js new file mode 100644 index 000000000..ce4c55dd1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/toLookup.js @@ -0,0 +1,28 @@ +var isFunction = require('../lang/isFunction'); + + /** + * Creates an object that holds a lookup for the objects in the array. + */ + function toLookup(arr, key) { + var result = {}; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length, value; + if (isFunction(key)) { + while (++i < len) { + value = arr[i]; + result[key(value)] = value; + } + } else { + while (++i < len) { + value = arr[i]; + result[value[key]] = value; + } + } + + return result; + } + module.exports = toLookup; + diff --git a/node_modules/express-error-handler/node_modules/mout/array/union.js b/node_modules/express-error-handler/node_modules/mout/array/union.js new file mode 100644 index 000000000..f1334a919 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/union.js @@ -0,0 +1,19 @@ +var unique = require('./unique'); +var append = require('./append'); + + /** + * Concat multiple arrays and remove duplicates + */ + function union(arrs) { + var results = []; + var i = -1, len = arguments.length; + while (++i < len) { + append(results, arguments[i]); + } + + return unique(results); + } + + module.exports = union; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/unique.js b/node_modules/express-error-handler/node_modules/mout/array/unique.js new file mode 100644 index 000000000..0192b2df6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/unique.js @@ -0,0 +1,17 @@ +var indexOf = require('./indexOf'); +var filter = require('./filter'); + + /** + * @return {array} Array of unique items + */ + function unique(arr){ + return filter(arr, isUnique); + } + + function isUnique(item, i, arr){ + return indexOf(arr, item, i+1) === -1; + } + + module.exports = unique; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/xor.js b/node_modules/express-error-handler/node_modules/mout/array/xor.js new file mode 100644 index 000000000..c125a9964 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/xor.js @@ -0,0 +1,26 @@ +var unique = require('./unique'); +var filter = require('./filter'); +var contains = require('./contains'); + + + /** + * Exclusive OR. Returns items that are present in a single array. + * - like ptyhon's `symmetric_difference` + */ + function xor(arr1, arr2) { + arr1 = unique(arr1); + arr2 = unique(arr2); + + var a1 = filter(arr1, function(item){ + return !contains(arr2, item); + }), + a2 = filter(arr2, function(item){ + return !contains(arr1, item); + }); + + return a1.concat(a2); + } + + module.exports = xor; + + diff --git a/node_modules/express-error-handler/node_modules/mout/array/zip.js b/node_modules/express-error-handler/node_modules/mout/array/zip.js new file mode 100644 index 000000000..8bce9c075 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/array/zip.js @@ -0,0 +1,28 @@ +var max = require('./max'); +var map = require('./map'); + + function getLength(arr) { + return arr == null ? 0 : arr.length; + } + + /** + * Merges together the values of each of the arrays with the values at the + * corresponding position. + */ + function zip(arr){ + var len = arr ? max(map(arguments, getLength)) : 0, + results = [], + i = -1; + while (++i < len) { + // jshint loopfunc: true + results.push(map(arguments, function(item) { + return item == null ? undefined : item[i]; + })); + } + + return results; + } + + module.exports = zip; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection.js b/node_modules/express-error-handler/node_modules/mout/collection.js new file mode 100644 index 000000000..d5cf6cad9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection.js @@ -0,0 +1,22 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'contains' : require('./collection/contains'), + 'every' : require('./collection/every'), + 'filter' : require('./collection/filter'), + 'find' : require('./collection/find'), + 'forEach' : require('./collection/forEach'), + 'make_' : require('./collection/make_'), + 'map' : require('./collection/map'), + 'max' : require('./collection/max'), + 'min' : require('./collection/min'), + 'pluck' : require('./collection/pluck'), + 'reduce' : require('./collection/reduce'), + 'reject' : require('./collection/reject'), + 'size' : require('./collection/size'), + 'some' : require('./collection/some') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/contains.js b/node_modules/express-error-handler/node_modules/mout/collection/contains.js new file mode 100644 index 000000000..a73f994bc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/contains.js @@ -0,0 +1,9 @@ +var make = require('./make_'); +var arrContains = require('../array/contains'); +var objContains = require('../object/contains'); + + /** + */ + module.exports = make(arrContains, objContains); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/every.js b/node_modules/express-error-handler/node_modules/mout/collection/every.js new file mode 100644 index 000000000..300e03c56 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/every.js @@ -0,0 +1,9 @@ +var make = require('./make_'); +var arrEvery = require('../array/every'); +var objEvery = require('../object/every'); + + /** + */ + module.exports = make(arrEvery, objEvery); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/filter.js b/node_modules/express-error-handler/node_modules/mout/collection/filter.js new file mode 100644 index 000000000..387570057 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/filter.js @@ -0,0 +1,23 @@ +var forEach = require('./forEach'); +var makeIterator = require('../function/makeIterator_'); + + /** + * filter collection values, returns array. + */ + function filter(list, iterator, thisObj) { + iterator = makeIterator(iterator, thisObj); + var results = []; + if (!list) { + return results; + } + forEach(list, function(value, index, list) { + if (iterator(value, index, list)) { + results[results.length] = value; + } + }); + return results; + } + + module.exports = filter; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/find.js b/node_modules/express-error-handler/node_modules/mout/collection/find.js new file mode 100644 index 000000000..14317e647 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/find.js @@ -0,0 +1,10 @@ +var make = require('./make_'); +var arrFind = require('../array/find'); +var objFind = require('../object/find'); + + /** + * Find value that returns true on iterator check. + */ + module.exports = make(arrFind, objFind); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/forEach.js b/node_modules/express-error-handler/node_modules/mout/collection/forEach.js new file mode 100644 index 000000000..6e28dcb10 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/forEach.js @@ -0,0 +1,9 @@ +var make = require('./make_'); +var arrForEach = require('../array/forEach'); +var objForEach = require('../object/forOwn'); + + /** + */ + module.exports = make(arrForEach, objForEach); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/make_.js b/node_modules/express-error-handler/node_modules/mout/collection/make_.js new file mode 100644 index 000000000..029d27bf7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/make_.js @@ -0,0 +1,19 @@ + + + /** + * internal method used to create other collection modules. + */ + function makeCollectionMethod(arrMethod, objMethod, defaultReturn) { + return function(){ + var args = Array.prototype.slice.call(arguments); + if (args[0] == null) { + return defaultReturn; + } + // array-like is treated as array + return (typeof args[0].length === 'number')? arrMethod.apply(null, args) : objMethod.apply(null, args); + }; + } + + module.exports = makeCollectionMethod; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/map.js b/node_modules/express-error-handler/node_modules/mout/collection/map.js new file mode 100644 index 000000000..fc157f53f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/map.js @@ -0,0 +1,23 @@ +var isObject = require('../lang/isObject'); +var values = require('../object/values'); +var arrMap = require('../array/map'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Map collection values, returns Array. + */ + function map(list, callback, thisObj) { + callback = makeIterator(callback, thisObj); + // list.length to check array-like object, if not array-like + // we simply map all the object values + if( isObject(list) && list.length == null ){ + list = values(list); + } + return arrMap(list, function (val, key, list) { + return callback(val, key, list); + }); + } + + module.exports = map; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/max.js b/node_modules/express-error-handler/node_modules/mout/collection/max.js new file mode 100644 index 000000000..a8490e7e8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/max.js @@ -0,0 +1,10 @@ +var make = require('./make_'); +var arrMax = require('../array/max'); +var objMax = require('../object/max'); + + /** + * Get maximum value inside collection + */ + module.exports = make(arrMax, objMax); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/min.js b/node_modules/express-error-handler/node_modules/mout/collection/min.js new file mode 100644 index 000000000..51d9f148d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/min.js @@ -0,0 +1,10 @@ +var make = require('./make_'); +var arrMin = require('../array/min'); +var objMin = require('../object/min'); + + /** + * Get minimum value inside collection. + */ + module.exports = make(arrMin, objMin); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/pluck.js b/node_modules/express-error-handler/node_modules/mout/collection/pluck.js new file mode 100644 index 000000000..9b2837761 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/pluck.js @@ -0,0 +1,14 @@ +var map = require('./map'); + + /** + * Extract a list of property values. + */ + function pluck(list, key) { + return map(list, function(value) { + return value[key]; + }); + } + + module.exports = pluck; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/reduce.js b/node_modules/express-error-handler/node_modules/mout/collection/reduce.js new file mode 100644 index 000000000..4c075735d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/reduce.js @@ -0,0 +1,9 @@ +var make = require('./make_'); +var arrReduce = require('../array/reduce'); +var objReduce = require('../object/reduce'); + + /** + */ + module.exports = make(arrReduce, objReduce); + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/reject.js b/node_modules/express-error-handler/node_modules/mout/collection/reject.js new file mode 100644 index 000000000..2a92e3b3d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/reject.js @@ -0,0 +1,16 @@ +var filter = require('./filter'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Inverse or collection/filter + */ + function reject(list, iterator, thisObj) { + iterator = makeIterator(iterator, thisObj); + return filter(list, function(value, index, list) { + return !iterator(value, index, list); + }, thisObj); + } + + module.exports = reject; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/size.js b/node_modules/express-error-handler/node_modules/mout/collection/size.js new file mode 100644 index 000000000..244e33e65 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/size.js @@ -0,0 +1,19 @@ +var isArray = require('../lang/isArray'); +var objSize = require('../object/size'); + + /** + * Get collection size + */ + function size(list) { + if (!list) { + return 0; + } + if (isArray(list)) { + return list.length; + } + return objSize(list); + } + + module.exports = size; + + diff --git a/node_modules/express-error-handler/node_modules/mout/collection/some.js b/node_modules/express-error-handler/node_modules/mout/collection/some.js new file mode 100644 index 000000000..48fd252e5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/collection/some.js @@ -0,0 +1,9 @@ +var make = require('./make_'); +var arrSome = require('../array/some'); +var objSome = require('../object/some'); + + /** + */ + module.exports = make(arrSome, objSome); + + diff --git a/node_modules/express-error-handler/node_modules/mout/date.js b/node_modules/express-error-handler/node_modules/mout/date.js new file mode 100644 index 000000000..1cde1a95c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date.js @@ -0,0 +1,21 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'dayOfTheYear' : require('./date/dayOfTheYear'), + 'diff' : require('./date/diff'), + 'i18n_' : require('./date/i18n_'), + 'isLeapYear' : require('./date/isLeapYear'), + 'isSame' : require('./date/isSame'), + 'parseIso' : require('./date/parseIso'), + 'startOf' : require('./date/startOf'), + 'strftime' : require('./date/strftime'), + 'timezoneAbbr' : require('./date/timezoneAbbr'), + 'timezoneOffset' : require('./date/timezoneOffset'), + 'totalDaysInMonth' : require('./date/totalDaysInMonth'), + 'totalDaysInYear' : require('./date/totalDaysInYear'), + 'weekOfTheYear' : require('./date/weekOfTheYear') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/dayOfTheYear.js b/node_modules/express-error-handler/node_modules/mout/date/dayOfTheYear.js new file mode 100644 index 000000000..85905c5a4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/dayOfTheYear.js @@ -0,0 +1,13 @@ +var isDate = require('../lang/isDate'); + + /** + * return the day of the year (1..366) + */ + function dayOfTheYear(date){ + return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - + Date.UTC(date.getFullYear(), 0, 1)) / 86400000 + 1; + } + + module.exports = dayOfTheYear; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/diff.js b/node_modules/express-error-handler/node_modules/mout/date/diff.js new file mode 100644 index 000000000..1131cdcbe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/diff.js @@ -0,0 +1,130 @@ +var totalDaysInMonth = require('./totalDaysInMonth'); +var totalDaysInYear = require('./totalDaysInYear'); +var convert = require('../time/convert'); + + /** + * calculate the difference between dates (range) + */ + function diff(start, end, unitName){ + // sort the dates to make it easier to process (specially year/month) + if (start > end) { + var swap = start; + start = end; + end = swap; + } + + var output; + + if (unitName === 'month') { + output = getMonthsDiff(start, end); + } else if (unitName === 'year'){ + output = getYearsDiff(start, end); + } else if (unitName != null) { + if (unitName === 'day') { + // ignore timezone difference because of daylight savings time + start = toUtc(start); + end = toUtc(end); + } + output = convert(end - start, 'ms', unitName); + } else { + output = end - start; + } + + return output; + } + + + function toUtc(d){ + // we ignore timezone differences on purpose because of daylight + // savings time, otherwise it would return fractional days/weeks even + // if a full day elapsed. eg: + // Wed Feb 12 2014 00:00:00 GMT-0200 (BRST) + // Sun Feb 16 2014 00:00:00 GMT-0300 (BRT) + // diff should be 4 days and not 4.041666666666667 + return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), + d.getHours(), d.getMinutes(), d.getSeconds(), + d.getMilliseconds()); + } + + + function getMonthsDiff(start, end){ + return getElapsedMonths(start, end) + + getElapsedYears(start, end) * 12 + + getFractionalMonth(start, end); + } + + + function getYearsDiff(start, end){ + var elapsedYears = getElapsedYears(start, end); + return elapsedYears + getFractionalYear(start, end, elapsedYears); + } + + + function getElapsedMonths(start, end){ + var monthDiff = end.getMonth() - start.getMonth(); + if (monthDiff < 0) { + monthDiff += 12; + } + // less than a full month + if (start.getDate() > end.getDate()) { + monthDiff -= 1; + } + return monthDiff; + } + + + function getElapsedYears(start, end){ + var yearDiff = end.getFullYear() - start.getFullYear(); + // less than a full year + if (start.getMonth() > end.getMonth()) { + yearDiff -= 1; + } + return yearDiff; + } + + + function getFractionalMonth(start, end){ + var fractionalDiff = 0; + var startDay = start.getDate(); + var endDay = end.getDate(); + + if (startDay !== endDay) { + var startTotalDays = totalDaysInMonth(start); + var endTotalDays = totalDaysInMonth(end); + var totalDays; + var daysElapsed; + + if (startDay > endDay) { + // eg: Jan 29 - Feb 27 (29 days elapsed but not a full month) + var baseDay = startTotalDays - startDay; + daysElapsed = endDay + baseDay; + // total days should be relative to 1st day of next month if + // startDay > endTotalDays + totalDays = (startDay > endTotalDays)? + endTotalDays + baseDay + 1 : startDay + baseDay; + } else { + // fractional is only based on endMonth eg: Jan 12 - Feb 18 + // (6 fractional days, 28 days until next full month) + daysElapsed = endDay - startDay; + totalDays = endTotalDays; + } + + fractionalDiff = daysElapsed / totalDays; + } + + return fractionalDiff; + } + + + function getFractionalYear(start, end, elapsedYears){ + var base = elapsedYears? + new Date(end.getFullYear(), start.getMonth(), start.getDate()) : + start; + var elapsedDays = diff(base, end, 'day'); + return elapsedDays / totalDaysInYear(end); + } + + + module.exports = diff; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/i18n/de-DE.js b/node_modules/express-error-handler/node_modules/mout/date/i18n/de-DE.js new file mode 100644 index 000000000..b3ab6207e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/i18n/de-DE.js @@ -0,0 +1,61 @@ + + // de-DE (German) + module.exports = { + "am" : "", + "pm" : "", + + "x": "%d/%m/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %H:%M:%S %Z", + + "months" : [ + "Januar", + "Februar", + "März", + "April", + "Mai", + "Juni", + "Juli", + "August", + "September", + "Oktober", + "November", + "Dezember" + ], + + "months_abbr" : [ + "Jan", + "Febr", + "März", + "Apr", + "Mai", + "Juni", + "Juli", + "Aug", + "Sept", + "Okt", + "Nov", + "Dez" + ], + + "days" : [ + "Sonntag", + "Montag", + "Dienstag", + "Mittwoch", + "Donnerstag", + "Freitag", + "Samstag" + ], + + "days_abbr" : [ + "So", + "Mo", + "Di", + "Mi", + "Do", + "Fr", + "Sa" + ] + }; + diff --git a/node_modules/express-error-handler/node_modules/mout/date/i18n/en-US.js b/node_modules/express-error-handler/node_modules/mout/date/i18n/en-US.js new file mode 100644 index 000000000..f9526ce46 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/i18n/en-US.js @@ -0,0 +1,61 @@ + + // en-US (English, United States) + module.exports = { + "am" : "AM", + "pm" : "PM", + + "x": "%m/%d/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %I:%M:%S %p %Z", + + "months" : [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + + "months_abbr" : [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + + "days" : [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + + "days_abbr" : [ + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat" + ] + }; + diff --git a/node_modules/express-error-handler/node_modules/mout/date/i18n/pt-BR.js b/node_modules/express-error-handler/node_modules/mout/date/i18n/pt-BR.js new file mode 100644 index 000000000..71ebadb5d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/i18n/pt-BR.js @@ -0,0 +1,61 @@ + + // pt-BR (Brazillian Portuguese) + module.exports = { + "am" : "", + "pm" : "", + + "x": "%d/%m/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %H:%M:%S %Z", + + "months" : [ + "Janeiro", + "Fevereiro", + "Março", + "Abril", + "Maio", + "Junho", + "Julho", + "Agosto", + "Setembro", + "Outubro", + "Novembro", + "Dezembro" + ], + + "months_abbr" : [ + "Jan", + "Fev", + "Mar", + "Abr", + "Mai", + "Jun", + "Jul", + "Ago", + "Set", + "Out", + "Nov", + "Dez" + ], + + "days" : [ + "Domingo", + "Segunda", + "Terça", + "Quarta", + "Quinta", + "Sexta", + "Sábado" + ], + + "days_abbr" : [ + "Dom", + "Seg", + "Ter", + "Qua", + "Qui", + "Sex", + "Sáb" + ] + }; + diff --git a/node_modules/express-error-handler/node_modules/mout/date/i18n_.js b/node_modules/express-error-handler/node_modules/mout/date/i18n_.js new file mode 100644 index 000000000..723fc103e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/i18n_.js @@ -0,0 +1,14 @@ +var mixIn = require('../object/mixIn'); +var enUS = require('./i18n/en-US'); + + // we also use mixIn to make sure we don't affect the original locale + var activeLocale = mixIn({}, enUS, { + // we expose a "set" method to allow overriding the global locale + set : function(localeData){ + mixIn(activeLocale, localeData); + } + }); + + module.exports = activeLocale; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/isLeapYear.js b/node_modules/express-error-handler/node_modules/mout/date/isLeapYear.js new file mode 100644 index 000000000..4212870be --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/isLeapYear.js @@ -0,0 +1,15 @@ +var isDate = require('../lang/isDate'); + + /** + * checks if it's a leap year + */ + function isLeapYear(fullYear){ + if (isDate(fullYear)) { + fullYear = fullYear.getFullYear(); + } + return fullYear % 400 === 0 || (fullYear % 100 !== 0 && fullYear % 4 === 0); + } + + module.exports = isLeapYear; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/isSame.js b/node_modules/express-error-handler/node_modules/mout/date/isSame.js new file mode 100644 index 000000000..4097d29b3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/isSame.js @@ -0,0 +1,16 @@ +var startOf = require('./startOf'); + + /** + * Check if date is "same" with optional period + */ + function isSame(date1, date2, period){ + if (period) { + date1 = startOf(date1, period); + date2 = startOf(date2, period); + } + return Number(date1) === Number(date2); + } + + module.exports = isSame; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/parseIso.js b/node_modules/express-error-handler/node_modules/mout/date/parseIso.js new file mode 100644 index 000000000..40a70a882 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/parseIso.js @@ -0,0 +1,146 @@ +var some = require('../array/some'); + + var datePatterns = [ + /^([0-9]{4})$/, // YYYY + /^([0-9]{4})-([0-9]{2})$/, // YYYY-MM (YYYYMM not allowed) + /^([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/ // YYYY-MM-DD or YYYYMMDD + ]; + var ORD_DATE = /^([0-9]{4})-?([0-9]{3})$/; // YYYY-DDD + + var timePatterns = [ + /^([0-9]{2}(?:\.[0-9]*)?)$/, // HH.hh + /^([0-9]{2}):?([0-9]{2}(?:\.[0-9]*)?)$/, // HH:MM.mm + /^([0-9]{2}):?([0-9]{2}):?([0-9]{2}(\.[0-9]*)?)$/ // HH:MM:SS.ss + ]; + + var DATE_TIME = /^(.+)T(.+)$/; + var TIME_ZONE = /^(.+)([+\-])([0-9]{2}):?([0-9]{2})$/; + + function matchAll(str, patterns) { + var match; + var found = some(patterns, function(pattern) { + return !!(match = pattern.exec(str)); + }); + + return found ? match : null; + } + + function getDate(year, month, day) { + var date = new Date(Date.UTC(year, month, day)); + + // Explicitly set year to avoid Date.UTC making dates < 100 relative to + // 1900 + date.setUTCFullYear(year); + + var valid = + date.getUTCFullYear() === year && + date.getUTCMonth() === month && + date.getUTCDate() === day; + return valid ? +date : NaN; + } + + function parseOrdinalDate(str) { + var match = ORD_DATE.exec(str); + if (match ) { + var year = +match[1], + day = +match[2], + date = new Date(Date.UTC(year, 0, day)); + + if (date.getUTCFullYear() === year) { + return +date; + } + } + + return NaN; + } + + function parseDate(str) { + var match, year, month, day; + + match = matchAll(str, datePatterns); + if (match === null) { + // Ordinal dates are verified differently. + return parseOrdinalDate(str); + } + + year = (match[1] === void 0) ? 0 : +match[1]; + month = (match[2] === void 0) ? 0 : +match[2] - 1; + day = (match[3] === void 0) ? 1 : +match[3]; + + return getDate(year, month, day); + } + + function getTime(hr, min, sec) { + var valid = + (hr < 24 && hr >= 0 && + min < 60 && min >= 0 && + sec < 60 && min >= 0) || + (hr === 24 && min === 0 && sec === 0); + if (!valid) { + return NaN; + } + + return ((hr * 60 + min) * 60 + sec) * 1000; + } + + function parseOffset(str) { + var match; + if (str.charAt(str.length - 1) === 'Z') { + str = str.substring(0, str.length - 1); + } else { + match = TIME_ZONE.exec(str); + if (match) { + var hours = +match[3], + minutes = (match[4] === void 0) ? 0 : +match[4], + offset = getTime(hours, minutes, 0); + + if (match[2] === '-') { + offset *= -1; + } + + return { offset: offset, time: match[1] }; + } + } + + // No time zone specified, assume UTC + return { offset: 0, time: str }; + } + + function parseTime(str) { + var match; + var offset = parseOffset(str); + + str = offset.time; + offset = offset.offset; + if (isNaN(offset)) { + return NaN; + } + + match = matchAll(str, timePatterns); + if (match === null) { + return NaN; + } + + var hours = (match[1] === void 0) ? 0 : +match[1], + minutes = (match[2] === void 0) ? 0 : +match[2], + seconds = (match[3] === void 0) ? 0 : +match[3]; + + return getTime(hours, minutes, seconds) - offset; + } + + /** + * Parse an ISO8601 formatted date string, and return a Date object. + */ + function parseISO8601(str){ + var match = DATE_TIME.exec(str); + if (!match) { + // No time specified + return parseDate(str); + } + + return parseDate(match[1]) + parseTime(match[2]); + } + + module.exports = parseISO8601; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/startOf.js b/node_modules/express-error-handler/node_modules/mout/date/startOf.js new file mode 100644 index 000000000..072bc0efc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/startOf.js @@ -0,0 +1,54 @@ +var clone = require('../lang/clone'); + + /** + * get a new Date object representing start of period + */ + function startOf(date, period){ + date = clone(date); + + // intentionally removed "break" from switch since start of + // month/year/etc should also reset the following periods + switch (period) { + case 'year': + date.setMonth(0); + /* falls through */ + case 'month': + date.setDate(1); + /* falls through */ + case 'week': + case 'day': + date.setHours(0); + /* falls through */ + case 'hour': + date.setMinutes(0); + /* falls through */ + case 'minute': + date.setSeconds(0); + /* falls through */ + case 'second': + date.setMilliseconds(0); + break; + default: + throw new Error('"'+ period +'" is not a valid period'); + } + + // week is the only case that should reset the weekDay and maybe even + // overflow to previous month + if (period === 'week') { + var weekDay = date.getDay(); + var baseDate = date.getDate(); + if (weekDay) { + if (weekDay >= baseDate) { + //start of the week is on previous month + date.setDate(0); + } + date.setDate(date.getDate() - date.getDay()); + } + } + + return date; + } + + module.exports = startOf; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/strftime.js b/node_modules/express-error-handler/node_modules/mout/date/strftime.js new file mode 100644 index 000000000..f033d10ff --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/strftime.js @@ -0,0 +1,118 @@ +var pad = require('../number/pad'); +var i18n = require('./i18n_'); +var dayOfTheYear = require('./dayOfTheYear'); +var timezoneOffset = require('./timezoneOffset'); +var timezoneAbbr = require('./timezoneAbbr'); +var weekOfTheYear = require('./weekOfTheYear'); + + var _combinations = { + 'D': '%m/%d/%y', + 'F': '%Y-%m-%d', + 'r': '%I:%M:%S %p', + 'R': '%H:%M', + 'T': '%H:%M:%S', + 'x': 'locale', + 'X': 'locale', + 'c': 'locale' + }; + + + /** + * format date based on strftime format + */ + function strftime(date, format, localeData){ + localeData = localeData || i18n; + var reToken = /%([a-z%])/gi; + + function makeIterator(fn) { + return function(match, token){ + return fn(date, token, localeData); + }; + } + + return format + .replace(reToken, makeIterator(expandCombinations)) + .replace(reToken, makeIterator(convertToken)); + } + + + function expandCombinations(date, token, l10n){ + if (token in _combinations) { + var expanded = _combinations[token]; + return expanded === 'locale'? l10n[token] : expanded; + } else { + return '%'+ token; + } + } + + + function convertToken(date, token, l10n){ + switch (token){ + case 'a': + return l10n.days_abbr[date.getDay()]; + case 'A': + return l10n.days[date.getDay()]; + case 'h': + case 'b': + return l10n.months_abbr[date.getMonth()]; + case 'B': + return l10n.months[date.getMonth()]; + case 'C': + return pad(Math.floor(date.getFullYear() / 100), 2); + case 'd': + return pad(date.getDate(), 2); + case 'e': + return pad(date.getDate(), 2, ' '); + case 'H': + return pad(date.getHours(), 2); + case 'I': + return pad(date.getHours() % 12, 2); + case 'j': + return pad(dayOfTheYear(date), 3); + case 'L': + return pad(date.getMilliseconds(), 3); + case 'm': + return pad(date.getMonth() + 1, 2); + case 'M': + return pad(date.getMinutes(), 2); + case 'n': + return '\n'; + case 'p': + return date.getHours() >= 12? l10n.pm : l10n.am; + case 'P': + return convertToken(date, 'p', l10n).toLowerCase(); + case 's': + return date.getTime() / 1000; + case 'S': + return pad(date.getSeconds(), 2); + case 't': + return '\t'; + case 'u': + var day = date.getDay(); + return day === 0? 7 : day; + case 'U': + return pad(weekOfTheYear(date), 2); + case 'w': + return date.getDay(); + case 'W': + return pad(weekOfTheYear(date, 1), 2); + case 'y': + return pad(date.getFullYear() % 100, 2); + case 'Y': + return pad(date.getFullYear(), 4); + case 'z': + return timezoneOffset(date); + case 'Z': + return timezoneAbbr(date); + case '%': + return '%'; + default: + // keep unrecognized tokens + return '%'+ token; + } + } + + + module.exports = strftime; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/timezoneAbbr.js b/node_modules/express-error-handler/node_modules/mout/date/timezoneAbbr.js new file mode 100644 index 000000000..b10068750 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/timezoneAbbr.js @@ -0,0 +1,17 @@ +var timezoneOffset = require('./timezoneOffset'); + + /** + * Abbreviated time zone name or similar information. + */ + function timezoneAbbr(date){ + // Date.toString gives different results depending on the + // browser/system so we fallback to timezone offset + // chrome: 'Mon Apr 08 2013 09:02:04 GMT-0300 (BRT)' + // IE: 'Mon Apr 8 09:02:04 UTC-0300 2013' + var tz = /\(([A-Z]{3,4})\)/.exec(date.toString()); + return tz? tz[1] : timezoneOffset(date); + } + + module.exports = timezoneAbbr; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/timezoneOffset.js b/node_modules/express-error-handler/node_modules/mout/date/timezoneOffset.js new file mode 100644 index 000000000..9492dcebf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/timezoneOffset.js @@ -0,0 +1,16 @@ +var pad = require('../number/pad'); + + /** + * time zone as hour and minute offset from UTC (e.g. +0900) + */ + function timezoneOffset(date){ + var offset = date.getTimezoneOffset(); + var abs = Math.abs(offset); + var h = pad(Math.floor(abs / 60), 2); + var m = pad(abs % 60, 2); + return (offset > 0? '-' : '+') + h + m; + } + + module.exports = timezoneOffset; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/totalDaysInMonth.js b/node_modules/express-error-handler/node_modules/mout/date/totalDaysInMonth.js new file mode 100644 index 000000000..8aafeb846 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/totalDaysInMonth.js @@ -0,0 +1,25 @@ +var isDate = require('../lang/isDate'); +var isLeapYear = require('./isLeapYear'); + + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + /** + * returns the total amount of days in the month (considering leap years) + */ + function totalDaysInMonth(fullYear, monthIndex){ + if (isDate(fullYear)) { + var date = fullYear; + year = date.getFullYear(); + monthIndex = date.getMonth(); + } + + if (monthIndex === 1 && isLeapYear(fullYear)) { + return 29; + } else { + return DAYS_IN_MONTH[monthIndex]; + } + } + + module.exports = totalDaysInMonth; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/totalDaysInYear.js b/node_modules/express-error-handler/node_modules/mout/date/totalDaysInYear.js new file mode 100644 index 000000000..b4b7e9b73 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/totalDaysInYear.js @@ -0,0 +1,13 @@ +var isLeapYear = require('./isLeapYear'); + + /** + * return the amount of days in the year following the gregorian calendar + * and leap years + */ + function totalDaysInYear(fullYear){ + return isLeapYear(fullYear)? 366 : 365; + } + + module.exports = totalDaysInYear; + + diff --git a/node_modules/express-error-handler/node_modules/mout/date/weekOfTheYear.js b/node_modules/express-error-handler/node_modules/mout/date/weekOfTheYear.js new file mode 100644 index 000000000..dd51b7f1f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/date/weekOfTheYear.js @@ -0,0 +1,16 @@ +var dayOfTheYear = require('./dayOfTheYear'); + + /** + * Return the week of the year based on given firstDayOfWeek + */ + function weekOfTheYear(date, firstDayOfWeek){ + firstDayOfWeek = firstDayOfWeek == null? 0 : firstDayOfWeek; + var doy = dayOfTheYear(date); + var dow = (7 + date.getDay() - firstDayOfWeek) % 7; + var relativeWeekDay = 6 - firstDayOfWeek - dow; + return Math.floor((doy + relativeWeekDay) / 7); + } + + module.exports = weekOfTheYear; + + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/array.md b/node_modules/express-error-handler/node_modules/mout/doc/array.md new file mode 100644 index 000000000..a81a50b59 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/array.md @@ -0,0 +1,781 @@ +# array # + +Array utilities. + + + + +## append(arr1, arr2):Array + +Appends an array to the end of the other. +The first array will be modified and will contain the appended items. + +See: [`union()`](#union), [`combine()`](#combine) + +```js +var foo = ['a', 'b'], + bar = ['b', 'd']; + +append(foo, bar); // ['a', 'b', 'b', 'd'] +``` + + + +## collect(arr, callback, [thisObj]):Array + +Maps the items in `arr` and concatenates the resulting arrays. + +See: [`map()`](#map) + +```js +collect([1, 2, 3], function(val) { + return [val, val % 2]; +}); // [1, 1, 2, 0, 3, 1]; + +collect(['a', 'bb', ''], function(val) { + return val.split(''); +}); // ['a', 'b', 'b'] +``` + +It also supports a shorthand syntax: + +```js +var items = [{ a: [1] }, { b: 'foo' }, { a: [2, 3] }]; +collect(items, 'a'); // [1, 2, 3]; +``` + + + +## combine(arr1, arr2):Array + +Combines an array with all the items of another. +The first array will be modified and will contain the combined items. +Does not allow duplicates and is case and type sensitive. + +See: [`union()`](#union), [`append()`](#append) + +```js +var foo = ['a', 'b'], + bar = ['b', 'd']; + +combine(foo, bar); // ['a', 'b', 'd'] +``` + + + +## compact(arr):Array + +Returns a new Array without any `null` or `undefined` values. Note that it will +keep empty strings and other falsy values (simillar to Ruby Array#compact). + +```js +var arr = [0, 1, null, false, '', 'foo', undefined, 'bar']; +compact(arr); // [0, 1, false, '', 'foo', 'bar']; +``` + + + +## contains(arr, value):Boolean + +Checks if Array contains value. Alias to `indexOf(arr, val) !== -1`. + +```js +var arr = [1, 2, 3]; +contains(arr, 2); // true +contains(arr, 'foo'); // false +``` + + + +## difference(...arrs):Array + +Return a new Array with elements that aren't present in the other Arrays +besides the first one. + +Works like [Python set#difference](http://docs.python.org/library/stdtypes.html#set.difference). + +It will remove duplicates. + +See: [`xor()`](#xor), [`intersection()`](#intersection) + +```js +var a = ['a', 'b', 1]; +var b = ['c', 1]; +difference(a, b); // ['a', 'b'] +``` + + + +## every(arr, callback, [thisObj]):Array + +Crossbrowser `Array.every()`. + +Tests whether all elements in the array pass the test implemented by the provided function. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +```js +var items = [1, 'foo', 'bar']; +every(items, isString); // false +every(items, isFunction); // false +every(items, function(val, key, arr){ + return val != null; +}); // true +``` + +more info at [MDN Array#every](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every) + +It also supports a shorthand syntax: + +```js +var items = [{id:1, active:true}, {id:3, active:true}, {id:8, active:true}]; +// all items with `id === 8` +every(items, {id:8}); // false +// `active` is truthy on all items +every(items, 'active'); // true +``` + + + +## filter(arr, callback, [thisObj]):Array + +Crossbrowser `Array.filter()`. + +Creates a new array with all elements that pass the callback test. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +```js +var nums = [1, 2, 3, 4, 5, 6]; +var oddNumbers = filter(nums, function(val, key, arr){ + return (val % 2) !== 0; +}); +// > [1, 3, 5] +``` + +more info at [MDN Array#filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter) + +Filter also supports shorthand notation: + +```js +var users = [ + {name:'john', surname:'connor', beard:false}, + {name:'john', surname:'doe', beard:true}, + {name:'jane', surname:'doe', beard:false} +]; +// filter item that matches all properties/values pairs +filter(arr, {name:'john', beard:false}); +// > [{name:'john', surnname:'connor', beard:false}] +// items where 'beard' is a truthy value +filter(arr, 'beard'); +// > [{name:'john', surnname:'doe', beard:true}] +``` + +See [`reject()`](#reject) + + + +## find(arr, callback, [thisObj]):void + +Loops through all the items in the Array and returns the first one that passes +a truth test (callback). + +```js +var arr = [123, {a:'b'}, 'foo', 'bar']; +find(arr, isString); // "foo" +find(arr, isNumber); // 123 +find(arr, isObject); // {a:'b'} +``` + +Find also supports shorthand notation: + +```js +var users = [ + {name:'john', surname:'connor', beard:false}, + {name:'john', surname:'doe', beard:true} +]; +// first item that matches all properties/values pairs +find(arr, {name:'john'}); // {name:'john', surnname:'connor', beard:false} +// first item where 'beard' is a truthy value +find(arr, 'beard'); // {name:'john', surnname:'doe', beard:true} +``` + +See: [findIndex()](#findIndex) + + + +## findIndex(arr, iterator, [thisObj]):Number + +Loops through the items in the Array and returns the index of the first one +that passes a truth test (callback). + +Returns `-1` if no item was found that passes the truth test. + +```js +var arr = [1, { a: 1 }, 'foo', 'bar']; +findIndex(arr, isString); // 2 +findIndex(arr, isNumber); // 0 +findIndex(arr, isObject); // 1 +findIndex(arr, isRegExp); // -1 +``` + +`findIndex` also supports shorthand notation: + +```js +var pets = [ + { pet: 'dog', name: 'Sam' }, + { pet: 'dog', name: 'Maggie' } +]; + +findIndex(pets, { pet: 'dog' }); // 0 +findIndex(pets, { name: 'Maggie' }); // 1 +``` + +See: [find()](#find) + + + +## flatten(arr, [level]):Array + +Recursively flattens an array. A new array containing all the elements is +returned. If `level` is specified, it will only flatten up to that level. + +### Example + +```js +flatten([1, [2], [3, [4, 5]]]); +// > [1, 2, 3, 4, 5] +flatten([1, [2], [3, [4, 5]]], 1); +// > [1, 2, 3, [4, 5]] +``` + + + +## forEach(arr, callback, [thisObj]):void + +Crossbrowser `Array.forEach()`. + +It allows exiting the iteration early by returning `false` on the callback. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +```js +var items = ['foo', 'bar', 'lorem', 'ipsum']; +forEach(items, function(val, key, arr){ + console.log(key +' : '+ val); + if (val === 'lorem') { + // stop iteration (break) + return false; + } +}); +``` + +more info at [MDN Array#forEach](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach) + + + +## indexOf(arr, item, [fromIndex]):Number + +Crossbrowser `Array.indexOf()`. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +more info at [MDN Array#indexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf) + + + + +## insert(arr, ...items):Number + +Push items into array only if they aren't contained by it. Returns the new +`length` of the array. + +See: [`remove()`](#remove), [`removeAll()`](#removeAll), +[`contains()`](#contains) + +```js +var arr = ['a', 'b']; +insert(arr, 'a'); // 2 : ['a', 'b'] +insert(arr, 'c'); // 3 : ['a', 'b', 'c'] +insert(arr, 1, 2, 'b'); // 5 : ['a', 'b', 'c', 1, 2] +``` + + + +## intersection(...arrs):Array + +Return a new Array with elements common to all Arrays. + +Similar to Python set#intersection and underscore.js intersection. + +It will remove duplicates. + +See: [`difference()`](#difference), [`xor()`](#xor) + +```js +var a = ['a', 'b', 1], + b = ['c', 1], + c = [1, 2, 3]; +intersection(a, b, c); // [1] +``` + + + +## invoke(arr, methodName[, ...args]):Array + +Call `methodName` on each item of the array passing custom arguments if needed. + +```js +invoke([[3,2,1], [9,5,2]], 'sort'); // [[1,2,3], [2,5,9]] +``` + + + +## join(arr, [separator]):String + +Joins the strings in `arr`, inserting `separator` between each value. + +This ignores null values and empty strings that are in the array. `separator` +defaults to an empty string. This will convert all non-string objects in the +array to a string. + +### Example + +```js +join(['a', 'b', 'c']); // 'abc' +join(['foo', 'bar'], ', '); // 'foo, bar' +join([null, 'foo', '', 'bar', undefined], ':'); // 'foo:bar' +``` + + + +## lastIndexOf(arr, item, [fromIndex]):Number + +Crossbrowser `Array.lastIndexOf()`. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +more info at [MDN Array#lastIndexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf) + + + +## map(arr, callback, [thisObj]]):Array + +Crossbrowser `Array.map()`. + +Creates a new array with the results of calling a provided function on every +element in this array. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +See: [`collect()`](#collect) + +```js +var nums = [1,2,3,4]; +var double = map(nums, function(val, key, arr){ + return val * 2; +}); +// > [2, 4, 6, 8] +``` + +more info at [MDN Array#map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map) + +It also supports a shorthand notation which can be used to achieve same result +as [`array/pluck`](#pluck): + +```js +var src = ['lorem', 'ipsum', 'foo', 'amet']; +// grab the "length" property of all items +var lengths = map(src, 'length'); // [5, 5, 3, 4] +``` + + + +## max(arr, [iterator], [thisObj]):* + +Returns maximum value inside array or use a custom iterator to define how items +should be compared. + +See: [`min()`](#min) + +```js +max([10, 2, 7]); // 10 +max(['foo', 'lorem', 'amet'], function(val){ + return val.length; +}); // 'lorem' +``` + +It also supports a shorthand notation: + +```js +max(['foo', 'lorem', 'amet'], 'length'); // "lorem" +``` + + + +## min(arr, [iterator], [thisObj]):* + +Returns minimum value inside array or use a custom iterator to define how items +should be compared. + +See: [`max()`](#max) + +```js +min([10, 2, 7]); // 2 +min(['foo', 'lorem', 'amet'], function(val){ + return val.length; +}); // 'foo' +``` + +It also supports a shorthand notation: + +```js +min(['foo', 'lorem', 'amet'], 'length'); // "foo" +``` + + + +## pick(arr, [nItems]):* + +Gets random item(s) and removes it from the original array. + +If `nItems` is specified it will return a new Array contained the *picked* +items otherwise it returns a single item. + +See: [`random/choice()`](./random.html#choice) + +### Example: + +```js +var arr = [1, 2, 3, 4, 5, 6]; +var item1 = pick(arr); // 4 +var item2 = pick(arr); // 1 +var items = pick(arr, 2); // [5, 2] +console.log(arr); // [3, 6] +``` + + + +## pluck(arr, propName):Array + +Extract a list of property values. + +See: [`function/prop()`](function.html#prop) + +```js +var users = [{name : 'John', age: 21}, {name: 'Jane', age : 27}]; +var names = pluck(users, 'name'); // ["John", "Jane"] +var ages = pluck(users, 'age'); // [21, 27] +``` + + + +## range([start], stop[, step]):Array + +Creates a new Array with all the values inside the range. Works similarly to +Python#range or PHP#range. + +### Arguments + + 1. `[start]` (Number) : Range start. Default is `0`. + 2. `stop` (Number) : Range limit. + 3. `[step]` (Number) : Step size. Default is `1`. + +### Example + +```js +range(5); // [0, 1, 2, 3, 4, 5] +range(0, 5); // [0, 1, 2, 3, 4, 5] +range(0, 5, 2); // [0, 2, 4] +range(20, 40, 5); // [20, 25, 30, 35, 40] +``` + + + +## reduce(arr, fn):* + +Crossbrowser `Array.reduce()`. + +Apply a function against an accumulator and each value of the array (from +left-to-right) as to reduce it to a single value. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +more info at [MDN Array#reduce](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce) + + + +## reduceRight(arr, fn):* + +Crossbrowser `Array.reduceRight()`. + +Apply a function simultaneously against two values of the array (from +right-to-left) as to reduce it to a single value. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +more info at [MDN Array#reduceRight](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduceRight) + + + +## reject(arr, fn, thisObj):Array + +Creates a new array with all the elements that do **not** pass the truth test. +Opposite of [`filter()`](#filter). + +See [`filter()`](#filter) + +### Example + +```js +var numbers = [1, 2, 3, 4, 5, 6]; +reject(numbers, function(x) { return (x % 2) !== 0; }); // [2, 4, 6] +``` + +It also supports a shorthand syntax: + +```js +var users = [ + {name:'john', surname:'connor', beard:false}, + {name:'john', surname:'doe', beard:true}, + {name:'jane', surname:'doe', beard:false} +]; +// reject items that matches all properties/values pairs +reject(arr, {name:'john'}); +// > [{name:'jane', surnname:'doe', beard:false}] +// reject items where 'beard' is a truthy value +filter(arr, 'beard'); +// > [{name:'john', surnname:'connor', beard:false}, +// {name:'jane', surname:'doe', beard:false}] +``` + + + +## remove(arr, item):void + +Remove a single item from the array. + +IMPORTANT: it won't remove duplicates, just a single item. + +### Example + +```js +var foo = [1, 2, 3, 4]; +remove(foo, 2); +console.log(foo); // [1, 3, 4] +``` + + + +## removeAll(arr, item):void + +Remove all instances of an item from the array. + +### Example + +```js +var foo = [1, 2, 3, 4, 2, 2]; +removeAll(foo, 2); +console.log(foo); // [1, 3, 4]; +``` + + + +## shuffle(arr):Array + +Returns a new Array with items randomly sorted (shuffled). Similar to Ruby Array#shuffle. + +### Example + +```js +var arr = ['a', 'b', 'c', 'd', 'e']; +shuffle(arr); // ['b', 'd', 'e', 'c', 'a'] +``` + + + +## some(arr, callback, [thisObj]):Array + +Crossbrowser `Array.some()`. + +Tests whether some element in the array passes the test implemented by the provided function. + +It differs from ES5 since it will also loop over sparse items in the array to +normalize the behavior across browsers (avoid inconsistencies). + +```js +var items = [1, 'foo', 'bar']; +some(items, isString); // true +some(items, isFunction); // false +``` + +more info at [MDN Array#some](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some) + +It also supports a shorthand syntax: + +```js +var items = [{id:1, active:true}, {id:3, active:false}, {id:8, active:false}]; +// at least one item with `id === 8` +some(items, {id:8}); // true +// `active` is truthy on at least one item +some(items, 'active'); // true +``` + +see also: [`object/matches`](object.html#matches) + + + +## sort(arr, [compareFn]):Array + +Returns a sorted Array using the [Merge Sort](http://en.wikipedia.org/wiki/Merge_sort) algorithm (stable sort). + +The `Array.prototype.sort` browser implementations differ since the sorting algorithm isn't described in the ES spec - [in V8 it isn't stable](http://code.google.com/p/v8/issues/detail?id=90) and [on Firefox it is stable](https://bugzilla.mozilla.org/show_bug.cgi?id=224128) - so this function doesn't use the browser native implementation and is recommended in cases where a stable sort is required (items should preserve same order if already sorted). + +**Important:** It does logical comparisson by default (greater/less than) and +not a string comparisson like the native `Array#sort`. + +### compareFn + +If `compareFn` is supplied elements are sorted based on the value returned by +the `compareFn`. + + - If `compareFn(a, b)` is less than `0`, sort `a` to a lower index than `b`. + - If `compareFn(a, b)` returns `0`, leave `a` and `b` unchanged with respect + to each other, but sorted with respect to all different elements. + - If `compareFn(a, b)` is greater than `0`, sort `b` to a lower index than + `a`. + +### Example + +```js +sort([187, 23, 47, 987, 12, 59, 0]); // [0, 12, 23, 47, 59, 187, 987] +sort(['a', 'z', 'c', 'beta', 'b']); // ['a', 'b', 'beta', 'c', 'z'] + +// ['sit', 'amet', 'lorem', 'ipsum'] +sort(['lorem', 'ipsum', 'sit', 'amet'], function(a, b){ + // sort by length, items with same length + // will keep the relative order (stable) + return a.length - b.length; +}); + +// [4, 3, 2, 1] +sort([2, 3, 1, 4], function(a, b){ + // reverse sort + return b - a; +}); +``` + + + +## split(arr, [segments]):Array + +Splits an array into a fixed number of segments. + +The number of segments is specified by `segments` and defaults to 2. If the +array cannot be evenly split, the first segments will contain the extra items. +If `arr` is empty, an empty array is returned. If `arr.length` is less than +`segments`, then the resulting array will have `arr.length` number of +single-element arrays. + +### Example +```js +split([1, 2, 3, 4, 5], 3) // [ [1, 2], [3, 4], [5] ] +split([1, 2, 3, 4, 5]) // [ [1, 2, 3], [4, 5] ] +split([]) // [] +split([1, 2], 3) // [ [1], [2] ] +``` + + + +## toLookup(arr, key):Object + +Create an object that indexes the items in the array by a key. If `key` is a function, the key for each value in the resulting object will be the result of calling the function with the value as an argument. Otherwise `key` specifies the property on each value to use as the key. + +### Example + +```js +var foo = [{ name: 'a', thing: 1 }, { name: 'b', thing: 2 }]; +// { a: { name: 'a', thing: 1 }, b: { name: 'b', thing: 2 } } +toLookup(foo, 'name'); +// same as above +toLookup(foo, function (value) { return value.name; }); +``` + + + +## union(...arrs):Array + +Concat multiple arrays removing duplicates. + +```js +var a = ['a', 'b'], + b = ['c', 'a'], + c = [1, 'b', 2, 3, 'a']; + +//note that unique remove from begin to end +union(a, b, c); // ['c', 1, 'b', 2, 3, 'a'] +``` + + + +## unique(arr):Array + +Return a new Array of unique items. + +### Example + +```js +var foo = [1, 2, 3, 4, 2, 2, 3, 4]; +var bar = unique(foo); +console.log(foo); // [1, 2, 3, 4]; +``` + + + +## xor(arr1, arr2):Array + +Exclusive OR. Returns items that are present in a single array. + +Works like [Python set#symmetric_difference](http://docs.python.org/library/stdtypes.html#set.symmetric_difference) renamed for brevity. + +It will remove duplicates. + +See: [`difference()`](#difference), [`intersection()`](#intersection) + +```js +var a = ['a', 'b', 1]; +var b = ['c', 1]; +xor(a, b); // ['a', 'b', 'c'] +``` + + + +## zip(...arrs):Array + +Groups the elements of each array at their corresponding indexes. + +Useful for separate data sources that are coordinated through matching array +indexes. For a matrix of nested arrays, `zip.apply(...)` can transpose the +matrix in a similar fashion. + +```js +// [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]] +zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); +``` + + + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/collection.md b/node_modules/express-error-handler/node_modules/mout/doc/collection.md new file mode 100644 index 000000000..2ffcab106 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/collection.md @@ -0,0 +1,233 @@ +# collection # + +Methods for dealing with collections (Array or Objects). + + + +## contains(list, value):Boolean + +Checks if collection contains value. + +```js +contains({a: 1, b: 2, c: 'bar'}, 2); // true +contains([1, 2, 3], 'foo'); // false +``` + +See: [array/contains](array.html#contains), [object/contains](object.html#contains) + + + +## every(list, callback, [thisObj]):Boolean + +Tests whether all values in the collection pass the test implemented by the +provided callback. + +```js +var obj = { + a: 1, + b: 2, + c: 3, + d: 'string' +}; + +every(obj, isNumber); // false +``` + +See: [array/every](array.html#every), [object/every](object.html#every) + + + +## filter(list, callback, [thisObj]):Array + +Filter collection properties. + +See: [array/filter](array.html#filter), [object/filter](object.html#filter) + + + +## find(list, callback, [thisObj]):* + +Loops through all the values in the collection and returns the first one that +passes a truth test (callback). + +**Important:** loop order over objects properties isn't guaranteed to be the +same on all environments. + +```js +find({a: 'foo', b: 12}, isString); // 'foo' +find(['foo', 12], isNumber); // 12 +``` + +See: [array/find](array.html#find), [object/find](object.html#find) + + + +## forEach(list, callback, [thisObj]) + +Loop through all values of the collection. + +See: [array/forEach](array.html#forEach), [object/forOwn](object.html#forOwn) + + + +## map(list, callback, [thisObj]):Array + +Returns a new collection where the properties values are the result of calling +the callback for each property in the original collection. + +See: [array/map](array.html#map), [object/map](object.html#map) + + + +## max(list, [iterator]):* + +Returns maximum value inside collection or use a custom iterator to define how +items should be compared. + +See: [`min()`](#min), [array/max](array.html#max), [object/max](object.html#max) + +```js +max({a: 100, b: 2, c: 1, d: 3, e: 200}); // 200 +max(['foo', 'lorem', 'amet'], function(val){ + return val.length; +}); // 'lorem' +``` + + + +## min(list, [iterator]):* + +Returns minimum value inside collection or use a custom iterator to define how +items should be compared. + +See: [`max()`](#max), [array/min](array.html#min), [object/min](object.html#min) + +```js +min([10, 2, 7]); // 2 +min({a: 'foo', b: 'lorem', c: 'amet'}, function(val){ + return val.length; +}); // 'foo' +``` + + + +## pluck(list, propName):Array + +Extract a list of property values. + +```js +var users = [ + { + name : 'John', + age : 21 + }, + { + name : 'Jane', + age : 27 + } +]; + +pluck(users, 'name'); // ["John", "Jane"] +pluck(users, 'age'); // [21, 27] + +users = { + first: { + name : 'John', + age : 21 + }, + second: { + name : 'Mary', + age : 25 + } +}; + +pluck(users, 'name'); // ['John', 'Mary'] +``` + +See: [array/pluck](array.html#pluck), [object/pluck](object.html#pluck) + + + +## reduce(list, callback, initial, [thisObj]):* + +Apply a function against an accumulator and each value in the collection as to +reduce it to a single value. + +```js +var obj = {a: 1, b: 2, c: 3, d: 4}; + +function sum(prev, cur, key, list) { + return prev + cur; +} + +reduce(obj, sum); // 10 +``` + +See: [array/reduce](array.html#reduce), [object/reduce](object.html#reduce) + + + +## reject(list, fn, [thisObj]):Array + +Creates a new array with all the elements that do **not** pass the truth test. +Opposite of [`filter()`](#filter). + +### Example + +```js +var numbers = [1, 2, 3, 4, 5]; +reject(numbers, function(x) { return (x % 2) !== 0; }); // [2, 4] + +var obj = {a: 1, b: 2, c: 3, d: 4, e: 5}; +reject(obj, function(x) { return (x % 2) !== 0; }); // [2, 4] +``` + +See: [array/reject](array.html#reject), [object/reject](object.html#reject) + + + +## size(list):Number + +Returns the number of values in the collection. + +```js +var obj = { + foo : 1, + bar : 2, + lorem : 3 +}; +size(obj); // 3 +size([1,2,3]); // 3 +size(null); // 0 +``` + +See: [object/size](object.html#size) + + + +## some(list, callback, [thisObj]):Boolean + +Tests whether any values in the collection pass the test implemented by the +provided callback. + +```js +var obj = { + a: 1, + b: 2, + c: 3, + d: 'string' +}; + +some(obj, isNumber); // true +some(obj, isString); // true +some([1, 2, 3], isNumber) // true +some([1, 2, 3], isString) // false +``` + +See: [array/some](array.html#some), [object/some](object.html#some) + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... diff --git a/node_modules/express-error-handler/node_modules/mout/doc/date.md b/node_modules/express-error-handler/node_modules/mout/doc/date.md new file mode 100644 index 000000000..b3f7f40ed --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/date.md @@ -0,0 +1,295 @@ +# date # + +Date utilities. + + +## dayOfTheYear(date):Number + +How many days elapsed since begining of the year (following gregorian +calendar). + +```js +// Jan 1st +dayOfTheYear(new Date(2013, 0, 1)); // 1 +// Dec 31th +dayOfTheYear(new Date(2013, 11, 31)); // 364 +``` + + + +## diff(date1, date2, [unitName]):Number + +Calculate the difference between dates (range). + +The returned value is always positive. The default `unitName` is `"ms"`. + +Available units: `year`, `month`, `week`, `day`, `hour`, `minute`, `second`, +`millisecond`. + +See: [`time/convert()`](time.html#convert) + +```js +var d1 = new Date(2012, 4, 5); +var d2 = new Date(2013, 4, 8); +diff(d1, d2); // 31795200000 +diff(d1, d2, 'hour'); // 8832 +diff(d1, d2, 'week'); // 52.57142857142857 +diff(d1, d2, 'month'); // 12.096774193548388 +diff(d1, d2, 'year'); // 1.0082191780821919 +``` + + + +## isLeapYear(fullYear|date):Boolean + +Checks if it's a [leap year](http://en.wikipedia.org/wiki/Leap_year) according +to the Gregorian calendar. + +see: [`totalDaysInMonth()`](#totalDaysInMonth) + +```js +isLeapYear(2012); // true +isLeapYear(2013); // false +isLeapYear(new Date(2012, 2, 28)); // true +``` + + +## isSame(date1, date2[, period]):Boolean + +Check if both dates are the "same". + +You can pass an optional *period* used to set the comparisson precision. + +Available periods: `year`, `month`, `week`, `day`, `hour`, `minute`, `second`. + +```js +var date1 = new Date(2013, 1, 3); +var date2 = new Date(2013, 2, 9); +isSame(date1, date2); // false +isSame(date1, date2, 'day'); // false +isSame(date1, date2, 'month'); // false +isSame(date1, date2, 'year'); // true +``` + + + +## parseIso(str):Number + +Parses an [ISO8601](http://en.wikipedia.org/wiki/Iso8601) date and returns the +number of milliseconds since January 1, 1970, 00:00:00 UTC, or `NaN` if it is +not a valid ISO8601 date. + +This parses *all* ISO8601 dates, including dates without times, [ordinal +dates](https://en.wikipedia.org/wiki/ISO_8601#Ordinal_dates), and the compact +representation (omitting delimeters). The only exception is [ISO week +dates](https://en.wikipedia.org/wiki/ISO_week_date), which are not parsed. + +If no time zone offset is specified, it assumes UTC time. + +```js +// Jan 01, 1970 00:00 GMT +parseIso('1970-01-01T00:00:00') // 0 +parseIso('1970-001') // 0 +parseIso('1970-01-01') // 0 +parseIso('19700101T000000.00') // 0 +parseIso('1970-01-01T02:00+02:00') // 0 + +// Jan 02, 2000 20:10 GMT+04:00 +parseIso('2000-01-02T20:10+04:00') // 946829400000 +``` + + + +## startOf(date, period):Date + +Get a new Date at the start of the period. + +Available periods: `year`, `month`, `week`, `day`, `hour`, `minute`, `second`. + +```js +// Apr 05 2013 11:27:43 +var date = new Date(2013, 3, 5, 11, 27, 43, 123); +startOf(date, 'year'); // Jan 01 2013 00:00:00 +startOf(date, 'month'); // Apr 01 2013 00:00:00 +startOf(date, 'day'); // Apr 05 2013 00:00:00 +startOf(date, 'hour'); // Apr 05 2013 11:00:00 +``` + + + +## strftime(date, format, [l10n]):String + +Format date based on strftime format. + +Replaced tokens: + +
+
%a
locale's abbreviated weekday name.
+
%A
locale's full weekday name.
+
%b
locale's abbreviated month name.
+
%B
locale's full month name.
+
%c
locale's appropriate date and time representation.
+
%C
century number (the year divided by 100 and truncated +to an integer) as a decimal number [00..99].
+
%d
day of the month as a decimal number [01..31].
+
%D
same as %m/%d/%y.
+
%e
day of the month as a decimal number [1..31]; +a single digit is preceded by a space.
+
%F
The ISO 8601 date format (%Y-%m-%d)
+
%h
same as %b.
+
%H
hour (24-hour clock) as a decimal number [00..23].
+
%I
hour (12-hour clock) as a decimal number [01..12].
+
%j
day of the year as a decimal number [001..366].
+
%L
zero-padded milliseconds [000..999]
+
%m
month as a decimal number [01..12].
+
%M
minute as a decimal number [00..59].
+
%n
newline character.
+
%p
locale's equivalent of either "am" or "pm"
+
%P
locale's equivalent of either "AM" or "PM"
+
%r
time in a.m. and +p.m. notation; in the POSIX locale this is equivalent to %I:%M:%S %p.
+
%R
time in 24 hour notation (%H:%M).
+
%s
seconds since Epoch (1970-01-01 00:00:00 UTC)
+
%S
second as a decimal number [00..60].
+
%t
tab character.
+
%T
time (%H:%M:%S).
+
%u
weekday as a decimal number [1..7], with 1 representing +Monday.
+
%U
week number of the year (Sunday as the first day of +the week) as a decimal number [00..53].
+
%V
week number of the year (Monday as the first day of the +week) as a decimal number [01..53]. If the week containing 1 January has +four or more days in the new year, then it is considered week 1. Otherwise, +it is the last week of the previous year, and the next week is week 1.
+
%w
weekday as a decimal number [0..6], with 0 representing +Sunday.
+
%W
week number of the year (Monday as the first day of +the week) as a decimal number [00..53]. All days in a new year preceding +the first Monday are considered to be in week 0.
+
%x
locale's appropriate date representation.
+
%X
locale's appropriate time representation.
+
%y
year without century as a decimal number [00..99].
+
%Y
year with century as a decimal number.
+
%Z
timezone name or abbreviation, or by no bytes +if no timezone information exists.
+
%%
is replaced by %.
+
+ +```js +var date = new Date(2013, 3, 8, 9, 2, 4); +strftime(date, '%Y-%m-%d'); // "2013-04-08" +strftime(date, '%R'); // "09:02" +strftime(date, '%Y-%m-%dT%H:%M:%S%z'); // "2013-04-08T09:02:04+0000" +``` + +You can also set a custom locale: + +```js +var ptBr = require('mout/date/i18n/pt-BR'); +strftime(date, '%a, %d %b', ptBr); // 'Seg, 08 Abr' +strftime(date, '%A, %d %B', ptBr); // 'Segunda, 08 Abril' +``` + +To set it globally: + +```js +require('mout/date/i18n_').set( customLocaleData ); +``` + +See [date/i18n](https://github.com/mout/mout/tree/master/src/date/i18n) +for localization examples. + + + +## timezoneAbbr(date):String + +Return timezone abbreviation or similar data. + +The result will vary based on the OS/browser since some environments doesn't +provide enough info about the current locale. + +```js +// IE 7-8 +timezoneAbbr(new Date()); // "-0500" +// Chrome, FF, V8 +timezoneAbbr(new Date()); // "EST" +``` + + + +## timezoneOffset(date):String + +Return time zone as hour and minute offset from UTC (e.g. +0900). + +It's important to note that JavaScript Date object will use the system locale +info to determinate the [timezone +offset](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset) +and that daylight saving time affects the result. + +```js +// if system locale is EST +timezoneOffset(new Date()); // -0500 +``` + + + +## totalDaysInMonth(fullYear, monthIndex):Number + +Returns the amount of days in the month taking into consideration leap years +(following Gregorian calendar). + +see: [`isLeapYear()`](#isLeapYear) + +```js +totalDaysInMonth(2008, 1); // 29 (leap year) +totalDaysInMonth(2009, 1); // 28 + +// you can also pass a Date object as single argument +totalDaysInMonth( new Date(2013, 0, 1) ); // 31 +``` + + +## totalDaysInYear(fullYear):Number + +Returns the amount of days in the year taking into consideration leap years +(following Gregorian calendar). + +see: [`isLeapYear()`](#isLeapYear), [`totalDaysInMonth()`](#totalDaysInMonth) + +```js +totalDaysInYear(2008); // 366 (leap year) +totalDaysInYear(2009); // 365 + +// you can also pass a Date object as single argument +totalDaysInYear( new Date(2013, 0, 1) ); // 365 +``` + + + +## weekOfTheYear(date, [firstDayOfWeek]):Number + +Returns how many weeks elapsed since start of the year (`0..53`). + +`firstDayOfWeek` can be `0` (Sunday) or `1` (Monday). By default weeks start at +Sunday. + +It will return `0` if `date` is before the first `firstDayOfWeek` of the year. + +```js +// Tue Jan 01 2013 +weekOfTheYear( new Date(2013,0,1) ); // 0 +// Wed Jan 09 2013 +weekOfTheYear( new Date(2013,0,9) ); // 1 +// Sun Jan 01 2012 +weekOfTheYear( new Date(2012,0,1) ); // 1 +// Mon Jan 09 2012 +weekOfTheYear( new Date(2012,0,9) ); // 2 +``` + + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/function.md b/node_modules/express-error-handler/node_modules/mout/doc/function.md new file mode 100644 index 000000000..f753744e0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/function.md @@ -0,0 +1,210 @@ +# function # + +Function*(al)* utilities. + + + +## bind(fn, context, [...args]):Function + +Return a function that will execute in the given context, optionally adding any additional supplied parameters to the beginning of the arguments collection. + +### Arguments + + 1. `fn` (Function) : Target Function + 2. `context` (Object) : Execution context (object used as `this`) + 3. `[...args]` (*) : Arguments (0...n arguments) + +See: [`partial()`](#partial), [object/bindAll](./object.html#bindAll) + + + +## compose(...fn):Function + +Returns the composition of a list of functions, where each function consumes +the return value of the function that follows. In math terms, composing the +functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + +```js +function add2(x) { return x + 2 } +function multi2(x) { return x * 2 } +map([1, 2, 3], compose(add2, multi2)); // [4, 6, 8] + +//same as +map([1, 2, 3], function(x){ + return add2( multi2(x) ); +}); +``` + + + +## debounce(fn, delay[, isAsap]):Function + +Creates a function that will delay the execution of `fn` until after `delay` +milliseconds have elapsed since the last time it was invoked. + +Subsequent calls to the debounced function will return the result of the last +`fn` call. + +```js +// sometimes less is more +var lazyRedraw = debounce(redraw, 300); +foo.on.resize.add(lazyRedraw); +``` + +In this visualization, `|` is a debounced-function call and `X` is the actual +callback execution: + + Default + ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| + X X + + Debounced with `isAsap == true`: + ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| + X X + +You also have the option to cancel the debounced call if it didn't happen yet: + +```js +lazyRedraw(); +// lazyRedraw won't be called since `cancel` was called before the `delay` +lazyRedraw.cancel(); +``` + +See: [`throttle()`](#throttle) + + +## func(name):Function + +Returns a function that calls a method with given `name` on supplied object. +Useful for iteration methods like `array/map` and `array/forEach`. + +See: [`prop()`](#prop) + +```js +// will call the method `getName()` for each `user` +var names = map(users, func('getName')); +``` + + + +## partial(fn, [...args]):Function + +Return a partially applied function supplying default arguments. + +This method is similar to [`bind`](#bind), except it does not alter the this +binding. + +### Arguments + + 1. `fn` (Function) : Target Function + 2. `[...args]` (*) : Arguments (0...n arguments) + +See: [`bind()`](#bind) + +```js +function add(a, b){ return a + b } +var add10 = partial(add, 10); +console.log( add10(2) ); // 12 +``` + + + +## prop(name):Function + +Returns a function that gets a property with given `name` from supplied object. +Useful for using in conjunction with `array/map` and/or for creating getters. + +See: [`array/pluck()`](array.html#pluck) + +```js +var users = [{name:"John", age:21}, {name:"Jane", age:25}]; +// ["John", "Jane"] +var names = map(users, prop('name')); +``` + + + +## series(...fn):Function + +Returns a function that will execute all the supplied functions in order and +passing the same parameters to all of them. Useful for combining multiple +`array/forEach` into a single one and/or for debugging. + +```js +// call `console.log()` and `doStuff()` for each item item in the array +forEach(arr, series(console.log, doStuff)); +``` + + + +## throttle(fn, interval):Function + +Creates a function that, when executed, will only call the `fn` function at +most once per every `interval` milliseconds. + +If the throttled function is invoked more than once during the wait timeout, +`fn` will also be called on the trailing edge of the timeout. + +Subsequent calls to the throttled function will return the result of the last +`fn` call. + +```js +// sometimes less is more +var lazyRedraw = throttle(redraw, 300); +foo.on.resize.add(lazyRedraw); +``` + +In this visualization, `|` is a throttled-function call and `X` is the actual +`fn` execution: + + ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| + X X X X X X X X X X X X + +You also have the option to cancel the throttled call if it didn't happen yet: + +```js +lazyRedraw(); +setTimeout(function(){ + lazyRedraw(); + // lazyRedraw will be called only once since `cancel` was called before + // the `interval` for 2nd call completed + lazyRedraw.cancel(); +}, 250); +``` + +See: [`debounce()`](#debounce) + + +## timeout(fn, millis, context, [...args]):Number + +Functions as a wrapper for `setTimeout`. Calls a the function `fn` after a given delay `millis` in milliseconds. +The function is called within the specified context. The return value can be used to clear the timeout using `clearTimeout`. + +```js +var id = timeout(doStuff, 300, this); + +clearTimeout(id); +``` + +## times(n, callback, [context]):void + +Iterates over a callback `n` times. + +### Arguments + + 1. `n` (Number) : Number of iterations + 2. `callback` (Function) : Closure executed for every iteration + 3. `context` (Object) : Execution context (object used as `this`) + +```js +var output = ''; +times(5, function(i) { + output += i.toString(); +}); +// output: 01234 +``` + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... diff --git a/node_modules/express-error-handler/node_modules/mout/doc/lang.md b/node_modules/express-error-handler/node_modules/mout/doc/lang.md new file mode 100644 index 000000000..8ad3928b3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/lang.md @@ -0,0 +1,464 @@ +# lang # + +Language Utilities. Easier inheritance, scope handling, type checks. + + + +## clone(val):* + +Clone native types like Object, Array, RegExp, Date and primitives. + +This method will not clone values that are referenced within `val`. It will +only copy the value reference to the new value. If the value is not a plain +object but is an object, it will return the value unchanged. + +### Example + +```js +var a = { foo: 'bar' }; +var b = clone(a); +console.log(a === b); // false +console.log(a.foo === b.foo); // true + +var c = [1, 2, 3]; +var d = clone(b); +console.log(c === d); // false +console.log(c); // [1, 2, 3] +``` + +See: [`deepClone()`](#deepClone) + + + +## createObject(parent, [props]):Object + +Create Object using prototypal inheritance and setting custom properties. + +Mix between [Douglas Crockford Prototypal Inheritance](http://javascript.crockford.com/prototypal.html) and [`object/mixIn`](./object.html#mixIn). + +### Arguments + + 1. `parent` (Object) : Parent Object + 2. `[props]` (Object) : Object properties + +### Example + +```js +var base = { + trace : function(){ + console.log(this.name); + } +}; + +var myObj = createObject(base, { + name : 'Lorem Ipsum' +}); + +myObject.trace(); // "Lorem Ipsum" +``` + + + +## ctorApply(constructor, args):Object + +Do `Function.prototype.apply()` on a constructor while maintaining prototype +chain. + +```js +function Person(name, surname) { + this.name = name; + this.surname = surname; +} + +Person.prototype.walk = function(){ + console.log(this.name +' is walking'); +}; + +var args = ['John', 'Doe']; + +// "similar" effect as calling `new Person("John", "Doe")` +var john = ctorApply(Person, args); +john.walk(); // "John is walking" +``` + + + +## deepClone(val, [instanceClone]):* + +Deep clone native types like Object, Array, RegExp, Date and primitives. + +The `instanceClone` function will be invoked to clone objects that are not +"plain" objects (as defined by [`isPlainObject`](#isPlainObject)) if it is +provided. If `instanceClone` is not specified, it will not attempt to clone +non-plain objects, and will copy the object reference. + +### Example + +```js +var a = {foo:'bar', obj: {a:1, b:2}}; +var b = deepClone(a); // {foo:'bar', obj: {a:1, b:2}} +console.log( a === b ); // false +console.log( a.obj === b.obj ); // false + +var c = [1, 2, [3, 4]]; +var d = deepClone(c); // [1, 2, [3, 4]] +var e = c.concat(); // [1, 2, [3, 4]] + +console.log( c[2] === d[2] ); // false +// concat doesn't do a deep clone, arrays are passed by reference +console.log( e[2] === d[2] ); // true + +function Custom() { } +function cloneCustom(x) { return new Custom(); } +var f = { test: new Custom() }; +var g = deepClone(f, cloneCustom); +g.test === f.test // false, since new Custom instance will be created +``` + +See: [`clone()`](#clone) + + + +## defaults(val, ...defaults):void + +Return first value that isn't `null` or `undefined`. + + function doSomethingAwesome(foo, bar) { + // default arguments + foo = defaults(foo, 'lorem'); + bar = defaults(bar, 123); + // ... + } + + + +## inheritPrototype(childCtor, parentCtor):void + +Inherit the prototype methods from one constructor into another. + +Similar to [node.js util/inherits](http://nodejs.org/docs/latest/api/util.html#util_util_inherits_constructor_superconstructor). + +```js +function Foo(name){ + this.name = name; +} +Foo.prototype = { + getName : function(){ + return this.name; + } +}; + +function Bar(name){ + Foo.call(this, name); +} +//should be called before calling constructor +inheritPrototype(Bar, Foo); + +var myObj = new Bar('lorem ipsum'); +myObj.getName(); // "lorem ipsum" + +console.log(myObj instanceof Foo); // true + +// you also have access to the "super" constructor +console.log(Bar.super_ === Foo); // true +``` + + +## is(x, y):Boolean + +Check if both values are identical/egal. + +```js +// wtfjs +NaN === NaN; // false +-0 === +0; // true + +is(NaN, NaN); // true +is(-0, +0); // false +is('a', 'b'); // false +``` + +See: [`isnt()`](#isnt) + + + +## isnt(x, y):Boolean + +Check if both values are not identical/egal. + +```js +// wtfjs +NaN === NaN; // false +-0 === +0; // true + +isnt(NaN, NaN); // false +isnt(-0, +0); // true +isnt('a', 'b'); // true +``` + +See: [`is()`](#is) + + + + +## isArguments(val):Boolean + +If value is an "Arguments" object. + + + +## isArray(val):Boolean + +If value is an Array. Uses native ES5 `Array.isArray()` if available. + + + +## isBoolean(val):Boolean + +If value is a Boolean. + + + +## isDate(val):Boolean + +If value is a Date. + + + +## isEmpty(val):Boolean + +Checks if Array/Object/String is empty. + + +```js +isEmpty(''); // true +isEmpty('bar'); // false +isEmpty([]); // true +isEmpty([1, 2]); // false +isEmpty({}); // true +isEmpty({a:1, b:2}); // false +``` + + +## isFinite(val):Boolean + +Checks if value is Finite. + +**IMPORTANT:** This is not the same as native `isFinite`, which will return +`true` for values that can be coerced into finite numbers. See +http://es5.github.com/#x15.1.2.5. + +```js +isFinite(123); // true +isFinite(Infinity); // false + +// this is different than native behavior +isFinite(''); // false +isFinite(true); // false +isFinite([]); // false +isFinite(null); // false +``` + + +## isFunction(val):Boolean + +If value is a Function. + + + +## isKind(val, kind):Boolean + +If value is of "kind". (used internally by some of the *isSomething* checks). + +Favor the other methods since strings are commonly mistyped and also because +some "kinds" can only be accurately checked by using other methods (e.g. +`Arguments`), some of the other checks are also faster. + +```js +isKind([1,2], 'Array'); // true +isKind(3, 'Array'); // false +isKind(3, 'Number'); // true +``` + +See: [`kindOf()`](#kindOf) + + + +## isInteger(val):Boolean + +Check if value is an integer. + +```js +isInteger(123); // true +isInteger(123.45); // false +isInteger({}); // false +isInteger('foo'); // false +isInteger('123'); // false +``` + + + +## isNaN(val):Boolean + +Check if value is not a number. + +It doesn't coerce value into number before doing the check, giving better +results than native `isNaN`. Returns `true` for everything besides numeric +values. + +**IMPORTANT:** behavior is very different than the native `isNaN` and way more +useful!!! See: http://es5.github.io/#x15.1.2.4 + +```js +isNaN(123); // false + +isNaN(NaN); // true +isNaN({}); // true +isNaN(undefined); // true +isNaN([4,5]); // true + +// these are all "false" on native isNaN and main reason why this module exists +isNaN(''); // true +isNaN(null); // true +isNaN(true); // true +isNaN(false); // true +isNaN("123"); // true +isNaN([]); // true +isNaN([5]); // true +``` + + + +## isNull(val):Boolean + +If value is `null`. + + + +## isNumber(val):Boolean + +If value is a Number. + + + +## isObject(val):Boolean + +If value is an Object. + + + +## isPlainObject(val):Boolean + +If the value is an Object created by the Object constructor. + + + +## isRegExp(val):Boolean + +If value is a RegExp. + + + +## isString(val):Boolean + +If value is a String. + + + +## isUndefined(val):Boolean + +If value is `undefined`. + + + +## kindOf(val):String + +Gets kind of value (e.g. "String", "Number", "RegExp", "Null", "Date"). +Used internally by `isKind()` and most of the other *isSomething* checks. + +```js +kindOf([1,2]); // "Array" +kindOf('foo'); // "String" +kindOf(3); // "Number" +``` + +See: [`isKind()`](#isKind) + + +## toArray(val):Array + +Convert array-like object into Array or wrap value into Array. + +```js +toArray({ + "0" : "foo", + "1" : "bar", + "length" : 2 +}); // ["foo", "bar"] + +function foo(){ + return toArray(arguments); +} +foo("lorem", 123); // ["lorem", 123] + +toArray("lorem ipsum"); // ["lorem ipsum"] +toArray(window); // [window] +toArray({foo:"bar", lorem:123}); // [{foo:"bar", lorem:123}] +``` + +See: object/values() + + + +## toNumber(val):Number + +Convert value into number. + +```js +// numeric values are typecasted as Number +toNumber('123'); // 123 +toNumber(-567); // -567 + +// falsy values returns zero +toNumber(''); // 0 +toNumber(null); // 0 +toNumber(undefined); // 0 +toNumber(false); // 0 + +// non-numeric values returns NaN +toNumber('asd'); // NaN +toNumber({}); // NaN +toNumber([]); // NaN + +// Date objects return milliseconds since epoch +toNumber(new Date(1985, 6, 23)); // 490935600000 +``` + + + +## toString(val):String + +Convert any value to its string representation. + +Will return an empty string for `undefined` or `null`, otherwise will convert +the value to its string representation. + +```js +// null and undefined are converted into empty strings +toString(null); // "" +toString(undefined); // "" + +toString(1); // "1" +toString([1,2,3]); // "1,2,3" +toString(false); // "false" + +// uses `val.toString()` to convert value +toString({toString:funtion(){ return 'foo'; }}); // "foo" +``` + + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... diff --git a/node_modules/express-error-handler/node_modules/mout/doc/math.md b/node_modules/express-error-handler/node_modules/mout/doc/math.md new file mode 100644 index 000000000..f45be3ed6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/math.md @@ -0,0 +1,298 @@ +# math # + +Math utilities. + + +## ceil(val[, step]):Number + +Round value up to full steps. Similar to `Math.ceil()` but can round value +to an arbitrary *radix*. + + ceil(7.2); // 8 + ceil(7.8); // 8 + ceil(7, 5); // 10 + ceil(11, 5); // 15 + ceil(15, 5); // 15 + +### Common use cases + +Round values by increments of 5/10/1000/etc. + +See: [`round()`](#round), [`floor()`](#floor), [`countSteps()`](#countSteps) + + + +## clamp(val, min, max):Number + +Clamps value inside range. + +`clamp()` is extremely useful in cases where you need to limit a value inside +a certain range. So instead of doing a complex `if/else` to filter/process the +value you can restrict it to always be inside the desired range: + + clamp(-5, 0, 10); // 0 + clamp(7, 1, 10); // 7 + clamp(8, 1, 10); // 8 + clamp(10, 1, 10); // 10 + clamp(11, 1, 10); // 10 + +If the value is smaller than `min` it returns the `min`, if `val` is higher +than `max` it returns `max`. + +### Common use cases + +Any situation where you need to limit a number inside a range like: slider +position, image galleries (so user can't skip to an image that doesn't +exist), drag and drop, scroll boundaries, etc. + +See: [`loop()`](#loop) + + + + +## countSteps(val, step[, overflow]):Number + +Count number of full steps. + +### Arguments: + + 1. `val` (Number) : Value. + 2. `step` (Number) : Step size. + 3. `[overflow]` (Number) : Maximum number of steps, nSteps will loop if +`>=` than overflow. + + +Count steps is very useful for cases where you need to know how many "full +steps" the number *completed*. Think of it as a division that only returns +integers and ignore remainders. + + countSteps(3, 5); // 0 + countSteps(6, 5); // 1 + countSteps(12, 5); // 2 + countSteps(18, 5); // 3 + countSteps(21, 5); // 4 + +You can also set an `overflow` which will reset the *counter* before reaching +this number. + + countSteps(3, 5, 3); // 0 + countSteps(6, 5, 3); // 1 + countSteps(12, 5, 3); // 2 + countSteps(18, 5, 3); // 0 + countSteps(21, 5, 3); // 1 + +### Common use cases + +#### How many items fit inside an area: + + var containerWidth = 100; + var itemWidth = 8; + var howManyFit = countSteps(containerWidth, itemWidth); // 12 + +#### Split value into different scales or convert value from one scale to another + +From [mout/time/parseMs](time.html#parseMs): + + function parseMs(ms){ + return { + milliseconds : countSteps(ms, 1, 1000), + seconds : countSteps(ms, 1000, 60), + minutes : countSteps(ms, 60000, 60), + hours : countSteps(ms, 3600000, 24), + days : countSteps(ms, 86400000) + }; + } + + // {days:27, hours:4, minutes:26, seconds:5, milliseconds:454} + parseMs(2348765454); + + + +## floor(val[, step]):Number + +Round value down to full steps. Similar to `Math.floor()` but can round value +to an arbitrary *radix*. (formerly `snap`) + + floor(7.2); // 7 + floor(7.8); // 7 + floor(7, 5); // 5 + floor(11, 5); // 10 + floor(15, 5); // 15 + +### Common use cases + +Round values by increments of 5/10/1000/etc. + +See: [`round()`](#round), [`ceil()`](#ceil), [`countSteps()`](#countSteps) + + + +## inRange(val, min, max[, threshold]):Boolean + +Checks if value is inside the range. + + inRange(-6, 1, 10); // false + inRange( 5, 1, 10); // true + inRange(12, 1, 10); // false + +The threshold can be useful when you want granular control of what should match +and/or the precision could change at runtime or by some configuration option, +avoids the clutter of adding/subtracting the `threshold` from `mix` and `max`. + + inRange(12, 1, 10, 2); // true + inRange(13, 1, 10, 2); // false + +### Common use cases + +Anything that needs to check if value is inside a range, be it collision +detection, limiting interaction by mouse position, ignoring parts of the logic +that shouldn't happen if value isn't valid, simplify `if/else` conditions, +making code more readable, etc... + + + + +## isNear(val, target, threshold):Boolean + +Check if value is close to target. + +Similar to `inRange()` but used to check if value is close to a certain value +or match the desired value. Basically to simplify `if/else` conditions and to +make code clearer. + + isNear( 10.2, 10, 0.5); // true + isNear( 10.5, 10, 0.5); // true + isNear(10.51, 10, 0.5); // false + +### Common use cases + +Games where a certain action should happen if an *actor* is close to a target, +gravity fields, any numeric check that has some tolerance. + + + + +## lerp(ratio, start, end):Number + +Linear interpolation. + + lerp(0.5, 0, 10); // 5 + lerp(0.75, 0, 10); // 7.5 + +### Common use cases + +Linear interpolation is commonly used to create animations of elements moving +from one point to another, where you simply update the current ratio (which in +this case represents time) and get back the position of the element at that +"frame". + +The core idea of `lerp` is that you are using a number that goes from `0` to +`1` to specify a ratio inside that scale. This concept can be applied to +convert numbers from different scales easily. + +See: [`map()`](#map), [`norm()`](#norm) + + + + +## loop(val, min, max):Number + +Loops value inside range. Will return `min` if `val > max` and `max` if `val +< min`, otherwise it returns `val`. + + loop(-1, 0, 10); // 10 + loop( 1, 0, 10); // 1 + loop( 5, 0, 10); // 5 + loop( 9, 0, 10); // 9 + loop(10, 0, 10); // 10 + loop(11, 0, 10); // 0 + +Similar to [`clamp()`](#clamp) but *loops* the value inside the range when an +overflow occurs. + +### Common use cases + +Image galleries, infinite scroll, any kind of logic that requires that the +first item should be displayed after the last one or the last one should be +displayed after first if going on the opposite direction. + +See: [`clamp()`](#clamp) + + + + +## map(val, min1, max1, min2, max2):Number + +Maps a number from one scale to another. + + map(3, 0, 4, -1, 1) // 0.5 + map(3, 0, 10, 0, 100) // 30 + +### Common use cases + +Very useful to convert values from/to multiple scales. + +Let's suppose we have a slider that needs to go from `2000` to `5000` and that slider +has `300px` of width, here is how we would translate the knob position into the +current value: + + var knobX = 123; + var sliderWid = 300; + var minVal = 2000; + var maxVal = 5000; + + var curVal = map(knobX, 0, sliderWid, minVal, maxVal); // 3230 + +See: [`lerp()`](#lerp), [`norm()`](#norm) + + + + +## norm(val, min, max):Number + +Gets normalized ratio of value inside range. + + norm(50, 0, 100); // 0.5 + norm(75, 0, 100); // 0.75 + +### Common use cases + +Convert values between scales, used by [`map()`](#map) internally. Direct +opposite of [`lerp()`](#lerp). + +See: [`lerp()`](#lerp), [`map()`](#map) + + + +## round(val[, step]):Number + +Round value to full steps. Similar to `Math.round()` but allow setting an +arbitrary *radix*. + + // default + round(0.22); // 0 + round(0.49); // 0 + round(0.51); // 1 + + // custom radix + round(0.22, 0.5); // 0 + round(0.49, 0.5); // 0.5 + round(0.51, 0.5); // 0.5 + round(0.74, 0.5); // 0.5 + round(0.75, 0.5); // 1 + round(1.24, 0.5); // 1 + round(1.25, 0.5); // 1.5 + round(1.74, 0.5); // 1.5 + +### Common use cases + +Round values by increments of 0.5/5/10/1000/etc. + +See: [`floor()`](#floor), [`ceil()`](#ceil), [`countSteps()`](#countSteps) + + + +------------------------------------------------------------------------------- + +For more usage more info check the specs and source code. + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/number.md b/node_modules/express-error-handler/node_modules/mout/doc/number.md new file mode 100644 index 000000000..8d93865bd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/number.md @@ -0,0 +1,225 @@ +# number # + +Number utilities. + + +## abbreviate(val[, nDecimalDigits, dictionary]):String + +Abbreviate number to thousands (K), millions (M) or billions (B). + +The default value for `nDecimalDigits` is `1`. + +### Example + + abbreviate(123456); // "123.5K" + abbreviate(12345678); // "12.3M" + abbreviate(1234567890); // "1.2B" + +You can set the amount of decimal digits (default is `1`): + + abbreviate(543); // "0.5K" + abbreviate(543, 1); // "0.5K" + abbreviate(543, 2); // "0.54K" + abbreviate(543, 3); // "0.543K" + +You can customize the abbreviation by passing a custom "dictionary": + + var _ptbrDict = { + thousands : ' mil', + millions : ' Mi', + billions : ' Bi' + }; + function customAbbr(val) { + return abbreviate(val, 1, _ptbrDict); + } + + customAbbr(123456); // "123.5 mil" + customAbbr(12345678); // "12.3 Mi" + customAbbr(1234567890); // "1.2 Bi" + + + +## currencyFormat(val[, nDecimalDigits, decimalSeparator, thousandsSeparator]):String + +Format a number as currency. + +### Example: + + currencyFormat(1000); // "1,000.00" + currencyFormat(1000, 1); // "1,000.0" + currencyFormat(1000, 2, ',', '.'); // "1.000,00" + + + +## enforcePrecision(val, nDecimalDigits):Number + +Enforce a specific amount of decimal digits and also fix floating point +rounding issues. + +### Example: + +```js +enforcePrecision(0.615, 2); // 0.62 +enforcePrecision(0.625, 2); // 0.63 +//floating point rounding "error" (rounds to odd number) ++(0.615).toFixed(2); // 0.61 ++(0.625).toFixed(2); // 0.63 +``` + + + +## MAX_INT:Number + +Maximum 32-bit signed integer value. `Math.pow(2, 31) - 1` + +### Example: + +```js +console.log( MAX_INT ); // 2147483647 +``` + + +## MAX_UINT:Number + +Maximum 32-bit unsigned integer value. `Math.pow(2, 32) - 1` + +### Example: + +```js +console.log( MAX_UINT ); // 4294967295 +``` + + +## MIN_INT:Number + +Minimum 32-bit signed integer value. `Math.pow(2, 31) * -1`. + +### Example: + +```js +console.log( MIN_INT ); // -2147483648 +``` + + +## pad(n, minLength[, char]):String + +Add padding zeros if `n.length` < `minLength`. + +### Example: + +```js +pad(1, 5); // "00001" +pad(12, 5); // "00012" +pad(123, 5); // "00123" +pad(1234, 5); // "01234" +pad(12345, 5); // "12345" +pad(123456, 5); // "123456" + +// you can also specify the "char" used for padding +pad(12, 5, '_'); // "___12" +``` + +see: [string/lpad](./string.html#lpad) + + + +## rol(val, shift):Number + +Bitwise circular shift left. + +More info at [Wikipedia#Circular_shift](http://en.wikipedia.org/wiki/Circular_shift) + + + +## ror(val, shift):Number + +Bitwise circular shift right. + +More info at [Wikipedia#Circular_shift](http://en.wikipedia.org/wiki/Circular_shift) + + + +## sign(val):Number + +Returns `-1` if value is negative, `0` if the value is `0` and `1` if value is positive. Useful for +multiplications. + +```js +sign(-123); // -1 +sign(123); // 1 +sign(0); // 0 +``` + + + +## toInt(val):Number + +"Convert" value into an 32-bit integer. Works like `Math.floor` if `val > 0` and +`Math.ceil` if `val < 0`. + +**IMPORTANT:** val will wrap at [number/MIN_INT](#MIN_INT) and +[number/MAX_INT](#MAX_INT). + +Created because most people don't know bitwise operations and also because this +feature is commonly needed. + +[Perf tests](http://jsperf.com/vs-vs-parseint-bitwise-operators/7) + +### Example: + +```js +toInt(1.25); // 1 +toInt(0.75); // 0 +toInt(-0.55); // 0 +toInt(-5.0001) // -5 +``` + + + +## toUInt(val):Number + +"Convert" value into an 32-bit unsigned integer. + +Works like AS3#uint(). + +**IMPORTANT:** val will wrap at 2^32. + +### Example: + +```js +toUInt(1.25); // 1 +toUInt(0.75); // 0 +toUInt(-0.55); // 0 +toUInt(-5.0001); // 4294967291 +toUInt(Math.pow(2,32) - 0.5); // 4294967295 +toUInt(Math.pow(2,32) + 0.5); // 0 +``` + + +## toUInt31(val):Number + +"Convert" value into an 31-bit unsigned integer (since 1 bit is used for sign). + +Useful since all bitwise operators besides `>>>` treat numbers as signed +integers. + +**IMPORTANT:** val will wrap at 2^31 and negative numbers will be treated as +`zero`. + +### Example: + +```js +toUInt31(1.25); // 1 +toUInt31(0.75); // 0 +toUInt31(-0.55); // 0 +toUInt31(-5.0001); // 0 +toUInt31(Math.pow(2,31) - 0.5); // 21474836470 +toUInt31(Math.pow(2,31) + 0.5); // 0 +``` + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/object.md b/node_modules/express-error-handler/node_modules/mout/doc/object.md new file mode 100644 index 000000000..b120aeed9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/object.md @@ -0,0 +1,780 @@ +# object # + +Object utilities. + + + +## bindAll(obj, [...methodNames]):void + +Bind methods of the target object to always execute on its own context +(ovewritting the original function). + +See: [function/bind](./function.html#bind) + +```js +var view = { + name: 'Lorem Ipsum', + logNameOnClick: function() { + console.log(this.name); + } +}; + +// binds all methods by default +bindAll(view); +jQuery('#docs').on('click', view.logNameOnClick); +``` + +You can also specify the list of methods that you want to bind (in case you +just want to bind a few of them). + +```js +// only the listed methods will be bound to `obj` context +bindAll(obj, 'logNameOnClick', 'doAwesomeStuffOnDrag'); +``` + + + +## contains(obj, value):Boolean + +Similar to [Array/contains](array.html#contains). Checks if Object contains +value. + +```js +var obj = { + a: 1, + b: 2, + c: 'bar' +}; +contains(obj, 2); // true +contains(obj, 'foo'); // false +``` + + + +## deepEquals(a, b, [callback]):Boolean + +Recursively tests whether two objects contain the same keys and equal values. + +`callback` specifies the equality comparison function used to compare +non-object values. It defaults to using the strict equals (`===`) operator. + +If the values are both an object, it will recurse into the objects, checking if +their keys/values are equal. It will only check the keys and values contained +by the objects; it will not check the objects' prototypes. If the either of +the values are not objects, they will be checked using the `callback` function. + +Example: + +```js +deepEquals({ a: 1 }, { a: 1 }); // true +deepEquals({ value: { a: 1 } }, { value: { a: 1 } }); // true +deepEquals({ value: { a: 1 } }, { value: { a: 2 } }); // false +deepEquals({ value: { a: 1 } }, { value: { a: 1, b: 2 } }); // false +deepEquals({}, null); // false +deepEquals(null, null); // true +deepEquals( + { a: { b: 1 } }, + { a: { b: '1' } }, + function(a, b) { return a == b; }); // true +``` + +See: [`equals()`](#equals) + + + +## deepFillIn(target, ...objects):Object + +Fill missing properties recursively. + +It's different from `deepMixIn` since it won't override any existing property. +It's also different from `merge` since it won't clone child objects during the +process. + +It returns the target object and mutates it in place. + +See: [`fillIn()`](#fillIn), [`deepMixIn()`](#deepMixIn), [`merge()`](#merge) + +```js +var base = { + foo : { + bar : 123 + }, + lorem : 'ipsum' +}; +var options = deepFillIn({foo : { baz : 45 }, lorem : 'amet'}, base); +// > {foo: {bar:123, baz : 45}, lorem : 'amet'} +``` + + + +## deepMatches(target, pattern):Boolean + +Recursively checks if object contains all properties/value pairs. When both +the target and pattern values are arrays, it checks that the target value +contain matches for all the items in the pattern array (independent of order). + +```js +var john = { + name: 'John', + age: 22, + pets: [ + { type: 'cat', name: 'Grumpy Cat' }, + { type: 'dog', name: 'Hawk' } + ] +}; + +deepMatches(john, { name: 'John' }); // true +deepMatches(john, { age: 21 }); // false +deepMatches(john, { pets: [ { type: 'cat' } ] }); // true +deepMatches(john, { pets: [ { name: 'Hawk' } ] }); // true +deepMatches(john, { pets: [ { name: 'Hairball' } ] }); // false +``` + +See [`matches()`](#matches) + + + +## deepMixIn(target, ...objects):Object + +Mixes objects into the target object, recursively mixing existing child objects +as well. + +It will only recursively mix objects if both (existing and new) values are +plain objects. + +Returns the target object. Like [`merge()`](#merge), but mutates the target +object, and does not clone child objects. + +```js +var target = { + foo: { + name: "foo", + id: 1 + } +}; + +deepMixIn(target, { foo: { id: 2 } }); +console.log(target); // { foo: { name: "foo", id: 2 } } +``` + +See: [`mixIn()`](#mixIn), [`merge()`](#merge), [`deepFillIn()`](#deepFillIn) + + + +## equals(a, b, [callback]):Boolean + +Tests whether two objects contain the same keys and values. + +`callback` specifies the equality comparison function used to compare the +values. It defaults to using the strict equals (`===`) operator. + +It will only check the keys and values contained by the objects; it will not +check the objects' prototypes. If either of the values are not objects, they +will be compared using the `callback` function. + +```js +equals({}, {}); // true +equals({ a: 1 }, { a: 1 }); // true +equals({ a: 1 }, { a: 2 }); // false +equals({ a: 1, b: 2 }, { a: 1 }); // false +equals({ a: 1 }, { a: 1, b: 2 }); // false +equals(null, null); // true +equals(null, {}); // false +equals({ a: 1 }, { a: '1' }, function(a, b) { return a == b; }); // true +``` + + + +## every(obj, callback, [thisObj]):Boolean + +Similar to [Array/every](array.html#every). Tests whether all properties in the +object pass the test implemented by the provided callback. + +```js +var obj = { + a: 1, + b: 2, + c: 3, + d: 'string' +}; + +every(obj, isNumber); // false +``` + + + +## fillIn(obj, ...default):Object + +Fill in missing properties in object with values from the *defaults* objects. + + var base = { + foo : 'bar', + num : 123 + }; + + fillIn({foo:'ipsum'}, base); // {foo:'ipsum', num:123} + +PS: it allows merging multiple objects at once, the first ones will take +precedence. + +See: [`mixIn()`](#mixIn), [`merge()`](#merge), [`deepFillIn()`](#deepFillIn) + + + +## filter(obj, callback, [thisObj]) + +Returns a new object containing all properties where `callback` returns true, +similar to Array/filter. It does not use properties from the object's +prototype. + +Callback receives the same arguments as `forOwn()`. + +See: [`forOwn()`](#forOwn), [`forIn()`](#forIn), [`pick()`](#pick) + +```js +var obj = { + foo: 'value', + bar: 'bar value' +}; + +// returns { bar: 'bar value' } +filter(obj, function(v) { return value.length > 5; }); + +// returns { foo: 'value' } +filter(obj, function(v, k) { return k === 'foo'; }); +``` + + + +## find(obj, callback, [thisObj]) + +Loops through all the properties in the Object and returns the first one that +passes a truth test (callback), similar to [Array/find](array.html#find). +Unlike Array/find, order of iteration is not guaranteed. + +```js +var obj = { + a: 'foo', + b: 12 +}; + +find(obj, isString); // 'foo' +find(obj, isNumber); // 12 +``` + + + +## forIn(obj, callback[, thisObj]) + +Iterate over all properties of an Object, similar to +[Array/forEach](array.html#forEach). + +It [avoids don't enum bug on IE](https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug). +It **will** iterate over inherited (enumerable) properties from the prototype. + +It allows exiting the iteration early by returning `false` on the callback. + +See: [`forOwn()`](#forOwn), [`keys()`](#keys), [`values()`](#values) + +### Callback arguments + +Callback will receive the following arguments: + + 1. Property Value (*) + 2. Key name (String) + 3. Target object (Object) + +### Example + +```js +function Foo(){ + this.foo = 1; + this.bar = 2; +} + +Foo.prototype.lorem = 4; + +var obj = new Foo(); + +var result = 0; +var keys = []; + +forIn(obj, function(val, key, o){ + result += val; + keys.push(key); +}); + +console.log(result); // 7 +console.log(keys); // ['foo', 'bar', 'lorem'] +``` + + + +## forOwn(obj, callback[, thisObj]) + +Iterate over all own properties from an Object, similar to +[Array/forEach](array.html#forEach). + +It [avoids don't enum bug on IE](https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug). +Notice that it **won't** iterate over properties from the prototype. + +It allows exiting the iteration early by returning `false` on the callback. + +See: [`forIn()`](#forIn), [`keys()`](#keys), [`values()`](#values) + +### Callback arguments + +Callback will receive the following arguments: + + 1. Property Value (*) + 2. Key name (String) + 3. Target object (Object) + +### Example + +```js +function Foo(){ + this.foo = 1; + this.bar = 2; +} + +// will be ignored +Foo.prototype.lorem = 4; + +var obj = new Foo(); + +var result = 0; +var keys = []; + +forOwn(obj, function(val, key, o){ + result += val; + keys.push(key); +}); + +console.log(result); // 3 +console.log(keys); // ['foo', 'bar'] +``` + + + +## functions(obj):Array + +Returns a sorted list of all enumerable properties that have function values +(including inherited properties). + +```js +var obj = { + foo : function(){}, + bar : 'baz' +}; +functions(obj); // ['foo'] +``` + + + +## get(obj, propName):* + +Returns nested property value. Will return `undefined` if property doesn't +exist. + +See: [`set()`](#set), [`namespace()`](#namespace), [`has()`](#has) + +```js +var lorem = { + ipsum : { + dolor : { + sit : 'amet' + } + } + }; + +get(lorem, 'ipsum.dolor.sit'); // "amet" +get(lorem, 'foo.bar'); // undefined +``` + + + +## has(obj, propName):Boolean + +Checks if object contains a child property. Useful for cases where you need to +check if an object contain a *nested* property. It will get properties +inherited by the prototype. + +see: [`hasOwn()`](#hasOwn), [`get()`](#get) + +```js +var a = { + b : { + c : 123 + } + }; + +has(a, 'b.c'); // true +has(a, 'foo.c'); // false +``` + +### Common use case + +```js +if( has(a, 'foo.c') ){ // false + // ... +} + +if( a.foo.c ){ // ReferenceError: `foo` is not defined + // ... +} +``` + + + +## hasOwn(obj, propName):Boolean + +Safer `Object.hasOwnProperty`. Returns a boolean indicating whether the object +has the specified property. + +see: [`has()`](#has) + +```js +var obj = { + foo: 1, + hasOwnProperty : 'bar' +}; + +obj.hasOwnProperty('foo'); // ERROR! hasOwnProperty is not a function + +hasOwn(obj, 'foo'); // true +hasOwn(obj, 'hasOwnProperty'); // true +hasOwn(obj, 'toString'); // false +``` + + + +## keys(obj):Array + +Returns an array of all own enumerable properties found upon a given object. +It will use the native `Object.keys` if present. + +PS: it won't return properties from the prototype. + +See: [`forOwn()`](#forOwn), [`values()`](#values) + +```js +var obj = { + foo : 1, + bar : 2, + lorem : 3 +}; +keys(obj); // ['foo', 'bar', 'lorem'] +``` + + + +## map(obj, callback, [thisObj]):Object + +Returns a new object where the property values are the result of calling the +callback for each property in the original object, similar to Array/map. + +The callback function receives the same arguments as in `forOwn()`. + +See: [`forOwn()`](#forOwn) + +```js +var obj = { foo: 1, bar: 2 }, + data = { foo: 0, bar: 1 }; + +map(obj, function(v) { return v + 1; }); // { foo: 2, bar: 3 } +map(obj, function(v, k) { return k; }); // { foo: "foo", bar: "bar" } +map(obj, function(v, k) { return this[k]; }, data); // { foo: 0, bar: 1 } +``` + + + +## matches(obj, props):Boolean + +Checks if object contains all properties/values pairs. Useful for validation +and filtering. + +```js +var john = {age:25, hair:'long', beard:true}; +var mark = {age:27, hair:'short', beard:false}; +var hippie = {hair:'long', beard:true}; +matches(john, hippie); // true +matches(mark, hippie); // false +``` + +See [`deepMatches()`](#deepMatches) + + + +## merge(...objects):Object + +Deep merges objects. Note that objects and properties will be cloned during the +process to avoid undesired side effects. It return a new object and won't +affect source objects. + +```js +var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}}; +var obj2 = {a: {b: 2, d : {f : 'yeah'} }}; + +merge(obj1, obj2); // {a: {b : 2, c : 1, d : {e : 1, f : 'yeah'}}} +``` + +See: [`deepMixIn()`](#deepMixIn), [`deepFillIn()`](#deepFillIn) + + + +## max(obj[, iterator]):* + +Returns maximum value inside object or use a custom iterator to define how +items should be compared. Similar to [Array/max](array.html#max). + +See: [`min()`](#min) + +```js +max({a: 100, b: 2, c: 1, d: 3, e: 200}); // 200 +max({a: 'foo', b: 'lorem', c: 'amet'}, function(val){ + return val.length; +}); // 'lorem' +``` + + + +## min(obj[, iterator]):* + +Returns minimum value inside object or use a custom iterator to define how +items should be compared. Similar to [Array/min](array.html#min). + +See: [`max()`](#max) + +```js +min({a: 100, b: 2, c: 1, d: 3, e: 200}); // 1 +min({a: 'foo', b: 'lorem', c: 'amet'}, function(val){ + return val.length; +}); // 'foo' +``` + + + +## mixIn(target, ...objects):Object + +Combine properties from all the objects into first one. + +This method affects target object in place, if you want to create a new Object +pass an empty object as first parameter. + +### Arguments + + 1. `target` (Object) : Target Object. + 2. `...objects` (...Object) : Objects to be combined (0...n objects). + +### Example + +```js +var a = {foo: "bar"}; +var b = {lorem: 123}; + +mixIn({}, a, b); // {foo: "bar", lorem: 123} +console.log(a); // {foo: "bar"} + +mixIn(a, b); // {foo: "bar", lorem: 123} +console.log(a); // {foo: "bar", lorem: 123} +``` + +See: [`fillIn()`](#fillIn), [`merge()`](#merge) + + + + +## namespace(obj, propName):Object + +Creates an empty object inside namespace if not existent. Will return created +object or existing object. + +See: [`get()`](#get), [`set()`](#set) + +```js +var obj = {}; +namespace(obj, 'foo.bar'); // {} +console.log(obj); // {foo:{bar:{}}} +``` + + + +## pick(obj, ...keys):Object + +Return a copy of the object that contains only the whitelisted keys. + +See: [`filter()`](#filter) + +```js +var user = { + firstName : 'John', + lastName : 'Doe', + dob : '1985/07/23', + gender : 'male' +}; + +// can pass an array of keys as second argument +var keys = ['firstName', 'dob'] +pick(user, keys); // {firstName:"John", dob: "1985/07/23"} + +// or multiple arguments +pick(user, 'firstName', 'lastName'); // {firstName:"John", lastName: "Doe"} +``` + + + +## pluck(obj, propName):Object + +Extract an object containing property values with keys as they appear in the +passed object. + +```js +var users = { + first: { + name : 'John', + age : 21 + }, + second: { + name : 'Mary', + age : 25 + } +}; + +pluck(users, 'name'); // {first: 'John', second: 'Mary'} ); +pluck(users, 'age'); // {first: 21, second: 25} ); +``` + + + +## reduce(obj, callback, initial, [thisObj]):* + +Similar to [Array/reduce](array.html#reduce). + +Apply a function against an accumulator and each property of the object (order +is undefined) as to reduce it to a single value. + +```js +var obj = {a: 1, b: 2, c: 3, d: 4}; + +function sum(prev, cur, key, list) { + compare1.push(prev); + return prev + cur; +} + +reduce(obj, sum); // 10 +``` + + + +## reject(obj, callback, thisObj):Object + +Returns a new object containing all properties where `callback` returns true, +similar to [Array/reject](array.html#reject). It does not use properties from +the object's prototype. Opposite of [`filter()`](#filter). + +See [`filter()`](#filter) + +### Example + +```js +var obj = {a: 1, b: 2, c: 3, d: 4, e: 5}; +reject(obj, function(x) { return (x % 2) !== 0; }); // {b: 2, d: 4} +``` + + + +## values(obj):Array + +Returns an array of all own enumerable properties values found upon a given object. + +PS: it won't return properties from the prototype. + +See: [`forOwn()`](#forOwn), [`keys()`](#keys) + +```js +var obj = { + foo : 1, + bar : 2, + lorem : 3 +}; +values(obj); // [1, 2, 3] +``` + + + +## set(obj, propName, value) + +Sets a nested property value. + +See: [`get()`](#get), [`namespace()`](#namespace) + +```js +var obj = {}; +set(obj, 'foo.bar', 123); +console.log(obj.foo.bar); // 123 +console.log(obj); // {foo:{bar:123}} +``` + + + +## size(obj):Number + +Returns the count of own enumerable properties found upon a given object. + +PS: it won't return properties from the prototype. + +See: [`forOwn()`](#forOwn), [`keys()`](#keys) + +```js +var obj = { + foo : 1, + bar : 2, + lorem : 3 +}; +size(obj); // 3 +``` + + + +## some(obj, callback, [thisObj]):Boolean + +Similar to [Array/some](array.html#some). Tests whether any properties in the +object pass the test implemented by the provided callback. + +```js +var obj = { + a: 1, + b: 2, + c: 3, + d: 'string' +}; + +some(obj, isNumber); // true +``` + + + +## unset(obj, propName):Boolean + +Delete object property if existent and returns a boolean indicating succes. It +will also return `true` if property doesn't exist. + +Some properties can't be deleted, to understand why [check this +article](http://perfectionkills.com/understanding-delete/). + +See: [`set()`](#set) + +```js +var lorem = { + ipsum : { + dolor : { + sit : 'amet' + } + } + }; + +unset(lorem, 'ipsum.dolor.sit'); // true +console.log(lorem.ipsum.dolor); // {} +unset(lorem, 'foo.bar'); // true +``` diff --git a/node_modules/express-error-handler/node_modules/mout/doc/queryString.md b/node_modules/express-error-handler/node_modules/mout/doc/queryString.md new file mode 100644 index 000000000..1be3c1026 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/queryString.md @@ -0,0 +1,115 @@ +# queryString # + +Utilities for query string manipulation. + + + +## contains(url, paramName):Boolen + +Checks if query string contains parameter. + +### Arguments: + + 1. `url` (String) : URL or query string. + 2. `paramName` (String) : Parameter name. + +### Example: + +```js +var url = 'example.com/?lorem=ipsum'; +contains(url, 'lorem'); // true +contains(url, 'foo'); //false +``` + + + +## decode(queryStr[, shouldTypecast]):Object + +Parses query string and creates an object of keys => vals. + +Will typecast value with [`string/typecast`](string.html#typecast) by default +and decode string parameters using `decodeURIComponent()`. + +```js +var query = '?foo=bar&lorem=123'; +decode(query); // {foo: "bar", lorem: 123} +decode(query, false); // {foo: "bar", lorem: "123"} +``` + + +## encode(obj):String + +Encode object into a query string. + +Will encode parameters with `encodeURIComponent()`. + +```js +encode({foo: "bar", lorem: 123}); // "?foo=bar&lorem=123" +``` + + +## getParam(url, param[, shouldTypecast]):* + +Get query parameter value. + +Will typecast value with [`string/typecast`](string.html#typecast) by default. + +See: [`setParam()`](#setParam) + +### Arguments: + + 1. `url` (String) : Url. + 2. `param` (String) : Parameter name. + 3. `[shouldTypecast]` (Boolean) : If it should typecast value. + +### Example: + +```js +var url = 'example.com/?foo=bar&lorem=123&ipsum=false'; +getParam(url, 'dolor'); // "amet" +getParam(url, 'lorem'); // 123 +getParam(url, 'lorem', false); // "123" +``` + + +## parse(url[, shouldTypecast]):Object + +Parses URL, extracts query string and decodes it. + +It will typecast all properties of the query object unless second argument is +`false`. + +Alias to: `decode(getQuery(url))`. + +```js +var url = 'example.com/?lorem=ipsum&a=123'; +parse(url); // {lorem: "ipsum", a: 123} +parse(url, false); // {lorem: "ipsum", a: "123"} +``` + + +## getQuery(url):String + +Gets full query as string with all special chars decoded. + +```js +getQuery('example.com/?lorem=ipsum'); // "?lorem=ipsum" +``` + + +## setParam(url, paramName, value):String + +Add new query string parameter to URL or update existing value. + +See: [`getParam()`](#getParam) + +```js +setParam('?foo=bar&lorem=0', 'lorem', 'ipsum'); // '?foo=bar&lorem=ipsum' +setParam('?lorem=1', 'foo', 123); // '?lorem=1&foo=123' +``` + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... diff --git a/node_modules/express-error-handler/node_modules/mout/doc/random.md b/node_modules/express-error-handler/node_modules/mout/doc/random.md new file mode 100644 index 000000000..b058b4e03 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/random.md @@ -0,0 +1,218 @@ +# random # + +Pseudo-random generators. + +mout uses `Math.random` by default on all the pseudo-random generators, if +you need a seeded random or a better algorithm see the [`random()`](#random) +documentation for instructions. + + + +## choice(...items):* + +Returns a random element from the supplied arguments or from an array if single +argument is an array. + +### Example: + +```js +choice(1, 2, 3, 4, 5); // 3 + +var arr = ['lorem', 'ipsum', 'dolor']; +choice(arr); // 'dolor' +``` + + + +## guid():String + +Generates a pseudo-random [Globally Unique Identifier](http://en.wikipedia.org/wiki/Globally_unique_identifier) (v4). + +Since the total number of GUIDs is 2122 the chance of generating the +same value twice is negligible. + +**Important:** this method uses `Math.random` by default so the UUID isn't +*safe* (sequence of outputs can be predicted in some cases), check the +[`random()`](#random) documentation for more info on how to replace the default +PRNG if you need extra safety or need *seeded* results. + +See: [`randHex()`](#randHex), [`random()`](#random) + +### Example: + +```js +guid(); // 830e9f50-ac7f-4369-a14f-ed0e62b2fa0b +guid(); // 5de3d09b-e79c-4727-932b-48c49228d508 +``` + + + +## rand([min], [max]):Number + +Gets a random number inside range or snap to min/max values. + +### Arguments: + + 1. `[min]` (Number) : Minimum value. Defaults to `number/MIN_INT`. + 2. `[max]` (Number) : Maximum value. Defaults to `number/MAX_INT`. + + +### Example: + +```js +rand(); // 448740433.55274725 +rand(); // -31797596.097682 +rand(0, 10); // 7.369723 +rand(0, 10); // 5.987042 +``` + +See: [`random()`](#random) + + + +## randBit():Number + +Returns a random "bit" (0 or 1). Useful for addition/subtraction. + +It's slightly faster than `choice(0, 1)` since implementation is simpler (not +that it will make a huge difference in most cases). + +See: [`choice()`](#choice) + +### Example: + +```js +randBit(); // 1 +randBit(); // 0 + +//same effect as +choice(0, 1); +``` + + + +## randHex([size]):String + +Returns a random hexadecimal string. + +The default `size` is `6`. + +### Example: + +```js +randHex(); // "dd8575" +randHex(); // "e6baeb" +randHex(2); // "a2" +randHex(30); // "effd7e2ad9a4a3067e30525fab983a" +``` + + + +## randInt([min], [max]):Number + +Gets a random integer inside range or snap to min/max values. + +### Arguments: + + 1. `[min]` (Number) : Minimum value. Defaults to `number/MIN_INT`. + 2. `[max]` (Number) : Maximum value. Defaults to `number/MAX_INT`. + + +### Example: + +```js +randInt(); // 448740433 +randInt(); // -31797596 +randInt(0, 10); // 7 +randInt(0, 10); // 5 +``` + + + +## randSign():Number + +Returns a random "sign" (-1 or 1). Useful for multiplications. + +It's slightly faster than `choice(-1, 1)` since implementation is simpler (not +that it will make a huge difference in most cases). + +See: [`choice()`](#choice) + +### Example: + +```js +randSign(); // -1 +randSign(); // 1 + +//same effect as +choice(-1, 1); +``` + + + +## random():Number + +Returns a random number between `0` and `1`. Same as `Math.random()`. + +```js +random(); // 0.35435103671625257 +random(); // 0.8768321881070733 +``` + +**Important:** No methods inside mout should call `Math.random()` +directly, they all use `random/random` as a proxy, that way we can +inject/replace the pseudo-random number generator if needed (ie. in case we +need a seeded random or a better algorithm than the native one). + +### Replacing the PRNG + +In some cases we might need better/different algorithms than the one provided +by `Math.random` (ie. safer, seeded). + +Because of licensing issues, file size limitations and different needs we +decided to **not** implement a custom PRNG and instead provide a easy way to +override the default behavior. - [issue #99](https://github.com/millermedeiros/amd-utils/issues/99) + +If you are using mout with a loader that supports the [AMD map +config](https://github.com/amdjs/amdjs-api/wiki/Common-Config), such as +[RequireJS](http://requirejs.org/), you can use it to replace the PRNG +(recommended approach): + +```js +requirejs.config({ + map : { + // all modules will load "my_custom_prng" instead of + // "mout/random/random" + '*' : { + 'mout/random/random' : 'my_custom_prng' + } + } +}); +``` + +You also have the option to override `random.get` in case you are using +mout on node.js or with a loader which doesn't support the map config: + +```js +// replace the PRNG +var n = 0; +random.get = function(){ + return ++n % 2? 0 : 1; // not so random :P +}; +random(); // 0 +random(); // 1 +random(); // 0 +random(); // 1 +``` + +See this [detailed explanation about PRNG in +JavaScript](http://baagoe.org/en/w/index.php/Better_random_numbers_for_javascript) +to understand the issues with the native `Math.random` and also for a list of +algorithms that could be used instead. + + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... diff --git a/node_modules/express-error-handler/node_modules/mout/doc/string.md b/node_modules/express-error-handler/node_modules/mout/doc/string.md new file mode 100644 index 000000000..04f61a76a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/string.md @@ -0,0 +1,606 @@ +# string # + +String utilities. + + +## camelCase(str):String + +Convert string to "camelCase" text. + +See: [`pascalCase()`](#pascalCase), [`unCamelCase()`](#unCamelCase) + +### Example + +```js +camelCase('lorem-ipsum-dolor'); // "loremIpsumDolor" +camelCase('lorem ipsum dolor'); // "loremIpsumDolor" +``` + + + +## contains(str, substring, [fromIndex]):Boolean + +Checks if string contains the given substring. + +See: [`startsWith()`](#startsWith), [`endsWith()`](#endsWith) + +### Example + +```js +contains('lorem', 'or'); // true +contains('lorem', 'bar'); // false +``` + + + +## crop(str, maxChars, [append]):String + +Truncate string at full words. Alias to `truncate(str, maxChars, append, true);`. + +See: [`truncate()`](#truncate) + +### Example + +```js +crop('lorem ipsum dolor', 10); // "lorem..." +crop('lorem ipsum dolor', 10, '+'); // "lorem+" +``` + + + +## endsWith(str, suffix):Boolean + +Checks if string ends with specified suffix. + +See: [`startsWith()`](#startsWith), [`contains()`](#contains) + +### Example + +```js +endsWith('lorem ipsum', 'lorem'); // false +endsWith('lorem ipsum', 'ipsum'); // true +``` + + + +## escapeHtml(str):String + +Escapes HTML special chars (`>`, `<`, `&`, `"`, `'`). + +See: [`unescapeHtml()`](#unescapeHtml) + +### Example + +```js +escapeHtml('lorem & "ipsum"'); // "lorem &amp; &quot;ipsum&quot;" +``` + + + +## escapeRegExp(str):String + +Escape special chars to be used as literals in RegExp constructors. + +### Example + +```js +str = escapeRegExp('[lorem.ipsum]'); // "\\[lorem\\.ipsum\\]" +reg = new RegExp(str); // /\[lorem\.ipsum\]/ +``` + + + +## escapeUnicode(str[, shouldEscapePrintable]):String + +Unicode escape chars. + +It will only escape non-printable ASCII chars unless `shouldEscapePrintable` is +set to `true`. + +See: [`unescapeUnicode()`](#unescapeUnicode) + +```js +escapeUnicode('føo bår'); +// > "f\u00f8o b\u00e5r" +escapeUnicode('føo bår', true); +// > "\u0066\u00f8\u006f\u0020\u0062\u00e5\u0072" +``` + + + +## hyphenate(str):String + +Replaces spaces with hyphens, split camelCase text, remove non-word chars, +remove accents and convert to lower case. + +See: [`slugify()`](#slugify), [`underscore()`](#underscore), +[`unhyphenate`](#unhyphenate) + +```js +hyphenate(' %# lorem ipsum ? $ dolor'); // "lorem-ipsum-dolor" +hyphenate('spéçïãl çhârs'); // "special-chars" +hyphenate('loremIpsum'); // "lorem-ipsum" +``` + + + +## insert(str, index, partial):String + +Inserts a `partial` before the given `index` in the provided `str`. +If the index is larger than the length of the string the partial is appended at the end. +A negative index is treated as `length - index` where `length` is the length or the string. + +```js +insert('this is a sentence', 10, 'sample '); // "this is a sample sentence" +insert('foo', 100, 'bar'); // "foobar" +insert('image.png', -4, '-large'); // "image-large.png" +``` + +## interpolate(str, replacements[, syntax]):String + +String interpolation. Format/replace tokens with object properties. + +```js +var tmpl = 'Hello {{name}}!'; +interpolate(tmpl, {name: 'World'}); // "Hello World!" +interpolate(tmpl, {name: 'Lorem Ipsum'}); // "Hello Lorem Ipsum!" +``` + +It uses a mustache-like syntax by default but you can set your own format if +needed. You can also use Arrays for the replacements (since Arrays are +objects as well): + +```js +// matches everything inside "${}" +var syntax = /\$\{([^}]+)\}/g; +var tmpl = "Hello ${0}!"; +interpolate(tmpl, ['Foo Bar'], syntax); // "Hello Foo Bar!" +``` + + + +## lowerCase(str):String + +"Safer" `String.toLowerCase()`. (Used internally) + +### Example + +```js +(null).toLowerCase(); // Error! +(undefined).toLowerCase(); // Error! +lowerCase(null); // "" +lowerCase(undefined); // "" +``` + + + +## lpad(str, minLength[, char]):String + +Pad string from left with `char` if its' length is smaller than `minLen`. + +See: [`rpad()`](#rpad) + +### Example + +```js +lpad('a', 5); // " a" +lpad('a', 5, '-'); // "----a" +lpad('abc', 3, '-'); // "abc" +lpad('abc', 4, '-'); // "-abc" +``` + + + +## ltrim(str, [chars]):String + +Remove chars or white-spaces from beginning of string. + +`chars` is an array of chars to remove from the beginning of the string. If +`chars` is not specified, Unicode whitespace chars will be used instead. + +See: [`rtrim()`](#rtrim), [`trim()`](#trim) + +### Example + +```js +ltrim(' lorem ipsum '); // "lorem ipsum " +ltrim('--lorem ipsum--', ['-']); // "lorem ipsum--" +``` + + + +## makePath(...args):String + +Group arguments as path segments, if any of the args is `null` or `undefined` +it will be ignored from resulting path. It will also remove duplicate "/". + +See: [`array/join()`](array.html#join) + +### Example + +```js +makePath('lorem', 'ipsum', null, 'dolor'); // "lorem/ipsum/dolor" +makePath('foo///bar/'); // "foo/bar/" +``` + + + +## normalizeLineBreaks(str, [lineBreak]):String + +Normalize line breaks to a single format. Defaults to Unix `\n`. + +It handles DOS (`\r\n`), Mac (`\r`) and Unix (`\n`) formats. + +### Example + +```js +// "foo\nbar\nlorem\nipsum" +normalizeLineBreaks('foo\nbar\r\nlorem\ripsum'); + +// "foo\rbar\rlorem\ripsum" +normalizeLineBreaks('foo\nbar\r\nlorem\ripsum', '\r'); + +// "foo bar lorem ipsum" +normalizeLineBreaks('foo\nbar\r\nlorem\ripsum', ' '); +``` + + + +## pascalCase(str):String + +Convert string to "PascalCase" text. + +See: [`camelCase()`](#camelCase) + +### Example + +```js +pascalCase('lorem-ipsum-dolor'); // "LoremIpsumDolor" +pascalCase('lorem ipsum dolor'); // "LoremIpsumDolor" +``` + + + +## properCase(str):String + +UPPERCASE first char of each word, lowercase other chars. + +### Example + +```js +properCase('loRem iPSum'); // "Lorem Ipsum" +``` + + + +## removeNonASCII(str):String + +Remove [non-printable ASCII +chars](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). + +### Example + +```js +removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // "lorem-ipsum" +``` + + + +## removeNonWord(str):String + +Remove non-word chars. + +### Example + +```js +var str = 'lorem ~!@#$%^&*()_+`-={}[]|\\:";\'/?><., ipsum'; +removeNonWord(str); // "lorem - ipsum" +``` + + + +## repeat(str, n):String + +Repeat string n-times. + +### Example + +```js +repeat('a', 3); // "aaa" +repeat('bc', 2); // "bcbc" +repeat('a', 0); // "" +``` + + + +## replace(str, search, replacements):String + +Replace string(s) with the replacement(s) in the source. + +`search` and `replacements` can be an array, or a single item. For every item +in `search`, it will call `str.replace` with the search item and the matching +replacement in `replacements`. If `replacements` only contains one replacement, +it will be used for all the searches, otherwise it will use the replacement at +the same index as the search. + +### Example + +```js +replace('foo bar', 'foo', 'test'); // "test bar" +replace('test 1 2', ['1', '2'], 'n'); // "test n n" +replace('test 1 2', ['1', '2'], ['one', 'two']); // "test one two" +replace('123abc', [/\d/g, /[a-z]/g], ['0', '.']); // "000..." +``` + + + +## replaceAccents(str):String + +Replaces all accented chars with regular ones. + +**Important:** Only covers **Basic Latin** and **Latin-1** unicode chars. + +### Example + +```js +replaceAccents('spéçïãl çhârs'); // "special chars" +``` + + + +## rpad(str, minLength[, char]):String + +Pad string from right with `char` if its' length is smaller than `minLen`. + +See: [`lpad()`](#lpad) + +### Example + +```js +rpad('a', 5); // "a " +rpad('a', 5, '-'); // "a----" +rpad('abc', 3, '-'); // "abc" +rpad('abc', 4, '-'); // "abc-" +``` + + + +## rtrim(str, [chars]):String + +Remove chars or white-spaces from end of string. + +`chars` is an array of chars to remove from the end of the string. If +`chars` is not specified, Unicode whitespace chars will be used instead. + +See: [`trim()`](#trim), [`ltrim()`](#ltrim) + +### Example + +```js +rtrim(' lorem ipsum '); // " lorem ipsum" +rtrim('--lorem ipsum--', ['-']); // "--lorem ipsum" +``` + + + +## sentenceCase(str):String + +UPPERCASE first char of each sentence and lowercase other chars. + +### Example + +```js +var str = 'Lorem IpSum DoLOr. maeCeNnas Ullamcor.'; +sentenceCase(str); // "Lorem ipsum dolor. Maecennas ullamcor." +``` + + + +## stripHtmlTags(str):String + +Remove HTML/XML tags from string. + +### Example + +```js +var str = '

lorem ipsum

'; +stripHtmlTags(str); // "lorem ipsum" +``` + + + +## startsWith(str, prefix):Boolean + +Checks if string starts with specified prefix. + +See: [`endsWith()`](#endsWith), [`contains()`](#contains) + +### Example + +```js +startsWith('lorem ipsum', 'lorem'); // true +startsWith('lorem ipsum', 'ipsum'); // false +``` + + + +## slugify(str[, delimeter]):String + +Convert to lower case, remove accents, remove non-word chars and replace spaces +with the delimeter. The default delimeter is a hyphen. + +Note that this does not split camelCase text. + +See: [`hyphenate()`](#hyphenate) and [`underscore()`](#underscore) + +### Example + +```js +var str = 'loremIpsum dolor spéçïãl chârs'; +slugify(str); // "loremipsum-dolor-special-chars" +slugify(str, '_'); // "loremipsum_dolor_special_chars" +``` + + + +## trim(str, [chars]):String + +Remove chars or white-spaces from beginning and end of string. + +`chars` is an array of chars to remove from the beginning and end of the +string. If `chars` is not specified, Unicode whitespace chars will be used +instead. + +See: [`rtrim()`](#rtrim), [`ltrim()`](#ltrim) + +### Example + +```js +trim(' lorem ipsum '); // "lorem ipsum" +trim('-+-lorem ipsum-+-', ['-', '+']); // "lorem ipsum" +``` + + + +## truncate(str, maxChars, [append], [onlyFullWords]):String + +Limit number of chars. Returned string `length` will be `<= maxChars`. + +See: [`crop()`](#crop) + +### Arguments + + 1. `str` (String) : String + 2. `maxChars` (Number) : Maximum number of characters including `append.length`. + 3. `[append]` (String) : Value that should be added to the end of string. + Defaults to "...". + 4. `[onlyFullWords]` (Boolean) : If it shouldn't break words. Default is + `false`. (favor [`crop()`](#crop) since code will be clearer). + +### Example + +```js +truncate('lorem ipsum dolor', 11); // "lorem ip..." +truncate('lorem ipsum dolor', 11, '+'); // "lorem ipsu+" +truncate('lorem ipsum dolor', 11, null, true); // "lorem..." +``` + + + +## typecast(str):* + +Parses string and convert it into a native value. + +### Example + +```js +typecast('lorem ipsum'); // "lorem ipsum" +typecast('123'); // 123 +typecast('123.45'); // 123.45 +typecast('false'); // false +typecast('true'); // true +typecast('null'); // null +typecast('undefined'); // undefined +``` + + + +## unCamelCase(str, [delimiter]):String + +Add the delimiter between camelCase text and convert first char of each word to +lower case. + +The delimiter defaults to a space character. + +See: [`camelCase()`][#camelCase] + +### Example + +```js +unCamelCase('loremIpsumDolor'); // "lorem ipsum dolor" +unCamelCase('loremIpsumDolor', '-'); // "lorem-ipsum-color" +``` + + +## underscore(str):String + +Replaces spaces with underscores, split camelCase text, remove non-word chars, +remove accents and convert to lower case. + +See: [`slugify()`](#slugify), [`hyphenate()`](#hyphenate) + +```js +underscore(' %# lorem ipsum ? $ dolor'); // "lorem_ipsum_dolor" +underscore('spéçïãl çhârs'); // "special_chars" +underscore('loremIpsum'); // "lorem_ipsum" +``` + + + +## unescapeHtml(str):String + +Unescapes HTML special chars (`>`, `<`, `&`, `"`, `'`). + +See: [`escapeHtml()`](#escapeHtml) + +### Example + +```js +unescapeHtml('lorem &amp; &quot;ipsum&quot;'); // 'lorem & "ipsum"' +``` + + + +## unescapeUnicode(str):String + +Unescapes unicode char sequences. + +See: [`escapeUnicode()`](#escapeUnicode) + +```js +unescapeUnicode('\\u0066\\u00f8\\u006f\\u0020\\u0062\\u00e5\\u0072'); +// > 'føo bår' +``` + + + +## unhyphenate(str):String + +Replaces hyphens with spaces. (only hyphens between word chars) + +See : [`hyphenate()`](#hyphenate) + +### Example + +```js +unhyphenate('lorem-ipsum-dolor'); // "lorem ipsum dolor" +``` + + +## upperCase(str):String + +"Safer" `String.toUpperCase()`. (Used internally) + +### Example + +```js +(null).toUpperCase(); // Error! +(undefined).toUpperCase(); // Error! +upperCase(null); // "" +upperCase(undefined); // "" +``` + + + +## WHITE_SPACES:Array + +Constant array of all [Unicode white-space +characters](http://en.wikipedia.org/wiki/Whitespace_character). + + + +------------------------------------------------------------------------------- + +For more usage examples check specs inside `/tests` folder. Unit tests are the +best documentation you can get... + diff --git a/node_modules/express-error-handler/node_modules/mout/doc/time.md b/node_modules/express-error-handler/node_modules/mout/doc/time.md new file mode 100644 index 000000000..628c2a9b6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/doc/time.md @@ -0,0 +1,64 @@ +# time # + +Utilities for time manipulation. + + +## convert(value, sourceUnit, [destinationUnit]):Number + +Converts time between units. + +Available units: `millisecond`, `second`, `minute`, `hour`, `day`, `week`. +Abbreviations: `ms`, `s`, `m`, `h`, `d`, `w`. + +We do **not** support year and month as a time unit since their values are not +fixed. + +The default `destinationUnit` is `ms`. + +```js +convert(1, 'minute'); // 60000 +convert(2.5, 's', 'ms'); // 2500 +convert(2, 'm', 's'); // 120 +convert(500, 'ms', 's'); // 0.5 +``` + + + +## now():Number + +Returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. +Uses `Date.now()` if available. + +### Example + +```js +now(); // 1335449614650 +``` + + + +## parseMs(ms):Object + +Parse timestamp (milliseconds) into an object `{milliseconds:number, +seconds:number, minutes:number, hours:number, days:number}`. + +### Example + +```js +// {days:27, hours:4, minutes:26, seconds:5, milliseconds:454} +parseMs(2348765454); +``` + + + +## toTimeString(ms):String + +Convert timestamp (milliseconds) into a time string in the format "[H:]MM:SS". + +### Example + +```js +toTimeString(12513); // "00:12" +toTimeString(951233); // "15:51" +toTimeString(8765235); // "2:26:05" +``` diff --git a/node_modules/express-error-handler/node_modules/mout/function.js b/node_modules/express-error-handler/node_modules/mout/function.js new file mode 100644 index 000000000..75d0c7e6f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function.js @@ -0,0 +1,19 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'bind' : require('./function/bind'), + 'compose' : require('./function/compose'), + 'debounce' : require('./function/debounce'), + 'func' : require('./function/func'), + 'makeIterator_' : require('./function/makeIterator_'), + 'partial' : require('./function/partial'), + 'prop' : require('./function/prop'), + 'series' : require('./function/series'), + 'throttle' : require('./function/throttle'), + 'timeout' : require('./function/timeout'), + 'times' : require('./function/times') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/bind.js b/node_modules/express-error-handler/node_modules/mout/function/bind.js new file mode 100644 index 000000000..71bc12576 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/bind.js @@ -0,0 +1,23 @@ + + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Return a function that will execute in the given context, optionally adding any additional supplied parameters to the beginning of the arguments collection. + * @param {Function} fn Function. + * @param {object} context Execution context. + * @param {rest} args Arguments (0...n arguments). + * @return {Function} Wrapped Function. + */ + function bind(fn, context, args){ + var argsArr = slice(arguments, 2); //curried args + return function(){ + return fn.apply(context, argsArr.concat(slice(arguments))); + }; + } + + module.exports = bind; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/compose.js b/node_modules/express-error-handler/node_modules/mout/function/compose.js new file mode 100644 index 000000000..8cd5c5f36 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/compose.js @@ -0,0 +1,23 @@ + + + /** + * Returns a function that composes multiple functions, passing results to + * each other. + */ + function compose() { + var fns = arguments; + return function(arg){ + // only cares about the first argument since the chain can only + // deal with a single return value anyway. It should start from + // the last fn. + var n = fns.length; + while (n--) { + arg = fns[n].call(this, arg); + } + return arg; + }; + } + + module.exports = compose; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/debounce.js b/node_modules/express-error-handler/node_modules/mout/function/debounce.js new file mode 100644 index 000000000..7f6f30210 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/debounce.js @@ -0,0 +1,32 @@ + + + /** + * Debounce callback execution + */ + function debounce(fn, threshold, isAsap){ + var timeout, result; + function debounced(){ + var args = arguments, context = this; + function delayed(){ + if (! isAsap) { + result = fn.apply(context, args); + } + timeout = null; + } + if (timeout) { + clearTimeout(timeout); + } else if (isAsap) { + result = fn.apply(context, args); + } + timeout = setTimeout(delayed, threshold); + return result; + } + debounced.cancel = function(){ + clearTimeout(timeout); + }; + return debounced; + } + + module.exports = debounce; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/func.js b/node_modules/express-error-handler/node_modules/mout/function/func.js new file mode 100644 index 000000000..b81bf0a83 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/func.js @@ -0,0 +1,14 @@ + + + /** + * Returns a function that call a method on the passed object + */ + function func(name){ + return function(obj){ + return obj[name](); + }; + } + + module.exports = func; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/makeIterator_.js b/node_modules/express-error-handler/node_modules/mout/function/makeIterator_.js new file mode 100644 index 000000000..b6e6a00e3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/makeIterator_.js @@ -0,0 +1,31 @@ +var prop = require('./prop'); +var deepMatches = require('../object/deepMatches'); + + /** + * Converts argument into a valid iterator. + * Used internally on most array/object/collection methods that receives a + * callback/iterator providing a shortcut syntax. + */ + function makeIterator(src, thisObj){ + switch(typeof src) { + case 'function': + // function is the first to improve perf (most common case) + return (typeof thisObj !== 'undefined')? function(val, i, arr){ + return src.call(thisObj, val, i, arr); + } : src; + case 'object': + // typeof null == "object" + return (src != null)? function(val){ + return deepMatches(val, src); + } : src; + case 'string': + case 'number': + return prop(src); + default: + return src; + } + } + + module.exports = makeIterator; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/partial.js b/node_modules/express-error-handler/node_modules/mout/function/partial.js new file mode 100644 index 000000000..d63ff1bee --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/partial.js @@ -0,0 +1,19 @@ + + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Creates a partially applied function. + */ + function partial(fn, var_args){ + var argsArr = slice(arguments, 1); //curried args + return function(){ + return fn.apply(this, argsArr.concat(slice(arguments))); + }; + } + + module.exports = partial; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/prop.js b/node_modules/express-error-handler/node_modules/mout/function/prop.js new file mode 100644 index 000000000..734acb7a8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/prop.js @@ -0,0 +1,14 @@ + + + /** + * Returns a function that gets a property of the passed object + */ + function prop(name){ + return function(obj){ + return obj[name]; + }; + } + + module.exports = prop; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/series.js b/node_modules/express-error-handler/node_modules/mout/function/series.js new file mode 100644 index 000000000..25159c2cd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/series.js @@ -0,0 +1,22 @@ + + + /** + * Returns a function that will execute a list of functions in sequence + * passing the same arguments to each one. (useful for batch processing + * items during a forEach loop) + */ + function series(){ + var fns = arguments; + return function(){ + var i = 0, + n = fns.length; + while (i < n) { + fns[i].apply(this, arguments); + i += 1; + } + }; + } + + module.exports = series; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/throttle.js b/node_modules/express-error-handler/node_modules/mout/function/throttle.js new file mode 100644 index 000000000..10bdc1f01 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/throttle.js @@ -0,0 +1,35 @@ +var now = require('../time/now'); + + /** + */ + function throttle(fn, delay){ + var context, timeout, result, args, + cur, diff, prev = 0; + function delayed(){ + prev = now(); + timeout = null; + result = fn.apply(context, args); + } + function throttled(){ + context = this; + args = arguments; + cur = now(); + diff = delay - (cur - prev); + if (diff <= 0) { + clearTimeout(timeout); + prev = cur; + result = fn.apply(context, args); + } else if (! timeout) { + timeout = setTimeout(delayed, diff); + } + return result; + } + throttled.cancel = function(){ + clearTimeout(timeout); + }; + return throttled; + } + + module.exports = throttle; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/timeout.js b/node_modules/express-error-handler/node_modules/mout/function/timeout.js new file mode 100644 index 000000000..e0d21a66d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/timeout.js @@ -0,0 +1,21 @@ + + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Delays the call of a function within a given context. + */ + function timeout(fn, millis, context){ + + var args = slice(arguments, 3); + + return setTimeout(function() { + fn.apply(context, args); + }, millis); + } + + module.exports = timeout; + + diff --git a/node_modules/express-error-handler/node_modules/mout/function/times.js b/node_modules/express-error-handler/node_modules/mout/function/times.js new file mode 100644 index 000000000..04a11c264 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/function/times.js @@ -0,0 +1,17 @@ + + + /** + * Iterates over a callback a set amount of times + */ + function times(n, callback, thisObj){ + var i = -1; + while (++i < n) { + if ( callback.call(thisObj, i) === false ) { + break; + } + } + } + + module.exports = times; + + diff --git a/node_modules/express-error-handler/node_modules/mout/index.js b/node_modules/express-error-handler/node_modules/mout/index.js new file mode 100644 index 000000000..5016d085a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/index.js @@ -0,0 +1,25 @@ +/**@license + * mout v0.7.1 | http://moutjs.com | MIT license + */ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'VERSION' : '0.7.1', + 'array' : require('./array'), + 'collection' : require('./collection'), + 'date' : require('./date'), + 'function' : require('./function'), + 'lang' : require('./lang'), + 'math' : require('./math'), + 'number' : require('./number'), + 'object' : require('./object'), + 'queryString' : require('./queryString'), + 'random' : require('./random'), + 'string' : require('./string'), + 'time' : require('./time'), + 'fn' : require('./function') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang.js b/node_modules/express-error-handler/node_modules/mout/lang.js new file mode 100644 index 000000000..024f7fa58 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang.js @@ -0,0 +1,37 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'clone' : require('./lang/clone'), + 'createObject' : require('./lang/createObject'), + 'ctorApply' : require('./lang/ctorApply'), + 'deepClone' : require('./lang/deepClone'), + 'defaults' : require('./lang/defaults'), + 'inheritPrototype' : require('./lang/inheritPrototype'), + 'is' : require('./lang/is'), + 'isArguments' : require('./lang/isArguments'), + 'isArray' : require('./lang/isArray'), + 'isBoolean' : require('./lang/isBoolean'), + 'isDate' : require('./lang/isDate'), + 'isEmpty' : require('./lang/isEmpty'), + 'isFinite' : require('./lang/isFinite'), + 'isFunction' : require('./lang/isFunction'), + 'isInteger' : require('./lang/isInteger'), + 'isKind' : require('./lang/isKind'), + 'isNaN' : require('./lang/isNaN'), + 'isNull' : require('./lang/isNull'), + 'isNumber' : require('./lang/isNumber'), + 'isObject' : require('./lang/isObject'), + 'isPlainObject' : require('./lang/isPlainObject'), + 'isRegExp' : require('./lang/isRegExp'), + 'isString' : require('./lang/isString'), + 'isUndefined' : require('./lang/isUndefined'), + 'isnt' : require('./lang/isnt'), + 'kindOf' : require('./lang/kindOf'), + 'toArray' : require('./lang/toArray'), + 'toNumber' : require('./lang/toNumber'), + 'toString' : require('./lang/toString') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/clone.js b/node_modules/express-error-handler/node_modules/mout/lang/clone.js new file mode 100644 index 000000000..33c4e949d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/clone.js @@ -0,0 +1,49 @@ +var kindOf = require('./kindOf'); +var isPlainObject = require('./isPlainObject'); +var mixIn = require('../object/mixIn'); + + /** + * Clone native types. + */ + function clone(val){ + switch (kindOf(val)) { + case 'Object': + return cloneObject(val); + case 'Array': + return cloneArray(val); + case 'RegExp': + return cloneRegExp(val); + case 'Date': + return cloneDate(val); + default: + return val; + } + } + + function cloneObject(source) { + if (isPlainObject(source)) { + return mixIn({}, source); + } else { + return source; + } + } + + function cloneRegExp(r) { + var flags = ''; + flags += r.multiline ? 'm' : ''; + flags += r.global ? 'g' : ''; + flags += r.ignorecase ? 'i' : ''; + return new RegExp(r.source, flags); + } + + function cloneDate(date) { + return new Date(+date); + } + + function cloneArray(arr) { + return arr.slice(); + } + + module.exports = clone; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/createObject.js b/node_modules/express-error-handler/node_modules/mout/lang/createObject.js new file mode 100644 index 000000000..bbc14c1df --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/createObject.js @@ -0,0 +1,18 @@ +var mixIn = require('../object/mixIn'); + + /** + * Create Object using prototypal inheritance and setting custom properties. + * - Mix between Douglas Crockford Prototypal Inheritance and the EcmaScript 5 `Object.create()` method. + * @param {object} parent Parent Object. + * @param {object} [props] Object properties. + * @return {object} Created object. + */ + function createObject(parent, props){ + function F(){} + F.prototype = parent; + return mixIn(new F(), props); + + } + module.exports = createObject; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/ctorApply.js b/node_modules/express-error-handler/node_modules/mout/lang/ctorApply.js new file mode 100644 index 000000000..d68dc5065 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/ctorApply.js @@ -0,0 +1,17 @@ + + + function F(){} + + /** + * Do fn.apply on a constructor. + */ + function ctorApply(ctor, args) { + F.prototype = ctor.prototype; + var instance = new F(); + ctor.apply(instance, args); + return instance; + } + + module.exports = ctorApply; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/deepClone.js b/node_modules/express-error-handler/node_modules/mout/lang/deepClone.js new file mode 100644 index 000000000..25fd95f14 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/deepClone.js @@ -0,0 +1,48 @@ +var clone = require('./clone'); +var forOwn = require('../object/forOwn'); +var kindOf = require('./kindOf'); +var isPlainObject = require('./isPlainObject'); + + /** + * Recursively clone native types. + */ + function deepClone(val, instanceClone) { + switch ( kindOf(val) ) { + case 'Object': + return cloneObject(val, instanceClone); + case 'Array': + return cloneArray(val, instanceClone); + default: + return clone(val); + } + } + + function cloneObject(source, instanceClone) { + if (isPlainObject(source)) { + var out = {}; + forOwn(source, function(val, key) { + this[key] = deepClone(val, instanceClone); + }, out); + return out; + } else if (instanceClone) { + return instanceClone(source); + } else { + return source; + } + } + + function cloneArray(arr, instanceClone) { + var out = [], + i = -1, + n = arr.length, + val; + while (++i < n) { + out[i] = deepClone(arr[i], instanceClone); + } + return out; + } + + module.exports = deepClone; + + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/defaults.js b/node_modules/express-error-handler/node_modules/mout/lang/defaults.js new file mode 100644 index 000000000..1111b2efa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/defaults.js @@ -0,0 +1,17 @@ +var toArray = require('./toArray'); +var find = require('../array/find'); + + /** + * Return first non void argument + */ + function defaults(var_args){ + return find(toArray(arguments), nonVoid); + } + + function nonVoid(val){ + return val != null; + } + + module.exports = defaults; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/inheritPrototype.js b/node_modules/express-error-handler/node_modules/mout/lang/inheritPrototype.js new file mode 100644 index 000000000..eb17b9cad --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/inheritPrototype.js @@ -0,0 +1,17 @@ +var createObject = require('./createObject'); + + /** + * Inherit prototype from another Object. + * - inspired by Nicholas Zackas Solution + * @param {object} child Child object + * @param {object} parent Parent Object + */ + function inheritPrototype(child, parent){ + var p = createObject(parent.prototype); + p.constructor = child; + child.prototype = p; + child.super_ = parent; + } + + module.exports = inheritPrototype; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/is.js b/node_modules/express-error-handler/node_modules/mout/lang/is.js new file mode 100644 index 000000000..4a8357396 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/is.js @@ -0,0 +1,23 @@ + + + /** + * Check if both arguments are egal. + */ + function is(x, y){ + // implementation borrowed from harmony:egal spec + if (x === y) { + // 0 === -0, but they are not identical + return x !== 0 || 1 / x === 1 / y; + } + + // NaN !== NaN, but they are identical. + // NaNs are the only non-reflexive value, i.e., if x !== x, + // then x is a NaN. + // isNaN is broken: it converts its argument to number, so + // isNaN("foo") => true + return x !== x && y !== y; + } + + module.exports = is; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isArguments.js b/node_modules/express-error-handler/node_modules/mout/lang/isArguments.js new file mode 100644 index 000000000..f7b08ba44 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isArguments.js @@ -0,0 +1,15 @@ +var isKind = require('./isKind'); + + /** + */ + var isArgs = isKind(arguments, 'Arguments')? + function(val){ + return isKind(val, 'Arguments'); + } : + function(val){ + // Arguments is an Object on IE7 + return !!(val && Object.prototype.hasOwnProperty.call(val, 'callee')); + }; + + module.exports = isArgs; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isArray.js b/node_modules/express-error-handler/node_modules/mout/lang/isArray.js new file mode 100644 index 000000000..262ee4007 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isArray.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + var isArray = Array.isArray || function (val) { + return isKind(val, 'Array'); + }; + module.exports = isArray; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isBoolean.js b/node_modules/express-error-handler/node_modules/mout/lang/isBoolean.js new file mode 100644 index 000000000..86557cb94 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isBoolean.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isBoolean(val) { + return isKind(val, 'Boolean'); + } + module.exports = isBoolean; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isDate.js b/node_modules/express-error-handler/node_modules/mout/lang/isDate.js new file mode 100644 index 000000000..4a5130f2c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isDate.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isDate(val) { + return isKind(val, 'Date'); + } + module.exports = isDate; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isEmpty.js b/node_modules/express-error-handler/node_modules/mout/lang/isEmpty.js new file mode 100644 index 000000000..0e9f77da2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isEmpty.js @@ -0,0 +1,24 @@ +var forOwn = require('../object/forOwn'); +var isArray = require('./isArray'); + + function isEmpty(val){ + if (val == null) { + // typeof null == 'object' so we check it first + return false; + } else if ( typeof val === 'string' || isArray(val) ) { + return !val.length; + } else if ( typeof val === 'object' || typeof val === 'function' ) { + var result = true; + forOwn(val, function(){ + result = false; + return false; // break loop + }); + return result; + } else { + return false; + } + } + + module.exports = isEmpty; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isFinite.js b/node_modules/express-error-handler/node_modules/mout/lang/isFinite.js new file mode 100644 index 000000000..6d4006f99 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isFinite.js @@ -0,0 +1,21 @@ +var isNumber = require('./isNumber'); + + var global = this; + + /** + * Check if value is finite + */ + function isFinite(val){ + var is = false; + if (typeof val === 'string' && val !== '') { + is = global.isFinite( parseFloat(val) ); + } else if (isNumber(val)){ + // need to use isNumber because of Number constructor + is = global.isFinite( val ); + } + return is; + } + + module.exports = isFinite; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isFunction.js b/node_modules/express-error-handler/node_modules/mout/lang/isFunction.js new file mode 100644 index 000000000..216879f65 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isFunction.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isFunction(val) { + return isKind(val, 'Function'); + } + module.exports = isFunction; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isInteger.js b/node_modules/express-error-handler/node_modules/mout/lang/isInteger.js new file mode 100644 index 000000000..29f95d96c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isInteger.js @@ -0,0 +1,12 @@ +var isNumber = require('./isNumber'); + + /** + * Check if value is an integer + */ + function isInteger(val){ + return isNumber(val) && (val % 1 === 0); + } + + module.exports = isInteger; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isKind.js b/node_modules/express-error-handler/node_modules/mout/lang/isKind.js new file mode 100644 index 000000000..02301e049 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isKind.js @@ -0,0 +1,9 @@ +var kindOf = require('./kindOf'); + /** + * Check if value is from a specific "kind". + */ + function isKind(val, kind){ + return kindOf(val) === kind; + } + module.exports = isKind; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isNaN.js b/node_modules/express-error-handler/node_modules/mout/lang/isNaN.js new file mode 100644 index 000000000..4ea3065d7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isNaN.js @@ -0,0 +1,16 @@ +var isNumber = require('./isNumber'); + + /** + * Check if value is NaN for realz + */ + function isNaN(val){ + // based on the fact that NaN !== NaN + // need to check if it's a number to avoid conflicts with host objects + // also need to coerce ToNumber to avoid edge case `new Number(NaN)` + // jshint eqeqeq: false + return !isNumber(val) || val != +val; + } + + module.exports = isNaN; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isNull.js b/node_modules/express-error-handler/node_modules/mout/lang/isNull.js new file mode 100644 index 000000000..6252f9ef6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isNull.js @@ -0,0 +1,9 @@ + + /** + */ + function isNull(val){ + return val === null; + } + module.exports = isNull; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isNumber.js b/node_modules/express-error-handler/node_modules/mout/lang/isNumber.js new file mode 100644 index 000000000..126c1cce8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isNumber.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isNumber(val) { + return isKind(val, 'Number'); + } + module.exports = isNumber; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isObject.js b/node_modules/express-error-handler/node_modules/mout/lang/isObject.js new file mode 100644 index 000000000..7350c8918 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isObject.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isObject(val) { + return isKind(val, 'Object'); + } + module.exports = isObject; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isPlainObject.js b/node_modules/express-error-handler/node_modules/mout/lang/isPlainObject.js new file mode 100644 index 000000000..b81342eee --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isPlainObject.js @@ -0,0 +1,13 @@ + + + /** + * Checks if the value is created by the `Object` constructor. + */ + function isPlainObject(value) { + return (!!value && typeof value === 'object' && + value.constructor === Object); + } + + module.exports = isPlainObject; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isRegExp.js b/node_modules/express-error-handler/node_modules/mout/lang/isRegExp.js new file mode 100644 index 000000000..fc5459a9d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isRegExp.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isRegExp(val) { + return isKind(val, 'RegExp'); + } + module.exports = isRegExp; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isString.js b/node_modules/express-error-handler/node_modules/mout/lang/isString.js new file mode 100644 index 000000000..f89065844 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isString.js @@ -0,0 +1,8 @@ +var isKind = require('./isKind'); + /** + */ + function isString(val) { + return isKind(val, 'String'); + } + module.exports = isString; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isUndefined.js b/node_modules/express-error-handler/node_modules/mout/lang/isUndefined.js new file mode 100644 index 000000000..fb2261df3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isUndefined.js @@ -0,0 +1,10 @@ + + var UNDEF; + + /** + */ + function isUndef(val){ + return val === UNDEF; + } + module.exports = isUndef; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/isnt.js b/node_modules/express-error-handler/node_modules/mout/lang/isnt.js new file mode 100644 index 000000000..9dad58ce0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/isnt.js @@ -0,0 +1,12 @@ +var is = require('./is'); + + /** + * Check if both values are not identical/egal + */ + function isnt(x, y){ + return !is(x, y); + } + + module.exports = isnt; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/kindOf.js b/node_modules/express-error-handler/node_modules/mout/lang/kindOf.js new file mode 100644 index 000000000..663464d09 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/kindOf.js @@ -0,0 +1,20 @@ + + + var _rKind = /^\[object (.*)\]$/, + _toString = Object.prototype.toString, + UNDEF; + + /** + * Gets the "kind" of value. (e.g. "String", "Number", etc) + */ + function kindOf(val) { + if (val === null) { + return 'Null'; + } else if (val === UNDEF) { + return 'Undefined'; + } else { + return _rKind.exec( _toString.call(val) )[1]; + } + } + module.exports = kindOf; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/toArray.js b/node_modules/express-error-handler/node_modules/mout/lang/toArray.js new file mode 100644 index 000000000..e39b8734f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/toArray.js @@ -0,0 +1,31 @@ +var kindOf = require('./kindOf'); + + var _win = this; + + /** + * Convert array-like object into array + */ + function toArray(val){ + var ret = [], + kind = kindOf(val), + n; + + if (val != null) { + if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) { + //string, regexp, function have .length but user probably just want + //to wrap value into an array.. + ret[ret.length] = val; + } else { + //window returns true on isObject in IE7 and may have length + //property. `typeof NodeList` returns `function` on Safari so + //we can't use it (#58) + n = val.length; + while (n--) { + ret[n] = val[n]; + } + } + } + return ret; + } + module.exports = toArray; + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/toNumber.js b/node_modules/express-error-handler/node_modules/mout/lang/toNumber.js new file mode 100644 index 000000000..8b6df3444 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/toNumber.js @@ -0,0 +1,20 @@ +var isArray = require('./isArray'); + + /** + * covert value into number if numeric + */ + function toNumber(val){ + // numberic values should come first because of -0 + if (typeof val === 'number') return val; + // we want all falsy values (besides -0) to return zero to avoid + // headaches + if (!val) return 0; + if (typeof val === 'string') return parseFloat(val); + // arrays are edge cases. `Number([4]) === 4` + if (isArray(val)) return NaN; + return Number(val); + } + + module.exports = toNumber; + + diff --git a/node_modules/express-error-handler/node_modules/mout/lang/toString.js b/node_modules/express-error-handler/node_modules/mout/lang/toString.js new file mode 100644 index 000000000..ae5c2b0f3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/lang/toString.js @@ -0,0 +1,13 @@ + + + /** + * Typecast a value to a String, using an empty string value for null or + * undefined. + */ + function toString(val){ + return val == null ? '' : val.toString(); + } + + module.exports = toString; + + diff --git a/node_modules/express-error-handler/node_modules/mout/math.js b/node_modules/express-error-handler/node_modules/mout/math.js new file mode 100644 index 000000000..c6ee889b6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math.js @@ -0,0 +1,19 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'ceil' : require('./math/ceil'), + 'clamp' : require('./math/clamp'), + 'countSteps' : require('./math/countSteps'), + 'floor' : require('./math/floor'), + 'inRange' : require('./math/inRange'), + 'isNear' : require('./math/isNear'), + 'lerp' : require('./math/lerp'), + 'loop' : require('./math/loop'), + 'map' : require('./math/map'), + 'norm' : require('./math/norm'), + 'round' : require('./math/round') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/math/ceil.js b/node_modules/express-error-handler/node_modules/mout/math/ceil.js new file mode 100644 index 000000000..a279e1586 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/ceil.js @@ -0,0 +1,11 @@ + + /** + * Round value up with a custom radix. + */ + function ceil(val, step){ + step = Math.abs(step || 1); + return Math.ceil(val / step) * step; + } + + module.exports = ceil; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/clamp.js b/node_modules/express-error-handler/node_modules/mout/math/clamp.js new file mode 100644 index 000000000..e929a9a66 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/clamp.js @@ -0,0 +1,9 @@ + + /** + * Clamps value inside range. + */ + function clamp(val, min, max){ + return val < min? min : (val > max? max : val); + } + module.exports = clamp; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/countSteps.js b/node_modules/express-error-handler/node_modules/mout/math/countSteps.js new file mode 100644 index 000000000..60ac90c32 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/countSteps.js @@ -0,0 +1,16 @@ + + /** + * Count number of full steps. + */ + function countSteps(val, step, overflow){ + val = Math.floor(val / step); + + if (overflow) { + return val % overflow; + } + + return val; + } + + module.exports = countSteps; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/floor.js b/node_modules/express-error-handler/node_modules/mout/math/floor.js new file mode 100644 index 000000000..9de505317 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/floor.js @@ -0,0 +1,10 @@ + + /** + * Floor value to full steps. + */ + function floor(val, step){ + step = Math.abs(step || 1); + return Math.floor(val / step) * step; + } + module.exports = floor; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/inRange.js b/node_modules/express-error-handler/node_modules/mout/math/inRange.js new file mode 100644 index 000000000..763218f80 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/inRange.js @@ -0,0 +1,11 @@ + + /** + * Checks if value is inside the range. + */ + function inRange(val, min, max, threshold){ + threshold = threshold || 0; + return (val + threshold >= min && val - threshold <= max); + } + + module.exports = inRange; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/isNear.js b/node_modules/express-error-handler/node_modules/mout/math/isNear.js new file mode 100644 index 000000000..45486b6d6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/isNear.js @@ -0,0 +1,9 @@ + + /** + * Check if value is close to target. + */ + function isNear(val, target, threshold){ + return (Math.abs(val - target) <= threshold); + } + module.exports = isNear; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/lerp.js b/node_modules/express-error-handler/node_modules/mout/math/lerp.js new file mode 100644 index 000000000..111e2717d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/lerp.js @@ -0,0 +1,11 @@ + + /** + * Linear interpolation. + * IMPORTANT:will return `Infinity` if numbers overflow Number.MAX_VALUE + */ + function lerp(ratio, start, end){ + return start + (end - start) * ratio; + } + + module.exports = lerp; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/loop.js b/node_modules/express-error-handler/node_modules/mout/math/loop.js new file mode 100644 index 000000000..35207c1ae --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/loop.js @@ -0,0 +1,10 @@ + + /** + * Loops value inside range. + */ + function loop(val, min, max){ + return val < min? max : (val > max? min : val); + } + + module.exports = loop; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/map.js b/node_modules/express-error-handler/node_modules/mout/math/map.js new file mode 100644 index 000000000..96c4b787d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/map.js @@ -0,0 +1,11 @@ +var lerp = require('./lerp'); +var norm = require('./norm'); + /** + * Maps a number from one scale to another. + * @example map(3, 0, 4, -1, 1) -> 0.5 + */ + function map(val, min1, max1, min2, max2){ + return lerp( norm(val, min1, max1), min2, max2 ); + } + module.exports = map; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/norm.js b/node_modules/express-error-handler/node_modules/mout/math/norm.js new file mode 100644 index 000000000..54caf78a4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/norm.js @@ -0,0 +1,9 @@ + + /** + * Gets normalized ratio of value inside range. + */ + function norm(val, min, max){ + return (val - min) / (max - min); + } + module.exports = norm; + diff --git a/node_modules/express-error-handler/node_modules/mout/math/round.js b/node_modules/express-error-handler/node_modules/mout/math/round.js new file mode 100644 index 000000000..d108e6cdd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/math/round.js @@ -0,0 +1,12 @@ + + /** + * Round number to a specific radix + */ + function round(value, radix){ + radix = radix || 1; // default round 1 + return Math.round(value / radix) * radix; + } + + module.exports = round; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number.js b/node_modules/express-error-handler/node_modules/mout/number.js new file mode 100644 index 000000000..0b6186cb5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number.js @@ -0,0 +1,21 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'MAX_INT' : require('./number/MAX_INT'), + 'MAX_UINT' : require('./number/MAX_UINT'), + 'MIN_INT' : require('./number/MIN_INT'), + 'abbreviate' : require('./number/abbreviate'), + 'currencyFormat' : require('./number/currencyFormat'), + 'enforcePrecision' : require('./number/enforcePrecision'), + 'pad' : require('./number/pad'), + 'rol' : require('./number/rol'), + 'ror' : require('./number/ror'), + 'sign' : require('./number/sign'), + 'toInt' : require('./number/toInt'), + 'toUInt' : require('./number/toUInt'), + 'toUInt31' : require('./number/toUInt31') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/MAX_INT.js b/node_modules/express-error-handler/node_modules/mout/number/MAX_INT.js new file mode 100644 index 000000000..1d6f0e48f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/MAX_INT.js @@ -0,0 +1,6 @@ +/** + * @constant Maximum 32-bit signed integer value. (2^31 - 1) + */ + + module.exports = 2147483647; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/MAX_UINT.js b/node_modules/express-error-handler/node_modules/mout/number/MAX_UINT.js new file mode 100644 index 000000000..700da0f6f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/MAX_UINT.js @@ -0,0 +1,6 @@ +/** + * @constant Maximum 32-bit unsigned integet value (2^32 - 1) + */ + + module.exports = 4294967295; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/MIN_INT.js b/node_modules/express-error-handler/node_modules/mout/number/MIN_INT.js new file mode 100644 index 000000000..b34ab2cea --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/MIN_INT.js @@ -0,0 +1,6 @@ +/** + * @constant Minimum 32-bit signed integer value (-2^31). + */ + + module.exports = -2147483648; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/abbreviate.js b/node_modules/express-error-handler/node_modules/mout/number/abbreviate.js new file mode 100644 index 000000000..dd6716b9a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/abbreviate.js @@ -0,0 +1,35 @@ +var enforcePrecision = require('./enforcePrecision'); + + var _defaultDict = { + thousand : 'K', + million : 'M', + billion : 'B' + }; + + /** + * Abbreviate number if bigger than 1000. (eg: 2.5K, 17.5M, 3.4B, ...) + */ + function abbreviateNumber(val, nDecimals, dict){ + nDecimals = nDecimals != null? nDecimals : 1; + dict = dict || _defaultDict; + val = enforcePrecision(val, nDecimals); + + var str, mod; + + if (val < 1000000) { + mod = enforcePrecision(val / 1000, nDecimals); + // might overflow to next scale during rounding + str = mod < 1000? mod + dict.thousand : 1 + dict.million; + } else if (val < 1000000000) { + mod = enforcePrecision(val / 1000000, nDecimals); + str = mod < 1000? mod + dict.million : 1 + dict.billion; + } else { + str = enforcePrecision(val / 1000000000, nDecimals) + dict.billion; + } + + return str; + } + + module.exports = abbreviateNumber; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/currencyFormat.js b/node_modules/express-error-handler/node_modules/mout/number/currencyFormat.js new file mode 100644 index 000000000..c85a66854 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/currencyFormat.js @@ -0,0 +1,27 @@ +var toNumber = require('../lang/toNumber'); + + /** + * Converts number into currency format + */ + function currencyFormat(val, nDecimalDigits, decimalSeparator, thousandsSeparator) { + val = toNumber(val); + nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits; + decimalSeparator = decimalSeparator == null? '.' : decimalSeparator; + thousandsSeparator = thousandsSeparator == null? ',' : thousandsSeparator; + + //can't use enforce precision since it returns a number and we are + //doing a RegExp over the string + var fixed = val.toFixed(nDecimalDigits), + //separate begin [$1], middle [$2] and decimal digits [$4] + parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); + + if(parts){ //val >= 1000 || val <= -1000 + return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : ''); + }else{ + return fixed.replace('.', decimalSeparator); + } + } + + module.exports = currencyFormat; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/enforcePrecision.js b/node_modules/express-error-handler/node_modules/mout/number/enforcePrecision.js new file mode 100644 index 000000000..3d3b2d409 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/enforcePrecision.js @@ -0,0 +1,12 @@ +var toNumber = require('../lang/toNumber'); + /** + * Enforce a specific amount of decimal digits and also fix floating + * point rounding issues. + */ + function enforcePrecision(val, nDecimalDigits){ + val = toNumber(val); + var pow = Math.pow(10, nDecimalDigits); + return +(Math.round(val * pow) / pow).toFixed(nDecimalDigits); + } + module.exports = enforcePrecision; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/pad.js b/node_modules/express-error-handler/node_modules/mout/number/pad.js new file mode 100644 index 000000000..1f83af45b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/pad.js @@ -0,0 +1,14 @@ +var lpad = require('../string/lpad'); +var toNumber = require('../lang/toNumber'); + + /** + * Add padding zeros if n.length < minLength. + */ + function pad(n, minLength, char){ + n = toNumber(n); + return lpad(''+ n, minLength, char || '0'); + } + + module.exports = pad; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/rol.js b/node_modules/express-error-handler/node_modules/mout/number/rol.js new file mode 100644 index 000000000..ecd58da47 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/rol.js @@ -0,0 +1,10 @@ + + /** + * Bitwise circular shift left + * http://en.wikipedia.org/wiki/Circular_shift + */ + function rol(val, shift){ + return (val << shift) | (val >> (32 - shift)); + } + module.exports = rol; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/ror.js b/node_modules/express-error-handler/node_modules/mout/number/ror.js new file mode 100644 index 000000000..2eda81da0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/ror.js @@ -0,0 +1,10 @@ + + /** + * Bitwise circular shift right + * http://en.wikipedia.org/wiki/Circular_shift + */ + function ror(val, shift){ + return (val >> shift) | (val << (32 - shift)); + } + module.exports = ror; + diff --git a/node_modules/express-error-handler/node_modules/mout/number/sign.js b/node_modules/express-error-handler/node_modules/mout/number/sign.js new file mode 100644 index 000000000..7f9a1e2f2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/sign.js @@ -0,0 +1,15 @@ +var toNumber = require('../lang/toNumber'); + + /** + * Get sign of the value. + */ + function sign(val) { + var num = toNumber(val); + if (num === 0) return num; // +0 and +0 === 0 + if (isNaN(num)) return num; // NaN + return num < 0? -1 : 1; + } + + module.exports = sign; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/toInt.js b/node_modules/express-error-handler/node_modules/mout/number/toInt.js new file mode 100644 index 000000000..72fd7de4d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/toInt.js @@ -0,0 +1,17 @@ + + + /** + * "Convert" value into an 32-bit integer. + * Works like `Math.floor` if val > 0 and `Math.ceil` if val < 0. + * IMPORTANT: val will wrap at 2^31 and -2^31. + * Perf tests: http://jsperf.com/vs-vs-parseint-bitwise-operators/7 + */ + function toInt(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return ~~val; + } + + module.exports = toInt; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/toUInt.js b/node_modules/express-error-handler/node_modules/mout/number/toUInt.js new file mode 100644 index 000000000..d27965630 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/toUInt.js @@ -0,0 +1,15 @@ + + + /** + * "Convert" value into a 32-bit unsigned integer. + * IMPORTANT: Value will wrap at 2^32. + */ + function toUInt(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return val >>> 0; + } + + module.exports = toUInt; + + diff --git a/node_modules/express-error-handler/node_modules/mout/number/toUInt31.js b/node_modules/express-error-handler/node_modules/mout/number/toUInt31.js new file mode 100644 index 000000000..6cd3bb527 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/number/toUInt31.js @@ -0,0 +1,15 @@ +var MAX_INT = require('./MAX_INT'); + + /** + * "Convert" value into an 31-bit unsigned integer (since 1 bit is used for sign). + * IMPORTANT: value wil wrap at 2^31, if negative will return 0. + */ + function toUInt31(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return (val <= 0)? 0 : (val > MAX_INT? ~~(val % (MAX_INT + 1)) : ~~val); + } + + module.exports = toUInt31; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object.js b/node_modules/express-error-handler/node_modules/mout/object.js new file mode 100644 index 000000000..76c064249 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object.js @@ -0,0 +1,42 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'bindAll' : require('./object/bindAll'), + 'contains' : require('./object/contains'), + 'deepEquals' : require('./object/deepEquals'), + 'deepFillIn' : require('./object/deepFillIn'), + 'deepMatches' : require('./object/deepMatches'), + 'deepMixIn' : require('./object/deepMixIn'), + 'equals' : require('./object/equals'), + 'every' : require('./object/every'), + 'fillIn' : require('./object/fillIn'), + 'filter' : require('./object/filter'), + 'find' : require('./object/find'), + 'forIn' : require('./object/forIn'), + 'forOwn' : require('./object/forOwn'), + 'functions' : require('./object/functions'), + 'get' : require('./object/get'), + 'has' : require('./object/has'), + 'hasOwn' : require('./object/hasOwn'), + 'keys' : require('./object/keys'), + 'map' : require('./object/map'), + 'matches' : require('./object/matches'), + 'max' : require('./object/max'), + 'merge' : require('./object/merge'), + 'min' : require('./object/min'), + 'mixIn' : require('./object/mixIn'), + 'namespace' : require('./object/namespace'), + 'pick' : require('./object/pick'), + 'pluck' : require('./object/pluck'), + 'reduce' : require('./object/reduce'), + 'reject' : require('./object/reject'), + 'set' : require('./object/set'), + 'size' : require('./object/size'), + 'some' : require('./object/some'), + 'unset' : require('./object/unset'), + 'values' : require('./object/values') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/bindAll.js b/node_modules/express-error-handler/node_modules/mout/object/bindAll.js new file mode 100644 index 000000000..b2f27d088 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/bindAll.js @@ -0,0 +1,18 @@ +var functions = require('./functions'); +var bind = require('../function/bind'); +var forEach = require('../array/forEach'); + + /** + * Binds methods of the object to be run in it's own context. + */ + function bindAll(obj, rest_methodNames){ + var keys = arguments.length > 1? + Array.prototype.slice.call(arguments, 1) : functions(obj); + forEach(keys, function(key){ + obj[key] = bind(obj[key], obj); + }); + } + + module.exports = bindAll; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/contains.js b/node_modules/express-error-handler/node_modules/mout/object/contains.js new file mode 100644 index 000000000..8076e2c51 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/contains.js @@ -0,0 +1,13 @@ +var some = require('./some'); + + /** + * Check if object contains value + */ + function contains(obj, needle) { + return some(obj, function(val) { + return (val === needle); + }); + } + module.exports = contains; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/deepEquals.js b/node_modules/express-error-handler/node_modules/mout/object/deepEquals.js new file mode 100644 index 000000000..fcde94491 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/deepEquals.js @@ -0,0 +1,27 @@ +var isObject = require('../lang/isObject'); +var equals = require('./equals'); + + function defaultCompare(a, b) { + return a === b; + } + + /** + * Recursively checks for same properties and values. + */ + function deepEquals(a, b, callback){ + callback = callback || defaultCompare; + + if (!isObject(a) || !isObject(b)) { + return callback(a, b); + } + + function compare(a, b){ + return deepEquals(a, b, callback); + } + + return equals(a, b, compare); + } + + module.exports = deepEquals; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/deepFillIn.js b/node_modules/express-error-handler/node_modules/mout/object/deepFillIn.js new file mode 100644 index 000000000..6568ea870 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/deepFillIn.js @@ -0,0 +1,33 @@ +var forOwn = require('./forOwn'); +var isPlainObject = require('../lang/isPlainObject'); + + /** + * Deeply copy missing properties in the target from the defaults. + */ + function deepFillIn(target, defaults){ + var i = 0, + n = arguments.length, + obj; + + while(++i < n) { + obj = arguments[i]; + if (obj) { + // jshint loopfunc: true + forOwn(obj, function(newValue, key) { + var curValue = target[key]; + if (curValue == null) { + target[key] = newValue; + } else if (isPlainObject(curValue) && + isPlainObject(newValue)) { + deepFillIn(curValue, newValue); + } + }); + } + } + + return target; + } + + module.exports = deepFillIn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/deepMatches.js b/node_modules/express-error-handler/node_modules/mout/object/deepMatches.js new file mode 100644 index 000000000..3366c52dd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/deepMatches.js @@ -0,0 +1,55 @@ +var forOwn = require('./forOwn'); +var isArray = require('../lang/isArray'); + + function containsMatch(array, pattern) { + var i = -1, length = array.length; + while (++i < length) { + if (deepMatches(array[i], pattern)) { + return true; + } + } + + return false; + } + + function matchArray(target, pattern) { + var i = -1, patternLength = pattern.length; + while (++i < patternLength) { + if (!containsMatch(target, pattern[i])) { + return false; + } + } + + return true; + } + + function matchObject(target, pattern) { + var result = true; + forOwn(pattern, function(val, key) { + if (!deepMatches(target[key], val)) { + // Return false to break out of forOwn early + return (result = false); + } + }); + + return result; + } + + /** + * Recursively check if the objects match. + */ + function deepMatches(target, pattern){ + if (target && typeof target === 'object') { + if (isArray(target) && isArray(pattern)) { + return matchArray(target, pattern); + } else { + return matchObject(target, pattern); + } + } else { + return target === pattern; + } + } + + module.exports = deepMatches; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/deepMixIn.js b/node_modules/express-error-handler/node_modules/mout/object/deepMixIn.js new file mode 100644 index 000000000..a97e98d0f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/deepMixIn.js @@ -0,0 +1,34 @@ +var forOwn = require('./forOwn'); +var isPlainObject = require('../lang/isPlainObject'); + + /** + * Mixes objects into the target object, recursively mixing existing child + * objects. + */ + function deepMixIn(target, objects) { + var i = 0, + n = arguments.length, + obj; + + while(++i < n){ + obj = arguments[i]; + if (obj) { + forOwn(obj, copyProp, target); + } + } + + return target; + } + + function copyProp(val, key) { + var existing = this[key]; + if (isPlainObject(val) && isPlainObject(existing)) { + deepMixIn(existing, val); + } else { + this[key] = val; + } + } + + module.exports = deepMixIn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/equals.js b/node_modules/express-error-handler/node_modules/mout/object/equals.js new file mode 100644 index 000000000..f50cbe4e4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/equals.js @@ -0,0 +1,36 @@ +var hasOwn = require('./hasOwn'); +var every = require('./every'); +var isObject = require('../lang/isObject'); + + function defaultCompare(a, b) { + return a === b; + } + + // Makes a function to compare the object values from the specified compare + // operation callback. + function makeCompare(callback) { + return function(value, key) { + return hasOwn(this, key) && callback(value, this[key]); + }; + } + + function checkProperties(value, key) { + return hasOwn(this, key); + } + + /** + * Checks if two objects have the same keys and values. + */ + function equals(a, b, callback) { + callback = callback || defaultCompare; + + if (!isObject(a) || !isObject(b)) { + return callback(a, b); + } + + return (every(a, makeCompare(callback), b) && + every(b, checkProperties, a)); + } + + module.exports = equals; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/every.js b/node_modules/express-error-handler/node_modules/mout/object/every.js new file mode 100644 index 000000000..01106e5fe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/every.js @@ -0,0 +1,23 @@ +var forOwn = require('./forOwn'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Object every + */ + function every(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = true; + forOwn(obj, function(val, key) { + // we consider any falsy values as "false" on purpose so shorthand + // syntax can be used to check property existence + if (!callback(val, key, obj)) { + result = false; + return false; // break + } + }); + return result; + } + + module.exports = every; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/fillIn.js b/node_modules/express-error-handler/node_modules/mout/object/fillIn.js new file mode 100644 index 000000000..80dcdf07b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/fillIn.js @@ -0,0 +1,20 @@ +var forEach = require('../array/forEach'); +var forOwn = require('./forOwn'); + + /** + * Copy missing properties in the obj from the defaults. + */ + function fillIn(obj, var_defaults){ + forEach(Array.prototype.slice.call(arguments, 1), function(base){ + forOwn(base, function(val, key){ + if (obj[key] == null) { + obj[key] = val; + } + }); + }); + return obj; + } + + module.exports = fillIn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/filter.js b/node_modules/express-error-handler/node_modules/mout/object/filter.js new file mode 100644 index 000000000..3a83a92f4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/filter.js @@ -0,0 +1,20 @@ +var forOwn = require('./forOwn'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Creates a new object with all the properties where the callback returns + * true. + */ + function filterValues(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var output = {}; + forOwn(obj, function(value, key, obj) { + if (callback(value, key, obj)) { + output[key] = value; + } + }); + + return output; + } + module.exports = filterValues; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/find.js b/node_modules/express-error-handler/node_modules/mout/object/find.js new file mode 100644 index 000000000..d39c07069 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/find.js @@ -0,0 +1,21 @@ +var some = require('./some'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Returns first item that matches criteria + */ + function find(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result; + some(obj, function(value, key, obj) { + if (callback(value, key, obj)) { + result = value; + return true; //break + } + }); + return result; + } + + module.exports = find; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/forIn.js b/node_modules/express-error-handler/node_modules/mout/object/forIn.js new file mode 100644 index 000000000..367f08cab --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/forIn.js @@ -0,0 +1,62 @@ + + + var _hasDontEnumBug, + _dontEnums; + + function checkDontEnum(){ + _dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + + _hasDontEnumBug = true; + + for (var key in {'toString': null}) { + _hasDontEnumBug = false; + } + } + + /** + * Similar to Array/forEach but works over object properties and fixes Don't + * Enum bug on IE. + * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation + */ + function forIn(obj, fn, thisObj){ + var key, i = 0; + // no need to check if argument is a real object that way we can use + // it for arrays, functions, date, etc. + + //post-pone check till needed + if (_hasDontEnumBug == null) checkDontEnum(); + + for (key in obj) { + if (exec(fn, obj, key, thisObj) === false) { + break; + } + } + + if (_hasDontEnumBug) { + while (key = _dontEnums[i++]) { + // since we aren't using hasOwn check we need to make sure the + // property was overwritten + if (obj[key] !== Object.prototype[key]) { + if (exec(fn, obj, key, thisObj) === false) { + break; + } + } + } + } + } + + function exec(fn, obj, key, thisObj){ + return fn.call(thisObj, obj[key], key, obj); + } + + module.exports = forIn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/forOwn.js b/node_modules/express-error-handler/node_modules/mout/object/forOwn.js new file mode 100644 index 000000000..5f2dfbfc0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/forOwn.js @@ -0,0 +1,19 @@ +var hasOwn = require('./hasOwn'); +var forIn = require('./forIn'); + + /** + * Similar to Array/forEach but works over object properties and fixes Don't + * Enum bug on IE. + * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation + */ + function forOwn(obj, fn, thisObj){ + forIn(obj, function(val, key){ + if (hasOwn(obj, key)) { + return fn.call(thisObj, obj[key], key, obj); + } + }); + } + + module.exports = forOwn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/functions.js b/node_modules/express-error-handler/node_modules/mout/object/functions.js new file mode 100644 index 000000000..f57179795 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/functions.js @@ -0,0 +1,18 @@ +var forIn = require('./forIn'); + + /** + * return a list of all enumerable properties that have function values + */ + function functions(obj){ + var keys = []; + forIn(obj, function(val, key){ + if (typeof val === 'function'){ + keys.push(key); + } + }); + return keys.sort(); + } + + module.exports = functions; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/get.js b/node_modules/express-error-handler/node_modules/mout/object/get.js new file mode 100644 index 000000000..7cf9d9bd1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/get.js @@ -0,0 +1,20 @@ + + + /** + * get "nested" object property + */ + function get(obj, prop){ + var parts = prop.split('.'), + last = parts.pop(); + + while (prop = parts.shift()) { + obj = obj[prop]; + if (typeof obj !== 'object' || !obj) return; + } + + return obj[last]; + } + + module.exports = get; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/has.js b/node_modules/express-error-handler/node_modules/mout/object/has.js new file mode 100644 index 000000000..ca9f22892 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/has.js @@ -0,0 +1,15 @@ +var get = require('./get'); + + var UNDEF; + + /** + * Check if object has nested property. + */ + function has(obj, prop){ + return get(obj, prop) !== UNDEF; + } + + module.exports = has; + + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/hasOwn.js b/node_modules/express-error-handler/node_modules/mout/object/hasOwn.js new file mode 100644 index 000000000..7e3c82aeb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/hasOwn.js @@ -0,0 +1,12 @@ + + + /** + * Safer Object.hasOwnProperty + */ + function hasOwn(obj, prop){ + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + module.exports = hasOwn; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/keys.js b/node_modules/express-error-handler/node_modules/mout/object/keys.js new file mode 100644 index 000000000..dd2f4f55b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/keys.js @@ -0,0 +1,16 @@ +var forOwn = require('./forOwn'); + + /** + * Get object keys + */ + var keys = Object.keys || function (obj) { + var keys = []; + forOwn(obj, function(val, key){ + keys.push(key); + }); + return keys; + }; + + module.exports = keys; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/map.js b/node_modules/express-error-handler/node_modules/mout/object/map.js new file mode 100644 index 000000000..dd449a782 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/map.js @@ -0,0 +1,18 @@ +var forOwn = require('./forOwn'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Creates a new object where all the values are the result of calling + * `callback`. + */ + function mapValues(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var output = {}; + forOwn(obj, function(val, key, obj) { + output[key] = callback(val, key, obj); + }); + + return output; + } + module.exports = mapValues; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/matches.js b/node_modules/express-error-handler/node_modules/mout/object/matches.js new file mode 100644 index 000000000..6074faa2d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/matches.js @@ -0,0 +1,20 @@ +var forOwn = require('./forOwn'); + + /** + * checks if a object contains all given properties/values + */ + function matches(target, props){ + // can't use "object/every" because of circular dependency + var result = true; + forOwn(props, function(val, key){ + if (target[key] !== val) { + // break loop at first difference + return (result = false); + } + }); + return result; + } + + module.exports = matches; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/max.js b/node_modules/express-error-handler/node_modules/mout/object/max.js new file mode 100644 index 000000000..3e8e92c7f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/max.js @@ -0,0 +1,12 @@ +var arrMax = require('../array/max'); +var values = require('./values'); + + /** + * Returns maximum value inside object. + */ + function max(obj, compareFn) { + return arrMax(values(obj), compareFn); + } + + module.exports = max; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/merge.js b/node_modules/express-error-handler/node_modules/mout/object/merge.js new file mode 100644 index 000000000..6961f608d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/merge.js @@ -0,0 +1,40 @@ +var hasOwn = require('./hasOwn'); +var deepClone = require('../lang/deepClone'); +var isObject = require('../lang/isObject'); + + /** + * Deep merge objects. + */ + function merge() { + var i = 1, + key, val, obj, target; + + // make sure we don't modify source element and it's properties + // objects are passed by reference + target = deepClone( arguments[0] ); + + while (obj = arguments[i++]) { + for (key in obj) { + if ( ! hasOwn(obj, key) ) { + continue; + } + + val = obj[key]; + + if ( isObject(val) && isObject(target[key]) ){ + // inception, deep merge objects + target[key] = merge(target[key], val); + } else { + // make sure arrays, regexp, date, objects are cloned + target[key] = deepClone(val); + } + + } + } + + return target; + } + + module.exports = merge; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/min.js b/node_modules/express-error-handler/node_modules/mout/object/min.js new file mode 100644 index 000000000..e1e669767 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/min.js @@ -0,0 +1,12 @@ +var arrMin = require('../array/min'); +var values = require('./values'); + + /** + * Returns minimum value inside object. + */ + function min(obj, iterator) { + return arrMin(values(obj), iterator); + } + + module.exports = min; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/mixIn.js b/node_modules/express-error-handler/node_modules/mout/object/mixIn.js new file mode 100644 index 000000000..55ec8fd59 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/mixIn.js @@ -0,0 +1,28 @@ +var forOwn = require('./forOwn'); + + /** + * Combine properties from all the objects into first one. + * - This method affects target object in place, if you want to create a new Object pass an empty object as first param. + * @param {object} target Target Object + * @param {...object} objects Objects to be combined (0...n objects). + * @return {object} Target Object. + */ + function mixIn(target, objects){ + var i = 0, + n = arguments.length, + obj; + while(++i < n){ + obj = arguments[i]; + if (obj != null) { + forOwn(obj, copyProp, target); + } + } + return target; + } + + function copyProp(val, key){ + this[key] = val; + } + + module.exports = mixIn; + diff --git a/node_modules/express-error-handler/node_modules/mout/object/namespace.js b/node_modules/express-error-handler/node_modules/mout/object/namespace.js new file mode 100644 index 000000000..c6e79f635 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/namespace.js @@ -0,0 +1,19 @@ +var forEach = require('../array/forEach'); + + /** + * Create nested object if non-existent + */ + function namespace(obj, path){ + if (!path) return obj; + forEach(path.split('.'), function(key){ + if (!obj[key]) { + obj[key] = {}; + } + obj = obj[key]; + }); + return obj; + } + + module.exports = namespace; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/pick.js b/node_modules/express-error-handler/node_modules/mout/object/pick.js new file mode 100644 index 000000000..74e56f983 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/pick.js @@ -0,0 +1,18 @@ + + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys. + */ + function pick(obj, var_keys){ + var keys = typeof arguments[1] !== 'string'? arguments[1] : Array.prototype.slice.call(arguments, 1), + out = {}, + i = 0, key; + while (key = keys[i++]) { + out[key] = obj[key]; + } + return out; + } + + module.exports = pick; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/pluck.js b/node_modules/express-error-handler/node_modules/mout/object/pluck.js new file mode 100644 index 000000000..e844df473 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/pluck.js @@ -0,0 +1,13 @@ +var map = require('./map'); +var prop = require('../function/prop'); + + /** + * Extract a list of property values. + */ + function pluck(obj, propName){ + return map(obj, prop(propName)); + } + + module.exports = pluck; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/reduce.js b/node_modules/express-error-handler/node_modules/mout/object/reduce.js new file mode 100644 index 000000000..6f19a3a2b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/reduce.js @@ -0,0 +1,29 @@ +var forOwn = require('./forOwn'); +var size = require('./size'); + + /** + * Object reduce + */ + function reduce(obj, callback, memo, thisObj) { + var initial = arguments.length > 2; + + if (!size(obj) && !initial) { + throw new Error('reduce of empty object with no initial value'); + } + + forOwn(obj, function(value, key, list) { + if (!initial) { + memo = value; + initial = true; + } + else { + memo = callback.call(thisObj, memo, value, key, list); + } + }); + + return memo; + } + + module.exports = reduce; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/reject.js b/node_modules/express-error-handler/node_modules/mout/object/reject.js new file mode 100644 index 000000000..746437954 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/reject.js @@ -0,0 +1,16 @@ +var filter = require('./filter'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Object reject + */ + function reject(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + return filter(obj, function(value, index, obj) { + return !callback(value, index, obj); + }, thisObj); + } + + module.exports = reject; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/set.js b/node_modules/express-error-handler/node_modules/mout/object/set.js new file mode 100644 index 000000000..9b3cdc483 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/set.js @@ -0,0 +1,17 @@ +var namespace = require('./namespace'); + + /** + * set "nested" object property + */ + function set(obj, prop, val){ + var parts = (/^(.+)\.(.+)$/).exec(prop); + if (parts){ + namespace(obj, parts[1])[parts[2]] = val; + } else { + obj[prop] = val; + } + } + + module.exports = set; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/size.js b/node_modules/express-error-handler/node_modules/mout/object/size.js new file mode 100644 index 000000000..97885953f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/size.js @@ -0,0 +1,16 @@ +var forOwn = require('./forOwn'); + + /** + * Get object size + */ + function size(obj) { + var count = 0; + forOwn(obj, function(){ + count++; + }); + return count; + } + + module.exports = size; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/some.js b/node_modules/express-error-handler/node_modules/mout/object/some.js new file mode 100644 index 000000000..384c6f3c7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/some.js @@ -0,0 +1,21 @@ +var forOwn = require('./forOwn'); +var makeIterator = require('../function/makeIterator_'); + + /** + * Object some + */ + function some(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = false; + forOwn(obj, function(val, key) { + if (callback(val, key, obj)) { + result = true; + return false; // break + } + }); + return result; + } + + module.exports = some; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/unset.js b/node_modules/express-error-handler/node_modules/mout/object/unset.js new file mode 100644 index 000000000..343bca0aa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/unset.js @@ -0,0 +1,23 @@ +var has = require('./has'); + + /** + * Unset object property. + */ + function unset(obj, prop){ + if (has(obj, prop)) { + var parts = prop.split('.'), + last = parts.pop(); + while (prop = parts.shift()) { + obj = obj[prop]; + } + return (delete obj[last]); + + } else { + // if property doesn't exist treat as deleted + return true; + } + } + + module.exports = unset; + + diff --git a/node_modules/express-error-handler/node_modules/mout/object/values.js b/node_modules/express-error-handler/node_modules/mout/object/values.js new file mode 100644 index 000000000..265a69383 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/object/values.js @@ -0,0 +1,16 @@ +var forOwn = require('./forOwn'); + + /** + * Get object values + */ + function values(obj) { + var vals = []; + forOwn(obj, function(val, key){ + vals.push(val); + }); + return vals; + } + + module.exports = values; + + diff --git a/node_modules/express-error-handler/node_modules/mout/package.json b/node_modules/express-error-handler/node_modules/mout/package.json new file mode 100644 index 000000000..3a7f0585a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/package.json @@ -0,0 +1,140 @@ +{ + "name": "mout", + "description": "Modular Utilities", + "version": "0.7.1", + "homepage": "http://moutjs.com/", + "contributors": [ + { + "name": "Adam Nowotny" + }, + { + "name": "André Cruz", + "email": "amdfcruz@gmail.com" + }, + { + "name": "Conrad Zimmerman", + "url": "http://www.conradz.com" + }, + { + "name": "Friedemann Altrock", + "email": "frodenius@gmail.com" + }, + { + "name": "Jarrod Overson", + "url": "http://jarrodoverson.com" + }, + { + "name": "Miller Medeiros", + "email": "contact@millermedeiros.com", + "url": "http://blog.millermedeiros.com" + }, + { + "name": "Zach Shipley" + } + ], + "keywords": [ + "utilities", + "functional", + "amd-utils", + "stdlib" + ], + "repository": { + "type": "git", + "url": "git://github.com/mout/mout.git" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/mit-license.php" + } + ], + "bugs": { + "url": "https://github.com/mout/mout/issues/" + }, + "main": "./index.js", + "scripts": { + "prepublish": "node build cjs .", + "pretest": "node build pkg", + "test": "node node_modules/istanbul/lib/cli test tests/runner.js --hook-run-in-context" + }, + "directories": { + "doc": "./doc" + }, + "devDependencies": { + "istanbul": "~0.1.27", + "jasmine-node": "~1.2.2", + "requirejs": "2.x", + "nodefy": "*", + "mdoc": "~0.3.2", + "handlebars": "~1.0.6", + "commander": "~1.0.5", + "rocambole": "~0.2.3", + "jshint": "2.x" + }, + "testling": { + "preprocess": "node build testling", + "browsers": { + "ie": [ + 7, + 8, + 9, + 10 + ], + "firefox": [ + 17, + "nightly" + ], + "chrome": [ + 23, + "canary" + ], + "opera": [ + 12, + "next" + ], + "safari": [ + 5.1, + 6 + ], + "iphone": [ + 6 + ], + "ipad": [ + 6 + ] + }, + "scripts": [ + "tests/lib/jasmine/jasmine.js", + "tests/lib/jasmine/jasmine.async.js", + "tests/lib/jasmine/jasmine-tap.js", + "tests/lib/requirejs/require.js", + "tests/testling/src.js", + "tests/testling/specs.js", + "tests/runner.js" + ] + }, + "_id": "mout@0.7.1", + "dist": { + "shasum": "218de2b0880b220d99f4fbaee3fc0c3a5310bda8", + "tarball": "http://registry.npmjs.org/mout/-/mout-0.7.1.tgz" + }, + "_from": "mout@~0.7.1", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "millermedeiros", + "email": "miller@millermedeiros.com" + }, + "maintainers": [ + { + "name": "millermedeiros", + "email": "miller@millermedeiros.com" + }, + { + "name": "satazor", + "email": "andremiguelcruz@msn.com" + } + ], + "_shasum": "218de2b0880b220d99f4fbaee3fc0c3a5310bda8", + "_resolved": "https://registry.npmjs.org/mout/-/mout-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/express-error-handler/node_modules/mout/queryString.js b/node_modules/express-error-handler/node_modules/mout/queryString.js new file mode 100644 index 000000000..22685a7fa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString.js @@ -0,0 +1,15 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'contains' : require('./queryString/contains'), + 'decode' : require('./queryString/decode'), + 'encode' : require('./queryString/encode'), + 'getParam' : require('./queryString/getParam'), + 'getQuery' : require('./queryString/getQuery'), + 'parse' : require('./queryString/parse'), + 'setParam' : require('./queryString/setParam') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/contains.js b/node_modules/express-error-handler/node_modules/mout/queryString/contains.js new file mode 100644 index 000000000..da678cf4e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/contains.js @@ -0,0 +1,12 @@ +var getQuery = require('./getQuery'); + + /** + * Checks if query string contains parameter. + */ + function contains(url, paramName) { + var regex = new RegExp('(\\?|&)'+ paramName +'=', 'g'); //matches `?param=` or `¶m=` + return regex.test(getQuery(url)); + } + + module.exports = contains; + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/decode.js b/node_modules/express-error-handler/node_modules/mout/queryString/decode.js new file mode 100644 index 000000000..1c15785bf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/decode.js @@ -0,0 +1,38 @@ +var typecast = require('../string/typecast'); +var isString = require('../lang/isString'); +var isArray = require('../lang/isArray'); +var hasOwn = require('../object/hasOwn'); + + /** + * Decode query string into an object of keys => vals. + */ + function decode(queryStr, shouldTypecast) { + var queryArr = (queryStr || '').replace('?', '').split('&'), + count = -1, + length = queryArr.length, + obj = {}, + item, pValue, pName, toSet; + + while (++count < length) { + item = queryArr[count].split('='); + pName = item[0]; + if (!pName || !pName.length){ + continue; + } + pValue = shouldTypecast === false ? item[1] : typecast(item[1]); + toSet = isString(pValue) ? decodeURIComponent(pValue) : pValue; + if (hasOwn(obj,pName)){ + if(isArray(obj[pName])){ + obj[pName].push(toSet); + } else { + obj[pName] = [obj[pName],toSet]; + } + } else { + obj[pName] = toSet; + } + } + return obj; + } + + module.exports = decode; + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/encode.js b/node_modules/express-error-handler/node_modules/mout/queryString/encode.js new file mode 100644 index 000000000..3a4fd0a69 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/encode.js @@ -0,0 +1,27 @@ +var forOwn = require('../object/forOwn'); +var isArray = require('../lang/isArray'); +var forEach = require('../array/forEach'); + + /** + * Encode object into a query string. + */ + function encode(obj){ + var query = [], + arrValues, reg; + forOwn(obj, function (val, key) { + if (isArray(val)) { + arrValues = key + '='; + reg = new RegExp('&'+key+'+=$'); + forEach(val, function (aValue) { + arrValues += encodeURIComponent(aValue) + '&' + key + '='; + }); + query.push(arrValues.replace(reg, '')); + } else { + query.push(key + '=' + encodeURIComponent(val)); + } + }); + return (query.length) ? '?' + query.join('&') : ''; + } + + module.exports = encode; + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/getParam.js b/node_modules/express-error-handler/node_modules/mout/queryString/getParam.js new file mode 100644 index 000000000..f149c3ea5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/getParam.js @@ -0,0 +1,15 @@ +var typecast = require('../string/typecast'); +var getQuery = require('./getQuery'); + + /** + * Get query parameter value. + */ + function getParam(url, param, shouldTypecast){ + var regexp = new RegExp('(\\?|&)'+ param + '=([^&]*)'), //matches `?param=value` or `¶m=value`, value = $2 + result = regexp.exec( getQuery(url) ), + val = (result && result[2])? result[2] : null; + return shouldTypecast === false? val : typecast(val); + } + + module.exports = getParam; + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/getQuery.js b/node_modules/express-error-handler/node_modules/mout/queryString/getQuery.js new file mode 100644 index 000000000..5194af2d3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/getQuery.js @@ -0,0 +1,13 @@ + + + /** + * Gets full query as string with all special chars decoded. + */ + function getQuery(url) { + url = url.replace(/#.*/, ''); //removes hash (to avoid getting hash query) + var queryString = /\?[a-zA-Z0-9\=\&\%\$\-\_\.\+\!\*\'\(\)\,]+/.exec(url); //valid chars according to: http://www.ietf.org/rfc/rfc1738.txt + return (queryString)? decodeURIComponent(queryString[0]) : ''; + } + + module.exports = getQuery; + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/parse.js b/node_modules/express-error-handler/node_modules/mout/queryString/parse.js new file mode 100644 index 000000000..532906c09 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/parse.js @@ -0,0 +1,13 @@ +var decode = require('./decode'); +var getQuery = require('./getQuery'); + + /** + * Get query string, parses and decodes it. + */ + function parse(url, shouldTypecast) { + return decode(getQuery(url), shouldTypecast); + } + + module.exports = parse; + + diff --git a/node_modules/express-error-handler/node_modules/mout/queryString/setParam.js b/node_modules/express-error-handler/node_modules/mout/queryString/setParam.js new file mode 100644 index 000000000..052a9ba63 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/queryString/setParam.js @@ -0,0 +1,28 @@ + + + /** + * Set query string parameter value + */ + function setParam(url, paramName, value){ + url = url || ''; + + var re = new RegExp('(\\?|&)'+ paramName +'=[^&]*' ); + var param = paramName +'='+ encodeURIComponent( value ); + + if ( re.test(url) ) { + return url.replace(re, '$1'+ param); + } else { + if (url.indexOf('?') === -1) { + url += '?'; + } + if (url.indexOf('=') !== -1) { + url += '&'; + } + return url + param; + } + + } + + module.exports = setParam; + + diff --git a/node_modules/express-error-handler/node_modules/mout/random.js b/node_modules/express-error-handler/node_modules/mout/random.js new file mode 100644 index 000000000..d9267f012 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random.js @@ -0,0 +1,16 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'choice' : require('./random/choice'), + 'guid' : require('./random/guid'), + 'rand' : require('./random/rand'), + 'randBit' : require('./random/randBit'), + 'randHex' : require('./random/randHex'), + 'randInt' : require('./random/randInt'), + 'randSign' : require('./random/randSign'), + 'random' : require('./random/random') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/random/choice.js b/node_modules/express-error-handler/node_modules/mout/random/choice.js new file mode 100644 index 000000000..51aa82a21 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/choice.js @@ -0,0 +1,15 @@ +var randInt = require('./randInt'); +var isArray = require('../lang/isArray'); + + /** + * Returns a random element from the supplied arguments + * or from the array (if single argument is an array). + */ + function choice(items) { + var target = (arguments.length === 1 && isArray(items))? items : arguments; + return target[ randInt(0, target.length - 1) ]; + } + + module.exports = choice; + + diff --git a/node_modules/express-error-handler/node_modules/mout/random/guid.js b/node_modules/express-error-handler/node_modules/mout/random/guid.js new file mode 100644 index 000000000..41f6eddc3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/guid.js @@ -0,0 +1,24 @@ +var randHex = require('./randHex'); +var choice = require('./choice'); + + /** + * Returns pseudo-random guid (UUID v4) + * IMPORTANT: it's not totally "safe" since randHex/choice uses Math.random + * by default and sequences can be predicted in some cases. See the + * "random/random" documentation for more info about it and how to replace + * the default PRNG. + */ + function guid() { + return ( + randHex(8)+'-'+ + randHex(4)+'-'+ + // v4 UUID always contain "4" at this position to specify it was + // randomly generated + '4' + randHex(3) +'-'+ + // v4 UUID always contain chars [a,b,8,9] at this position + choice(8, 9, 'a', 'b') + randHex(3)+'-'+ + randHex(12) + ); + } + module.exports = guid; + diff --git a/node_modules/express-error-handler/node_modules/mout/random/rand.js b/node_modules/express-error-handler/node_modules/mout/random/rand.js new file mode 100644 index 000000000..782dec88a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/rand.js @@ -0,0 +1,15 @@ +var random = require('./random'); +var MIN_INT = require('../number/MIN_INT'); +var MAX_INT = require('../number/MAX_INT'); + + /** + * Returns random number inside range + */ + function rand(min, max){ + min = min == null? MIN_INT : min; + max = max == null? MAX_INT : max; + return min + (max - min) * random(); + } + + module.exports = rand; + diff --git a/node_modules/express-error-handler/node_modules/mout/random/randBit.js b/node_modules/express-error-handler/node_modules/mout/random/randBit.js new file mode 100644 index 000000000..bd20b4a08 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/randBit.js @@ -0,0 +1,11 @@ +var random = require('./random'); + + /** + * Returns random bit (0 or 1) + */ + function randomBit() { + return random() > 0.5? 1 : 0; + } + + module.exports = randomBit; + diff --git a/node_modules/express-error-handler/node_modules/mout/random/randHex.js b/node_modules/express-error-handler/node_modules/mout/random/randHex.js new file mode 100644 index 000000000..d8d711c31 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/randHex.js @@ -0,0 +1,19 @@ +var choice = require('./choice'); + + var _chars = '0123456789abcdef'.split(''); + + /** + * Returns a random hexadecimal string + */ + function randHex(size){ + size = size && size > 0? size : 6; + var str = ''; + while (size--) { + str += choice(_chars); + } + return str; + } + + module.exports = randHex; + + diff --git a/node_modules/express-error-handler/node_modules/mout/random/randInt.js b/node_modules/express-error-handler/node_modules/mout/random/randInt.js new file mode 100644 index 000000000..e237d9647 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/randInt.js @@ -0,0 +1,18 @@ +var MIN_INT = require('../number/MIN_INT'); +var MAX_INT = require('../number/MAX_INT'); +var rand = require('./rand'); + + /** + * Gets random integer inside range or snap to min/max values. + */ + function randInt(min, max){ + min = min == null? MIN_INT : ~~min; + max = max == null? MAX_INT : ~~max; + // can't be max + 0.5 otherwise it will round up if `rand` + // returns `max` causing it to overflow range. + // -0.5 and + 0.49 are required to avoid bias caused by rounding + return Math.round( rand(min - 0.5, max + 0.499999999999) ); + } + + module.exports = randInt; + diff --git a/node_modules/express-error-handler/node_modules/mout/random/randSign.js b/node_modules/express-error-handler/node_modules/mout/random/randSign.js new file mode 100644 index 000000000..5a9fed76f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/randSign.js @@ -0,0 +1,11 @@ +var random = require('./random'); + + /** + * Returns random sign (-1 or 1) + */ + function randomSign() { + return random() > 0.5? 1 : -1; + } + + module.exports = randomSign; + diff --git a/node_modules/express-error-handler/node_modules/mout/random/random.js b/node_modules/express-error-handler/node_modules/mout/random/random.js new file mode 100644 index 000000000..670a3cc47 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/random/random.js @@ -0,0 +1,18 @@ + + + /** + * Just a wrapper to Math.random. No methods inside mout/random should call + * Math.random() directly so we can inject the pseudo-random number + * generator if needed (ie. in case we need a seeded random or a better + * algorithm than the native one) + */ + function random(){ + return random.get(); + } + + // we expose the method so it can be swapped if needed + random.get = Math.random; + + module.exports = random; + + diff --git a/node_modules/express-error-handler/node_modules/mout/src/array.js b/node_modules/express-error-handler/node_modules/mout/src/array.js new file mode 100644 index 000000000..7bcc961b5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array.js @@ -0,0 +1,46 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'append' : require('./array/append'), + 'collect' : require('./array/collect'), + 'combine' : require('./array/combine'), + 'compact' : require('./array/compact'), + 'contains' : require('./array/contains'), + 'difference' : require('./array/difference'), + 'every' : require('./array/every'), + 'filter' : require('./array/filter'), + 'find' : require('./array/find'), + 'findIndex' : require('./array/findIndex'), + 'flatten' : require('./array/flatten'), + 'forEach' : require('./array/forEach'), + 'indexOf' : require('./array/indexOf'), + 'insert' : require('./array/insert'), + 'intersection' : require('./array/intersection'), + 'invoke' : require('./array/invoke'), + 'join' : require('./array/join'), + 'lastIndexOf' : require('./array/lastIndexOf'), + 'map' : require('./array/map'), + 'max' : require('./array/max'), + 'min' : require('./array/min'), + 'pick' : require('./array/pick'), + 'pluck' : require('./array/pluck'), + 'range' : require('./array/range'), + 'reduce' : require('./array/reduce'), + 'reduceRight' : require('./array/reduceRight'), + 'reject' : require('./array/reject'), + 'remove' : require('./array/remove'), + 'removeAll' : require('./array/removeAll'), + 'shuffle' : require('./array/shuffle'), + 'some' : require('./array/some'), + 'sort' : require('./array/sort'), + 'split' : require('./array/split'), + 'toLookup' : require('./array/toLookup'), + 'union' : require('./array/union'), + 'unique' : require('./array/unique'), + 'xor' : require('./array/xor'), + 'zip' : require('./array/zip') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/append.js b/node_modules/express-error-handler/node_modules/mout/src/array/append.js new file mode 100644 index 000000000..549d8754c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/append.js @@ -0,0 +1,21 @@ +define(function () { + + /** + * Appends an array to the end of another. + * The first array will be modified. + */ + function append(arr1, arr2) { + if (arr2 == null) { + return arr1; + } + + var pad = arr1.length, + i = -1, + len = arr2.length; + while (++i < len) { + arr1[pad + i] = arr2[i]; + } + return arr1; + } + return append; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/collect.js b/node_modules/express-error-handler/node_modules/mout/src/array/collect.js new file mode 100644 index 000000000..8f60cda28 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/collect.js @@ -0,0 +1,26 @@ +define(['./append', '../function/makeIterator_'], function (append, makeIterator) { + + /** + * Maps the items in the array and concatenates the result arrays. + */ + function collect(arr, callback, thisObj){ + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length; + while (++i < len) { + var value = callback(arr[i], i, arr); + if (value != null) { + append(results, value); + } + } + + return results; + } + + return collect; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/combine.js b/node_modules/express-error-handler/node_modules/mout/src/array/combine.js new file mode 100644 index 000000000..22efb8607 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/combine.js @@ -0,0 +1,22 @@ +define(['./indexOf'], function (indexOf) { + + /** + * Combines an array with all the items of another. + * Does not allow duplicates and is case and type sensitive. + */ + function combine(arr1, arr2) { + if (arr2 == null) { + return arr1; + } + + var i = -1, len = arr2.length; + while (++i < len) { + if (indexOf(arr1, arr2[i]) === -1) { + arr1.push(arr2[i]); + } + } + + return arr1; + } + return combine; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/compact.js b/node_modules/express-error-handler/node_modules/mout/src/array/compact.js new file mode 100644 index 000000000..02a81098f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/compact.js @@ -0,0 +1,13 @@ +define(['./filter'], function (filter) { + + /** + * Remove all null/undefined items from array. + */ + function compact(arr) { + return filter(arr, function(val){ + return (val != null); + }); + } + + return compact; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/contains.js b/node_modules/express-error-handler/node_modules/mout/src/array/contains.js new file mode 100644 index 000000000..fca4f7cbe --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/contains.js @@ -0,0 +1,10 @@ +define(['./indexOf'], function (indexOf) { + + /** + * If array contains values. + */ + function contains(arr, val) { + return indexOf(arr, val) !== -1; + } + return contains; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/difference.js b/node_modules/express-error-handler/node_modules/mout/src/array/difference.js new file mode 100644 index 000000000..819bda3ec --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/difference.js @@ -0,0 +1,19 @@ +define(['./unique', './filter', './some', './contains'], function (unique, filter, some, contains) { + + + /** + * Return a new Array with elements that aren't present in the other Arrays. + */ + function difference(arr) { + var arrs = Array.prototype.slice.call(arguments, 1), + result = filter(unique(arr), function(needle){ + return !some(arrs, function(haystack){ + return contains(haystack, needle); + }); + }); + return result; + } + + return difference; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/every.js b/node_modules/express-error-handler/node_modules/mout/src/array/every.js new file mode 100644 index 000000000..78ba46d32 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/every.js @@ -0,0 +1,27 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Array every + */ + function every(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = true; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (!callback(arr[i], i, arr) ) { + result = false; + break; + } + } + + return result; + } + + return every; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/filter.js b/node_modules/express-error-handler/node_modules/mout/src/array/filter.js new file mode 100644 index 000000000..38add180f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/filter.js @@ -0,0 +1,26 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Array filter + */ + function filter(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + if (callback(value, i, arr)) { + results.push(value); + } + } + + return results; + } + + return filter; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/find.js b/node_modules/express-error-handler/node_modules/mout/src/array/find.js new file mode 100644 index 000000000..3957dcd53 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/find.js @@ -0,0 +1,13 @@ +define(['./findIndex'], function (findIndex) { + + /** + * Returns first item that matches criteria + */ + function find(arr, iterator, thisObj){ + var idx = findIndex(arr, iterator, thisObj); + return idx >= 0? arr[idx] : void(0); + } + + return find; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/findIndex.js b/node_modules/express-error-handler/node_modules/mout/src/array/findIndex.js new file mode 100644 index 000000000..59dfeeb9f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/findIndex.js @@ -0,0 +1,23 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Returns the index of the first item that matches criteria + */ + function findIndex(arr, iterator, thisObj){ + iterator = makeIterator(iterator, thisObj); + if (arr == null) { + return -1; + } + + var i = -1, len = arr.length; + while (++i < len) { + if (iterator(arr[i], i, arr)) { + return i; + } + } + + return -1; + } + + return findIndex; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/flatten.js b/node_modules/express-error-handler/node_modules/mout/src/array/flatten.js new file mode 100644 index 000000000..42e87f435 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/flatten.js @@ -0,0 +1,42 @@ +define(['../lang/isArray', './append'], function (isArray, append) { + + /* + * Helper function to flatten to a destination array. + * Used to remove the need to create intermediate arrays while flattening. + */ + function flattenTo(arr, result, level) { + if (arr == null) { + return result; + } else if (level === 0) { + append(result, arr); + return result; + } + + var value, + i = -1, + len = arr.length; + while (++i < len) { + value = arr[i]; + if (isArray(value)) { + flattenTo(value, result, level - 1); + } else { + result.push(value); + } + } + return result; + } + + /** + * Recursively flattens an array. + * A new array containing all the elements is returned. + * If `shallow` is true, it will only flatten one level. + */ + function flatten(arr, level) { + level = level == null? -1 : level; + return flattenTo(arr, [], level); + } + + return flatten; + +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/forEach.js b/node_modules/express-error-handler/node_modules/mout/src/array/forEach.js new file mode 100644 index 000000000..0e0458686 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/forEach.js @@ -0,0 +1,23 @@ +define(function () { + + /** + * Array forEach + */ + function forEach(arr, callback, thisObj) { + if (arr == null) { + return; + } + var i = -1, + len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if ( callback.call(thisObj, arr[i], i, arr) === false ) { + break; + } + } + } + + return forEach; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/indexOf.js b/node_modules/express-error-handler/node_modules/mout/src/array/indexOf.js new file mode 100644 index 000000000..0e75f99b1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/indexOf.js @@ -0,0 +1,28 @@ +define(function () { + + /** + * Array.indexOf + */ + function indexOf(arr, item, fromIndex) { + fromIndex = fromIndex || 0; + if (arr == null) { + return -1; + } + + var len = arr.length, + i = fromIndex < 0 ? len + fromIndex : fromIndex; + while (i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (arr[i] === item) { + return i; + } + + i++; + } + + return -1; + } + + return indexOf; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/insert.js b/node_modules/express-error-handler/node_modules/mout/src/array/insert.js new file mode 100644 index 000000000..d8d831f6d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/insert.js @@ -0,0 +1,14 @@ +define(['./difference', '../lang/toArray'], function (difference, toArray) { + + /** + * Insert item into array if not already present. + */ + function insert(arr, rest_items) { + var diff = difference(toArray(arguments).slice(1), arr); + if (diff.length) { + Array.prototype.push.apply(arr, diff); + } + return arr.length; + } + return insert; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/intersection.js b/node_modules/express-error-handler/node_modules/mout/src/array/intersection.js new file mode 100644 index 000000000..64e6ee97d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/intersection.js @@ -0,0 +1,20 @@ +define(['./unique', './filter', './every', './contains'], function (unique, filter, every, contains) { + + + /** + * Return a new Array with elements common to all Arrays. + * - based on underscore.js implementation + */ + function intersection(arr) { + var arrs = Array.prototype.slice.call(arguments, 1), + result = filter(unique(arr), function(needle){ + return every(arrs, function(haystack){ + return contains(haystack, needle); + }); + }); + return result; + } + + return intersection; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/invoke.js b/node_modules/express-error-handler/node_modules/mout/src/array/invoke.js new file mode 100644 index 000000000..f94a9a4a6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/invoke.js @@ -0,0 +1,23 @@ +define(function () { + + /** + * Call `methodName` on each item of the array passing custom arguments if + * needed. + */ + function invoke(arr, methodName, var_args){ + if (arr == null) { + return arr; + } + + var args = Array.prototype.slice.call(arguments, 2); + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + value[methodName].apply(value, args); + } + + return arr; + } + + return invoke; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/join.js b/node_modules/express-error-handler/node_modules/mout/src/array/join.js new file mode 100644 index 000000000..2c618d291 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/join.js @@ -0,0 +1,17 @@ +define(['./filter'], function(filter) { + + function isValidString(val) { + return (val != null && val !== ''); + } + + /** + * Joins strings with the specified separator inserted between each value. + * Null values and empty strings will be excluded. + */ + function join(items, separator) { + separator = separator || ''; + return filter(items, isValidString).join(separator); + } + + return join; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/lastIndexOf.js b/node_modules/express-error-handler/node_modules/mout/src/array/lastIndexOf.js new file mode 100644 index 000000000..931235f46 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/lastIndexOf.js @@ -0,0 +1,28 @@ +define(function () { + + /** + * Array lastIndexOf + */ + function lastIndexOf(arr, item, fromIndex) { + if (arr == null) { + return -1; + } + + var len = arr.length; + fromIndex = (fromIndex == null || fromIndex >= len)? len - 1 : fromIndex; + fromIndex = (fromIndex < 0)? len + fromIndex : fromIndex; + + while (fromIndex >= 0) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if (arr[fromIndex] === item) { + return fromIndex; + } + fromIndex--; + } + + return -1; + } + + return lastIndexOf; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/map.js b/node_modules/express-error-handler/node_modules/mout/src/array/map.js new file mode 100644 index 000000000..14377ab6b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/map.js @@ -0,0 +1,22 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Array map + */ + function map(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null){ + return results; + } + + var i = -1, len = arr.length; + while (++i < len) { + results[i] = callback(arr[i], i, arr); + } + + return results; + } + + return map; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/max.js b/node_modules/express-error-handler/node_modules/mout/src/array/max.js new file mode 100644 index 000000000..d0628f0a9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/max.js @@ -0,0 +1,34 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Return maximum value inside array + */ + function max(arr, iterator, thisObj){ + if (arr == null || !arr.length) { + return Infinity; + } else if (arr.length && !iterator) { + return Math.max.apply(Math, arr); + } else { + iterator = makeIterator(iterator, thisObj); + var result, + compare = -Infinity, + value, + temp; + + var i = -1, len = arr.length; + while (++i < len) { + value = arr[i]; + temp = iterator(value, i, arr); + if (temp > compare) { + compare = temp; + result = value; + } + } + + return result; + } + } + + return max; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/min.js b/node_modules/express-error-handler/node_modules/mout/src/array/min.js new file mode 100644 index 000000000..07a0c71ff --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/min.js @@ -0,0 +1,34 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Return minimum value inside array + */ + function min(arr, iterator, thisObj){ + if (arr == null || !arr.length) { + return -Infinity; + } else if (arr.length && !iterator) { + return Math.min.apply(Math, arr); + } else { + iterator = makeIterator(iterator, thisObj); + var result, + compare = Infinity, + value, + temp; + + var i = -1, len = arr.length; + while (++i < len) { + value = arr[i]; + temp = iterator(value, i, arr); + if (temp < compare) { + compare = temp; + result = value; + } + } + + return result; + } + } + + return min; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/pick.js b/node_modules/express-error-handler/node_modules/mout/src/array/pick.js new file mode 100644 index 000000000..dc5b222f4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/pick.js @@ -0,0 +1,31 @@ +define(['../random/randInt'], function (randInt) { + + /** + * Remove random item(s) from the Array and return it. + * Returns an Array of items if [nItems] is provided or a single item if + * it isn't specified. + */ + function pick(arr, nItems){ + if (nItems != null) { + var result = []; + if (nItems > 0 && arr && arr.length) { + nItems = nItems > arr.length? arr.length : nItems; + while (nItems--) { + result.push( pickOne(arr) ); + } + } + return result; + } + return (arr && arr.length)? pickOne(arr) : void(0); + } + + + function pickOne(arr){ + var idx = randInt(0, arr.length - 1); + return arr.splice(idx, 1)[0]; + } + + + return pick; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/pluck.js b/node_modules/express-error-handler/node_modules/mout/src/array/pluck.js new file mode 100644 index 000000000..c908856ef --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/pluck.js @@ -0,0 +1,12 @@ +define(['./map'], function (map) { + + /** + * Extract a list of property values. + */ + function pluck(arr, propName){ + return map(arr, propName); + } + + return pluck; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/range.js b/node_modules/express-error-handler/node_modules/mout/src/array/range.js new file mode 100644 index 000000000..148ebf96f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/range.js @@ -0,0 +1,27 @@ +define(['../math/countSteps'], function (countSteps) { + + /** + * Returns an Array of numbers inside range. + */ + function range(start, stop, step) { + if (stop == null) { + stop = start; + start = 0; + } + step = step || 1; + + var result = [], + nSteps = countSteps(stop - start, step), + i = start; + + while (i <= stop) { + result.push(i); + i += step; + } + + return result; + } + + return range; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/reduce.js b/node_modules/express-error-handler/node_modules/mout/src/array/reduce.js new file mode 100644 index 000000000..5f97ae8e2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/reduce.js @@ -0,0 +1,33 @@ +define(function () { + + /** + * Array reduce + */ + function reduce(arr, fn, initVal) { + // check for args.length since initVal might be "undefined" see #gh-57 + var hasInit = arguments.length > 2, + result = initVal; + + if (arr == null || !arr.length) { + if (!hasInit) { + throw new Error('reduce of empty array with no initial value'); + } else { + return initVal; + } + } + + var i = -1, len = arr.length; + while (++i < len) { + if (!hasInit) { + result = arr[i]; + hasInit = true; + } else { + result = fn(result, arr[i], i, arr); + } + } + + return result; + } + + return reduce; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/reduceRight.js b/node_modules/express-error-handler/node_modules/mout/src/array/reduceRight.js new file mode 100644 index 000000000..ddae0e7f4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/reduceRight.js @@ -0,0 +1,34 @@ +define(function () { + + /** + * Array reduceRight + */ + function reduceRight(arr, fn, initVal) { + // check for args.length since initVal might be "undefined" see #gh-57 + var hasInit = arguments.length > 2; + + if (arr == null || !arr.length) { + if (hasInit) { + return initVal; + } else { + throw new Error('reduce of empty array with no initial value'); + } + } + + var i = arr.length, result = initVal, value; + while (--i >= 0) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + value = arr[i]; + if (!hasInit) { + result = value; + hasInit = true; + } else { + result = fn(result, value, i, arr); + } + } + return result; + } + + return reduceRight; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/reject.js b/node_modules/express-error-handler/node_modules/mout/src/array/reject.js new file mode 100644 index 000000000..cad403846 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/reject.js @@ -0,0 +1,25 @@ +define(['../function/makeIterator_'], function(makeIterator) { + + /** + * Array reject + */ + function reject(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var results = []; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + value = arr[i]; + if (!callback(value, i, arr)) { + results.push(value); + } + } + + return results; + } + + return reject; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/remove.js b/node_modules/express-error-handler/node_modules/mout/src/array/remove.js new file mode 100644 index 000000000..dec9134dc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/remove.js @@ -0,0 +1,13 @@ +define(['./indexOf'], function(indexOf){ + + /** + * Remove a single item from the array. + * (it won't remove duplicates, just a single item) + */ + function remove(arr, item){ + var idx = indexOf(arr, item); + if (idx !== -1) arr.splice(idx, 1); + } + + return remove; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/removeAll.js b/node_modules/express-error-handler/node_modules/mout/src/array/removeAll.js new file mode 100644 index 000000000..e81022b86 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/removeAll.js @@ -0,0 +1,15 @@ +define(['./indexOf'], function(indexOf){ + + /** + * Remove all instances of an item from array. + */ + function removeAll(arr, item){ + var idx = indexOf(arr, item); + while (idx !== -1) { + arr.splice(idx, 1); + idx = indexOf(arr, item, idx); + } + } + + return removeAll; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/shuffle.js b/node_modules/express-error-handler/node_modules/mout/src/array/shuffle.js new file mode 100644 index 000000000..891d16774 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/shuffle.js @@ -0,0 +1,28 @@ +define(['../random/randInt'], function (randInt) { + + /** + * Shuffle array items. + */ + function shuffle(arr) { + var results = [], + rnd; + if (arr == null) { + return results; + } + + var i = -1, len = arr.length, value; + while (++i < len) { + if (!i) { + results[0] = arr[0]; + } else { + rnd = randInt(0, i); + results[i] = results[rnd]; + results[rnd] = arr[i]; + } + } + + return results; + } + + return shuffle; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/some.js b/node_modules/express-error-handler/node_modules/mout/src/array/some.js new file mode 100644 index 000000000..e46a9781f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/some.js @@ -0,0 +1,27 @@ +define(['../function/makeIterator_'], function (makeIterator) { + + /** + * Array some + */ + function some(arr, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = false; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length; + while (++i < len) { + // we iterate over sparse items since there is no way to make it + // work properly on IE 7-8. see #64 + if ( callback(arr[i], i, arr) ) { + result = true; + break; + } + } + + return result; + } + + return some; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/sort.js b/node_modules/express-error-handler/node_modules/mout/src/array/sort.js new file mode 100644 index 000000000..4c1940423 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/sort.js @@ -0,0 +1,55 @@ +define(function () { + + /** + * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) + */ + function mergeSort(arr, compareFn) { + if (arr == null) { + return []; + } else if (arr.length < 2) { + return arr; + } + + if (compareFn == null) { + compareFn = defaultCompare; + } + + var mid, left, right; + + mid = ~~(arr.length / 2); + left = mergeSort( arr.slice(0, mid), compareFn ); + right = mergeSort( arr.slice(mid, arr.length), compareFn ); + + return merge(left, right, compareFn); + } + + function defaultCompare(a, b) { + return a < b ? -1 : (a > b? 1 : 0); + } + + function merge(left, right, compareFn) { + var result = []; + + while (left.length && right.length) { + if (compareFn(left[0], right[0]) <= 0) { + // if 0 it should preserve same order (stable) + result.push(left.shift()); + } else { + result.push(right.shift()); + } + } + + if (left.length) { + result.push.apply(result, left); + } + + if (right.length) { + result.push.apply(result, right); + } + + return result; + } + + return mergeSort; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/split.js b/node_modules/express-error-handler/node_modules/mout/src/array/split.js new file mode 100644 index 000000000..a17275eb9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/split.js @@ -0,0 +1,35 @@ +define(function() { + + /** + * Split array into a fixed number of segments. + */ + function split(array, segments) { + segments = segments || 2; + var results = []; + if (array == null) { + return results; + } + + var minLength = Math.floor(array.length / segments), + remainder = array.length % segments, + i = 0, + len = array.length, + segmentIndex = 0, + segmentLength; + + while (i < len) { + segmentLength = minLength; + if (segmentIndex < remainder) { + segmentLength++; + } + + results.push(array.slice(i, i + segmentLength)); + + segmentIndex++; + i += segmentLength; + } + + return results; + } + return split; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/toLookup.js b/node_modules/express-error-handler/node_modules/mout/src/array/toLookup.js new file mode 100644 index 000000000..aac8fd1d5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/toLookup.js @@ -0,0 +1,28 @@ +define(['../lang/isFunction'], function (isFunction) { + + /** + * Creates an object that holds a lookup for the objects in the array. + */ + function toLookup(arr, key) { + var result = {}; + if (arr == null) { + return result; + } + + var i = -1, len = arr.length, value; + if (isFunction(key)) { + while (++i < len) { + value = arr[i]; + result[key(value)] = value; + } + } else { + while (++i < len) { + value = arr[i]; + result[value[key]] = value; + } + } + + return result; + } + return toLookup; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/union.js b/node_modules/express-error-handler/node_modules/mout/src/array/union.js new file mode 100644 index 000000000..5f9922e52 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/union.js @@ -0,0 +1,18 @@ +define(['./unique', './append'], function (unique, append) { + + /** + * Concat multiple arrays and remove duplicates + */ + function union(arrs) { + var results = []; + var i = -1, len = arguments.length; + while (++i < len) { + append(results, arguments[i]); + } + + return unique(results); + } + + return union; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/unique.js b/node_modules/express-error-handler/node_modules/mout/src/array/unique.js new file mode 100644 index 000000000..c4bd23b42 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/unique.js @@ -0,0 +1,16 @@ +define(['./indexOf', './filter'], function(indexOf, filter){ + + /** + * @return {array} Array of unique items + */ + function unique(arr){ + return filter(arr, isUnique); + } + + function isUnique(item, i, arr){ + return indexOf(arr, item, i+1) === -1; + } + + return unique; +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/xor.js b/node_modules/express-error-handler/node_modules/mout/src/array/xor.js new file mode 100644 index 000000000..7df89d9c9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/xor.js @@ -0,0 +1,24 @@ +define(['./unique', './filter', './contains'], function (unique, filter, contains) { + + + /** + * Exclusive OR. Returns items that are present in a single array. + * - like ptyhon's `symmetric_difference` + */ + function xor(arr1, arr2) { + arr1 = unique(arr1); + arr2 = unique(arr2); + + var a1 = filter(arr1, function(item){ + return !contains(arr2, item); + }), + a2 = filter(arr2, function(item){ + return !contains(arr1, item); + }); + + return a1.concat(a2); + } + + return xor; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/array/zip.js b/node_modules/express-error-handler/node_modules/mout/src/array/zip.js new file mode 100644 index 000000000..bd0dbb846 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/array/zip.js @@ -0,0 +1,27 @@ +define(['./max', './map'], function (max, map) { + + function getLength(arr) { + return arr == null ? 0 : arr.length; + } + + /** + * Merges together the values of each of the arrays with the values at the + * corresponding position. + */ + function zip(arr){ + var len = arr ? max(map(arguments, getLength)) : 0, + results = [], + i = -1; + while (++i < len) { + // jshint loopfunc: true + results.push(map(arguments, function(item) { + return item == null ? undefined : item[i]; + })); + } + + return results; + } + + return zip; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection.js b/node_modules/express-error-handler/node_modules/mout/src/collection.js new file mode 100644 index 000000000..386e6da94 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection.js @@ -0,0 +1,22 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'contains' : require('./collection/contains'), + 'every' : require('./collection/every'), + 'filter' : require('./collection/filter'), + 'find' : require('./collection/find'), + 'forEach' : require('./collection/forEach'), + 'make_' : require('./collection/make_'), + 'map' : require('./collection/map'), + 'max' : require('./collection/max'), + 'min' : require('./collection/min'), + 'pluck' : require('./collection/pluck'), + 'reduce' : require('./collection/reduce'), + 'reject' : require('./collection/reject'), + 'size' : require('./collection/size'), + 'some' : require('./collection/some') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/contains.js b/node_modules/express-error-handler/node_modules/mout/src/collection/contains.js new file mode 100644 index 000000000..192167e8e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/contains.js @@ -0,0 +1,7 @@ +define(['./make_', '../array/contains', '../object/contains'], function (make, arrContains, objContains) { + + /** + */ + return make(arrContains, objContains); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/every.js b/node_modules/express-error-handler/node_modules/mout/src/collection/every.js new file mode 100644 index 000000000..6317f5032 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/every.js @@ -0,0 +1,7 @@ +define(['./make_', '../array/every', '../object/every'], function (make, arrEvery, objEvery) { + + /** + */ + return make(arrEvery, objEvery); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/filter.js b/node_modules/express-error-handler/node_modules/mout/src/collection/filter.js new file mode 100644 index 000000000..4e7fadc8b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/filter.js @@ -0,0 +1,22 @@ +define(['./forEach', '../function/makeIterator_'], function (forEach, makeIterator) { + + /** + * filter collection values, returns array. + */ + function filter(list, iterator, thisObj) { + iterator = makeIterator(iterator, thisObj); + var results = []; + if (!list) { + return results; + } + forEach(list, function(value, index, list) { + if (iterator(value, index, list)) { + results[results.length] = value; + } + }); + return results; + } + + return filter; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/find.js b/node_modules/express-error-handler/node_modules/mout/src/collection/find.js new file mode 100644 index 000000000..681f9414c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/find.js @@ -0,0 +1,8 @@ +define(['./make_', '../array/find', '../object/find'], function(make, arrFind, objFind) { + + /** + * Find value that returns true on iterator check. + */ + return make(arrFind, objFind); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/forEach.js b/node_modules/express-error-handler/node_modules/mout/src/collection/forEach.js new file mode 100644 index 000000000..3b39d3ed3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/forEach.js @@ -0,0 +1,7 @@ +define(['./make_', '../array/forEach', '../object/forOwn'], function (make, arrForEach, objForEach) { + + /** + */ + return make(arrForEach, objForEach); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/make_.js b/node_modules/express-error-handler/node_modules/mout/src/collection/make_.js new file mode 100644 index 000000000..312e0564b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/make_.js @@ -0,0 +1,19 @@ +define(function(){ + + /** + * internal method used to create other collection modules. + */ + function makeCollectionMethod(arrMethod, objMethod, defaultReturn) { + return function(){ + var args = Array.prototype.slice.call(arguments); + if (args[0] == null) { + return defaultReturn; + } + // array-like is treated as array + return (typeof args[0].length === 'number')? arrMethod.apply(null, args) : objMethod.apply(null, args); + }; + } + + return makeCollectionMethod; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/map.js b/node_modules/express-error-handler/node_modules/mout/src/collection/map.js new file mode 100644 index 000000000..96e249875 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/map.js @@ -0,0 +1,20 @@ +define(['../lang/isObject', '../object/values', '../array/map', '../function/makeIterator_'], function (isObject, values, arrMap, makeIterator) { + + /** + * Map collection values, returns Array. + */ + function map(list, callback, thisObj) { + callback = makeIterator(callback, thisObj); + // list.length to check array-like object, if not array-like + // we simply map all the object values + if( isObject(list) && list.length == null ){ + list = values(list); + } + return arrMap(list, function (val, key, list) { + return callback(val, key, list); + }); + } + + return map; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/max.js b/node_modules/express-error-handler/node_modules/mout/src/collection/max.js new file mode 100644 index 000000000..de9a6da55 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/max.js @@ -0,0 +1,8 @@ +define(['./make_', '../array/max', '../object/max'], function (make, arrMax, objMax) { + + /** + * Get maximum value inside collection + */ + return make(arrMax, objMax); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/min.js b/node_modules/express-error-handler/node_modules/mout/src/collection/min.js new file mode 100644 index 000000000..f0c239a6e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/min.js @@ -0,0 +1,8 @@ +define(['./make_', '../array/min', '../object/min'], function (make, arrMin, objMin) { + + /** + * Get minimum value inside collection. + */ + return make(arrMin, objMin); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/pluck.js b/node_modules/express-error-handler/node_modules/mout/src/collection/pluck.js new file mode 100644 index 000000000..ef784a7a2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/pluck.js @@ -0,0 +1,14 @@ +define(['./map'], function (map) { + + /** + * Extract a list of property values. + */ + function pluck(list, key) { + return map(list, function(value) { + return value[key]; + }); + } + + return pluck; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/reduce.js b/node_modules/express-error-handler/node_modules/mout/src/collection/reduce.js new file mode 100644 index 000000000..bd05d43d7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/reduce.js @@ -0,0 +1,7 @@ +define(['./make_', '../array/reduce', '../object/reduce'], function (make, arrReduce, objReduce) { + + /** + */ + return make(arrReduce, objReduce); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/reject.js b/node_modules/express-error-handler/node_modules/mout/src/collection/reject.js new file mode 100644 index 000000000..581adfdc5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/reject.js @@ -0,0 +1,15 @@ +define(['./filter', '../function/makeIterator_'], function (filter, makeIterator) { + + /** + * Inverse or collection/filter + */ + function reject(list, iterator, thisObj) { + iterator = makeIterator(iterator, thisObj); + return filter(list, function(value, index, list) { + return !iterator(value, index, list); + }, thisObj); + } + + return reject; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/size.js b/node_modules/express-error-handler/node_modules/mout/src/collection/size.js new file mode 100644 index 000000000..4e5ab419f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/size.js @@ -0,0 +1,18 @@ +define(['../lang/isArray', '../object/size'], function (isArray, objSize) { + + /** + * Get collection size + */ + function size(list) { + if (!list) { + return 0; + } + if (isArray(list)) { + return list.length; + } + return objSize(list); + } + + return size; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/collection/some.js b/node_modules/express-error-handler/node_modules/mout/src/collection/some.js new file mode 100644 index 000000000..c0aebee2b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/collection/some.js @@ -0,0 +1,7 @@ +define(['./make_', '../array/some', '../object/some'], function (make, arrSome, objSome) { + + /** + */ + return make(arrSome, objSome); + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date.js b/node_modules/express-error-handler/node_modules/mout/src/date.js new file mode 100644 index 000000000..4d449150c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date.js @@ -0,0 +1,21 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'dayOfTheYear' : require('./date/dayOfTheYear'), + 'diff' : require('./date/diff'), + 'i18n_' : require('./date/i18n_'), + 'isLeapYear' : require('./date/isLeapYear'), + 'isSame' : require('./date/isSame'), + 'parseIso' : require('./date/parseIso'), + 'startOf' : require('./date/startOf'), + 'strftime' : require('./date/strftime'), + 'timezoneAbbr' : require('./date/timezoneAbbr'), + 'timezoneOffset' : require('./date/timezoneOffset'), + 'totalDaysInMonth' : require('./date/totalDaysInMonth'), + 'totalDaysInYear' : require('./date/totalDaysInYear'), + 'weekOfTheYear' : require('./date/weekOfTheYear') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/dayOfTheYear.js b/node_modules/express-error-handler/node_modules/mout/src/date/dayOfTheYear.js new file mode 100644 index 000000000..dc77ae1b2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/dayOfTheYear.js @@ -0,0 +1,13 @@ +define(['../lang/isDate'], function (isDate) { + + /** + * return the day of the year (1..366) + */ + function dayOfTheYear(date){ + return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - + Date.UTC(date.getFullYear(), 0, 1)) / 86400000 + 1; + } + + return dayOfTheYear; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/diff.js b/node_modules/express-error-handler/node_modules/mout/src/date/diff.js new file mode 100644 index 000000000..667165fe4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/diff.js @@ -0,0 +1,128 @@ +define(['./totalDaysInMonth', './totalDaysInYear', '../time/convert'], function(totalDaysInMonth, totalDaysInYear, convert){ + + /** + * calculate the difference between dates (range) + */ + function diff(start, end, unitName){ + // sort the dates to make it easier to process (specially year/month) + if (start > end) { + var swap = start; + start = end; + end = swap; + } + + var output; + + if (unitName === 'month') { + output = getMonthsDiff(start, end); + } else if (unitName === 'year'){ + output = getYearsDiff(start, end); + } else if (unitName != null) { + if (unitName === 'day') { + // ignore timezone difference because of daylight savings time + start = toUtc(start); + end = toUtc(end); + } + output = convert(end - start, 'ms', unitName); + } else { + output = end - start; + } + + return output; + } + + + function toUtc(d){ + // we ignore timezone differences on purpose because of daylight + // savings time, otherwise it would return fractional days/weeks even + // if a full day elapsed. eg: + // Wed Feb 12 2014 00:00:00 GMT-0200 (BRST) + // Sun Feb 16 2014 00:00:00 GMT-0300 (BRT) + // diff should be 4 days and not 4.041666666666667 + return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), + d.getHours(), d.getMinutes(), d.getSeconds(), + d.getMilliseconds()); + } + + + function getMonthsDiff(start, end){ + return getElapsedMonths(start, end) + + getElapsedYears(start, end) * 12 + + getFractionalMonth(start, end); + } + + + function getYearsDiff(start, end){ + var elapsedYears = getElapsedYears(start, end); + return elapsedYears + getFractionalYear(start, end, elapsedYears); + } + + + function getElapsedMonths(start, end){ + var monthDiff = end.getMonth() - start.getMonth(); + if (monthDiff < 0) { + monthDiff += 12; + } + // less than a full month + if (start.getDate() > end.getDate()) { + monthDiff -= 1; + } + return monthDiff; + } + + + function getElapsedYears(start, end){ + var yearDiff = end.getFullYear() - start.getFullYear(); + // less than a full year + if (start.getMonth() > end.getMonth()) { + yearDiff -= 1; + } + return yearDiff; + } + + + function getFractionalMonth(start, end){ + var fractionalDiff = 0; + var startDay = start.getDate(); + var endDay = end.getDate(); + + if (startDay !== endDay) { + var startTotalDays = totalDaysInMonth(start); + var endTotalDays = totalDaysInMonth(end); + var totalDays; + var daysElapsed; + + if (startDay > endDay) { + // eg: Jan 29 - Feb 27 (29 days elapsed but not a full month) + var baseDay = startTotalDays - startDay; + daysElapsed = endDay + baseDay; + // total days should be relative to 1st day of next month if + // startDay > endTotalDays + totalDays = (startDay > endTotalDays)? + endTotalDays + baseDay + 1 : startDay + baseDay; + } else { + // fractional is only based on endMonth eg: Jan 12 - Feb 18 + // (6 fractional days, 28 days until next full month) + daysElapsed = endDay - startDay; + totalDays = endTotalDays; + } + + fractionalDiff = daysElapsed / totalDays; + } + + return fractionalDiff; + } + + + function getFractionalYear(start, end, elapsedYears){ + var base = elapsedYears? + new Date(end.getFullYear(), start.getMonth(), start.getDate()) : + start; + var elapsedDays = diff(base, end, 'day'); + return elapsedDays / totalDaysInYear(end); + } + + + return diff; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/i18n/de-DE.js b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/de-DE.js new file mode 100644 index 000000000..46f5c6aa5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/de-DE.js @@ -0,0 +1,61 @@ +define(function(){ + // de-DE (German) + return { + "am" : "", + "pm" : "", + + "x": "%d/%m/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %H:%M:%S %Z", + + "months" : [ + "Januar", + "Februar", + "März", + "April", + "Mai", + "Juni", + "Juli", + "August", + "September", + "Oktober", + "November", + "Dezember" + ], + + "months_abbr" : [ + "Jan", + "Febr", + "März", + "Apr", + "Mai", + "Juni", + "Juli", + "Aug", + "Sept", + "Okt", + "Nov", + "Dez" + ], + + "days" : [ + "Sonntag", + "Montag", + "Dienstag", + "Mittwoch", + "Donnerstag", + "Freitag", + "Samstag" + ], + + "days_abbr" : [ + "So", + "Mo", + "Di", + "Mi", + "Do", + "Fr", + "Sa" + ] + }; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/i18n/en-US.js b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/en-US.js new file mode 100644 index 000000000..5e640c225 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/en-US.js @@ -0,0 +1,61 @@ +define(function(){ + // en-US (English, United States) + return { + "am" : "AM", + "pm" : "PM", + + "x": "%m/%d/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %I:%M:%S %p %Z", + + "months" : [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + + "months_abbr" : [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + + "days" : [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + + "days_abbr" : [ + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat" + ] + }; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/i18n/pt-BR.js b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/pt-BR.js new file mode 100644 index 000000000..47256dd2a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/i18n/pt-BR.js @@ -0,0 +1,61 @@ +define(function(){ + // pt-BR (Brazillian Portuguese) + return { + "am" : "", + "pm" : "", + + "x": "%d/%m/%y", + "X": "%H:%M:%S", + "c": "%a %d %b %Y %H:%M:%S %Z", + + "months" : [ + "Janeiro", + "Fevereiro", + "Março", + "Abril", + "Maio", + "Junho", + "Julho", + "Agosto", + "Setembro", + "Outubro", + "Novembro", + "Dezembro" + ], + + "months_abbr" : [ + "Jan", + "Fev", + "Mar", + "Abr", + "Mai", + "Jun", + "Jul", + "Ago", + "Set", + "Out", + "Nov", + "Dez" + ], + + "days" : [ + "Domingo", + "Segunda", + "Terça", + "Quarta", + "Quinta", + "Sexta", + "Sábado" + ], + + "days_abbr" : [ + "Dom", + "Seg", + "Ter", + "Qua", + "Qui", + "Sex", + "Sáb" + ] + }; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/i18n_.js b/node_modules/express-error-handler/node_modules/mout/src/date/i18n_.js new file mode 100644 index 000000000..c04ce8852 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/i18n_.js @@ -0,0 +1,13 @@ +define(['../object/mixIn', './i18n/en-US'], function(mixIn, enUS){ + + // we also use mixIn to make sure we don't affect the original locale + var activeLocale = mixIn({}, enUS, { + // we expose a "set" method to allow overriding the global locale + set : function(localeData){ + mixIn(activeLocale, localeData); + } + }); + + return activeLocale; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/isLeapYear.js b/node_modules/express-error-handler/node_modules/mout/src/date/isLeapYear.js new file mode 100644 index 000000000..e400b43dc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/isLeapYear.js @@ -0,0 +1,15 @@ +define(['../lang/isDate'], function (isDate) { + + /** + * checks if it's a leap year + */ + function isLeapYear(fullYear){ + if (isDate(fullYear)) { + fullYear = fullYear.getFullYear(); + } + return fullYear % 400 === 0 || (fullYear % 100 !== 0 && fullYear % 4 === 0); + } + + return isLeapYear; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/isSame.js b/node_modules/express-error-handler/node_modules/mout/src/date/isSame.js new file mode 100644 index 000000000..f30531fc7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/isSame.js @@ -0,0 +1,16 @@ +define(['./startOf'], function (startOf) { + + /** + * Check if date is "same" with optional period + */ + function isSame(date1, date2, period){ + if (period) { + date1 = startOf(date1, period); + date2 = startOf(date2, period); + } + return Number(date1) === Number(date2); + } + + return isSame; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/parseIso.js b/node_modules/express-error-handler/node_modules/mout/src/date/parseIso.js new file mode 100644 index 000000000..b21c87977 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/parseIso.js @@ -0,0 +1,146 @@ +define(['../array/some'], function (some) { + + var datePatterns = [ + /^([0-9]{4})$/, // YYYY + /^([0-9]{4})-([0-9]{2})$/, // YYYY-MM (YYYYMM not allowed) + /^([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/ // YYYY-MM-DD or YYYYMMDD + ]; + var ORD_DATE = /^([0-9]{4})-?([0-9]{3})$/; // YYYY-DDD + + var timePatterns = [ + /^([0-9]{2}(?:\.[0-9]*)?)$/, // HH.hh + /^([0-9]{2}):?([0-9]{2}(?:\.[0-9]*)?)$/, // HH:MM.mm + /^([0-9]{2}):?([0-9]{2}):?([0-9]{2}(\.[0-9]*)?)$/ // HH:MM:SS.ss + ]; + + var DATE_TIME = /^(.+)T(.+)$/; + var TIME_ZONE = /^(.+)([+\-])([0-9]{2}):?([0-9]{2})$/; + + function matchAll(str, patterns) { + var match; + var found = some(patterns, function(pattern) { + return !!(match = pattern.exec(str)); + }); + + return found ? match : null; + } + + function getDate(year, month, day) { + var date = new Date(Date.UTC(year, month, day)); + + // Explicitly set year to avoid Date.UTC making dates < 100 relative to + // 1900 + date.setUTCFullYear(year); + + var valid = + date.getUTCFullYear() === year && + date.getUTCMonth() === month && + date.getUTCDate() === day; + return valid ? +date : NaN; + } + + function parseOrdinalDate(str) { + var match = ORD_DATE.exec(str); + if (match ) { + var year = +match[1], + day = +match[2], + date = new Date(Date.UTC(year, 0, day)); + + if (date.getUTCFullYear() === year) { + return +date; + } + } + + return NaN; + } + + function parseDate(str) { + var match, year, month, day; + + match = matchAll(str, datePatterns); + if (match === null) { + // Ordinal dates are verified differently. + return parseOrdinalDate(str); + } + + year = (match[1] === void 0) ? 0 : +match[1]; + month = (match[2] === void 0) ? 0 : +match[2] - 1; + day = (match[3] === void 0) ? 1 : +match[3]; + + return getDate(year, month, day); + } + + function getTime(hr, min, sec) { + var valid = + (hr < 24 && hr >= 0 && + min < 60 && min >= 0 && + sec < 60 && min >= 0) || + (hr === 24 && min === 0 && sec === 0); + if (!valid) { + return NaN; + } + + return ((hr * 60 + min) * 60 + sec) * 1000; + } + + function parseOffset(str) { + var match; + if (str.charAt(str.length - 1) === 'Z') { + str = str.substring(0, str.length - 1); + } else { + match = TIME_ZONE.exec(str); + if (match) { + var hours = +match[3], + minutes = (match[4] === void 0) ? 0 : +match[4], + offset = getTime(hours, minutes, 0); + + if (match[2] === '-') { + offset *= -1; + } + + return { offset: offset, time: match[1] }; + } + } + + // No time zone specified, assume UTC + return { offset: 0, time: str }; + } + + function parseTime(str) { + var match; + var offset = parseOffset(str); + + str = offset.time; + offset = offset.offset; + if (isNaN(offset)) { + return NaN; + } + + match = matchAll(str, timePatterns); + if (match === null) { + return NaN; + } + + var hours = (match[1] === void 0) ? 0 : +match[1], + minutes = (match[2] === void 0) ? 0 : +match[2], + seconds = (match[3] === void 0) ? 0 : +match[3]; + + return getTime(hours, minutes, seconds) - offset; + } + + /** + * Parse an ISO8601 formatted date string, and return a Date object. + */ + function parseISO8601(str){ + var match = DATE_TIME.exec(str); + if (!match) { + // No time specified + return parseDate(str); + } + + return parseDate(match[1]) + parseTime(match[2]); + } + + return parseISO8601; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/startOf.js b/node_modules/express-error-handler/node_modules/mout/src/date/startOf.js new file mode 100644 index 000000000..747f114d3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/startOf.js @@ -0,0 +1,54 @@ +define(['../lang/clone'], function (clone) { + + /** + * get a new Date object representing start of period + */ + function startOf(date, period){ + date = clone(date); + + // intentionally removed "break" from switch since start of + // month/year/etc should also reset the following periods + switch (period) { + case 'year': + date.setMonth(0); + /* falls through */ + case 'month': + date.setDate(1); + /* falls through */ + case 'week': + case 'day': + date.setHours(0); + /* falls through */ + case 'hour': + date.setMinutes(0); + /* falls through */ + case 'minute': + date.setSeconds(0); + /* falls through */ + case 'second': + date.setMilliseconds(0); + break; + default: + throw new Error('"'+ period +'" is not a valid period'); + } + + // week is the only case that should reset the weekDay and maybe even + // overflow to previous month + if (period === 'week') { + var weekDay = date.getDay(); + var baseDate = date.getDate(); + if (weekDay) { + if (weekDay >= baseDate) { + //start of the week is on previous month + date.setDate(0); + } + date.setDate(date.getDate() - date.getDay()); + } + } + + return date; + } + + return startOf; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/strftime.js b/node_modules/express-error-handler/node_modules/mout/src/date/strftime.js new file mode 100644 index 000000000..dd7825051 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/strftime.js @@ -0,0 +1,113 @@ +define(['../number/pad', './i18n_', './dayOfTheYear', './timezoneOffset', './timezoneAbbr', './weekOfTheYear'], function (pad, i18n, dayOfTheYear, timezoneOffset, timezoneAbbr, weekOfTheYear) { + + var _combinations = { + 'D': '%m/%d/%y', + 'F': '%Y-%m-%d', + 'r': '%I:%M:%S %p', + 'R': '%H:%M', + 'T': '%H:%M:%S', + 'x': 'locale', + 'X': 'locale', + 'c': 'locale' + }; + + + /** + * format date based on strftime format + */ + function strftime(date, format, localeData){ + localeData = localeData || i18n; + var reToken = /%([a-z%])/gi; + + function makeIterator(fn) { + return function(match, token){ + return fn(date, token, localeData); + }; + } + + return format + .replace(reToken, makeIterator(expandCombinations)) + .replace(reToken, makeIterator(convertToken)); + } + + + function expandCombinations(date, token, l10n){ + if (token in _combinations) { + var expanded = _combinations[token]; + return expanded === 'locale'? l10n[token] : expanded; + } else { + return '%'+ token; + } + } + + + function convertToken(date, token, l10n){ + switch (token){ + case 'a': + return l10n.days_abbr[date.getDay()]; + case 'A': + return l10n.days[date.getDay()]; + case 'h': + case 'b': + return l10n.months_abbr[date.getMonth()]; + case 'B': + return l10n.months[date.getMonth()]; + case 'C': + return pad(Math.floor(date.getFullYear() / 100), 2); + case 'd': + return pad(date.getDate(), 2); + case 'e': + return pad(date.getDate(), 2, ' '); + case 'H': + return pad(date.getHours(), 2); + case 'I': + return pad(date.getHours() % 12, 2); + case 'j': + return pad(dayOfTheYear(date), 3); + case 'L': + return pad(date.getMilliseconds(), 3); + case 'm': + return pad(date.getMonth() + 1, 2); + case 'M': + return pad(date.getMinutes(), 2); + case 'n': + return '\n'; + case 'p': + return date.getHours() >= 12? l10n.pm : l10n.am; + case 'P': + return convertToken(date, 'p', l10n).toLowerCase(); + case 's': + return date.getTime() / 1000; + case 'S': + return pad(date.getSeconds(), 2); + case 't': + return '\t'; + case 'u': + var day = date.getDay(); + return day === 0? 7 : day; + case 'U': + return pad(weekOfTheYear(date), 2); + case 'w': + return date.getDay(); + case 'W': + return pad(weekOfTheYear(date, 1), 2); + case 'y': + return pad(date.getFullYear() % 100, 2); + case 'Y': + return pad(date.getFullYear(), 4); + case 'z': + return timezoneOffset(date); + case 'Z': + return timezoneAbbr(date); + case '%': + return '%'; + default: + // keep unrecognized tokens + return '%'+ token; + } + } + + + return strftime; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/timezoneAbbr.js b/node_modules/express-error-handler/node_modules/mout/src/date/timezoneAbbr.js new file mode 100644 index 000000000..225a6856d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/timezoneAbbr.js @@ -0,0 +1,17 @@ +define(['./timezoneOffset'], function(timezoneOffset) { + + /** + * Abbreviated time zone name or similar information. + */ + function timezoneAbbr(date){ + // Date.toString gives different results depending on the + // browser/system so we fallback to timezone offset + // chrome: 'Mon Apr 08 2013 09:02:04 GMT-0300 (BRT)' + // IE: 'Mon Apr 8 09:02:04 UTC-0300 2013' + var tz = /\(([A-Z]{3,4})\)/.exec(date.toString()); + return tz? tz[1] : timezoneOffset(date); + } + + return timezoneAbbr; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/timezoneOffset.js b/node_modules/express-error-handler/node_modules/mout/src/date/timezoneOffset.js new file mode 100644 index 000000000..ca06705de --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/timezoneOffset.js @@ -0,0 +1,16 @@ +define(['../number/pad'], function (pad) { + + /** + * time zone as hour and minute offset from UTC (e.g. +0900) + */ + function timezoneOffset(date){ + var offset = date.getTimezoneOffset(); + var abs = Math.abs(offset); + var h = pad(Math.floor(abs / 60), 2); + var m = pad(abs % 60, 2); + return (offset > 0? '-' : '+') + h + m; + } + + return timezoneOffset; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInMonth.js b/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInMonth.js new file mode 100644 index 000000000..98f7e9d14 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInMonth.js @@ -0,0 +1,24 @@ +define(['../lang/isDate', './isLeapYear'], function (isDate, isLeapYear) { + + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + /** + * returns the total amount of days in the month (considering leap years) + */ + function totalDaysInMonth(fullYear, monthIndex){ + if (isDate(fullYear)) { + var date = fullYear; + year = date.getFullYear(); + monthIndex = date.getMonth(); + } + + if (monthIndex === 1 && isLeapYear(fullYear)) { + return 29; + } else { + return DAYS_IN_MONTH[monthIndex]; + } + } + + return totalDaysInMonth; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInYear.js b/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInYear.js new file mode 100644 index 000000000..e9036b42d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/totalDaysInYear.js @@ -0,0 +1,13 @@ +define(['./isLeapYear'], function (isLeapYear) { + + /** + * return the amount of days in the year following the gregorian calendar + * and leap years + */ + function totalDaysInYear(fullYear){ + return isLeapYear(fullYear)? 366 : 365; + } + + return totalDaysInYear; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/date/weekOfTheYear.js b/node_modules/express-error-handler/node_modules/mout/src/date/weekOfTheYear.js new file mode 100644 index 000000000..8dabc458e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/date/weekOfTheYear.js @@ -0,0 +1,16 @@ +define(['./dayOfTheYear'], function (dayOfTheYear) { + + /** + * Return the week of the year based on given firstDayOfWeek + */ + function weekOfTheYear(date, firstDayOfWeek){ + firstDayOfWeek = firstDayOfWeek == null? 0 : firstDayOfWeek; + var doy = dayOfTheYear(date); + var dow = (7 + date.getDay() - firstDayOfWeek) % 7; + var relativeWeekDay = 6 - firstDayOfWeek - dow; + return Math.floor((doy + relativeWeekDay) / 7); + } + + return weekOfTheYear; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function.js b/node_modules/express-error-handler/node_modules/mout/src/function.js new file mode 100644 index 000000000..713072461 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function.js @@ -0,0 +1,19 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'bind' : require('./function/bind'), + 'compose' : require('./function/compose'), + 'debounce' : require('./function/debounce'), + 'func' : require('./function/func'), + 'makeIterator_' : require('./function/makeIterator_'), + 'partial' : require('./function/partial'), + 'prop' : require('./function/prop'), + 'series' : require('./function/series'), + 'throttle' : require('./function/throttle'), + 'timeout' : require('./function/timeout'), + 'times' : require('./function/times') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/bind.js b/node_modules/express-error-handler/node_modules/mout/src/function/bind.js new file mode 100644 index 000000000..09e5e20ad --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/bind.js @@ -0,0 +1,23 @@ +define(function(){ + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Return a function that will execute in the given context, optionally adding any additional supplied parameters to the beginning of the arguments collection. + * @param {Function} fn Function. + * @param {object} context Execution context. + * @param {rest} args Arguments (0...n arguments). + * @return {Function} Wrapped Function. + */ + function bind(fn, context, args){ + var argsArr = slice(arguments, 2); //curried args + return function(){ + return fn.apply(context, argsArr.concat(slice(arguments))); + }; + } + + return bind; +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/compose.js b/node_modules/express-error-handler/node_modules/mout/src/function/compose.js new file mode 100644 index 000000000..d8b228fa6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/compose.js @@ -0,0 +1,23 @@ +define(function () { + + /** + * Returns a function that composes multiple functions, passing results to + * each other. + */ + function compose() { + var fns = arguments; + return function(arg){ + // only cares about the first argument since the chain can only + // deal with a single return value anyway. It should start from + // the last fn. + var n = fns.length; + while (n--) { + arg = fns[n].call(this, arg); + } + return arg; + }; + } + + return compose; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/debounce.js b/node_modules/express-error-handler/node_modules/mout/src/function/debounce.js new file mode 100644 index 000000000..8c5fd47fc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/debounce.js @@ -0,0 +1,32 @@ +define(function () { + + /** + * Debounce callback execution + */ + function debounce(fn, threshold, isAsap){ + var timeout, result; + function debounced(){ + var args = arguments, context = this; + function delayed(){ + if (! isAsap) { + result = fn.apply(context, args); + } + timeout = null; + } + if (timeout) { + clearTimeout(timeout); + } else if (isAsap) { + result = fn.apply(context, args); + } + timeout = setTimeout(delayed, threshold); + return result; + } + debounced.cancel = function(){ + clearTimeout(timeout); + }; + return debounced; + } + + return debounce; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/func.js b/node_modules/express-error-handler/node_modules/mout/src/function/func.js new file mode 100644 index 000000000..b920e00e8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/func.js @@ -0,0 +1,14 @@ +define(function () { + + /** + * Returns a function that call a method on the passed object + */ + function func(name){ + return function(obj){ + return obj[name](); + }; + } + + return func; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/makeIterator_.js b/node_modules/express-error-handler/node_modules/mout/src/function/makeIterator_.js new file mode 100644 index 000000000..c498e1319 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/makeIterator_.js @@ -0,0 +1,30 @@ +define(['./prop', '../object/deepMatches'], function(prop, deepMatches) { + + /** + * Converts argument into a valid iterator. + * Used internally on most array/object/collection methods that receives a + * callback/iterator providing a shortcut syntax. + */ + function makeIterator(src, thisObj){ + switch(typeof src) { + case 'function': + // function is the first to improve perf (most common case) + return (typeof thisObj !== 'undefined')? function(val, i, arr){ + return src.call(thisObj, val, i, arr); + } : src; + case 'object': + // typeof null == "object" + return (src != null)? function(val){ + return deepMatches(val, src); + } : src; + case 'string': + case 'number': + return prop(src); + default: + return src; + } + } + + return makeIterator; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/partial.js b/node_modules/express-error-handler/node_modules/mout/src/function/partial.js new file mode 100644 index 000000000..ad730746b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/partial.js @@ -0,0 +1,19 @@ +define(function () { + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Creates a partially applied function. + */ + function partial(fn, var_args){ + var argsArr = slice(arguments, 1); //curried args + return function(){ + return fn.apply(this, argsArr.concat(slice(arguments))); + }; + } + + return partial; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/prop.js b/node_modules/express-error-handler/node_modules/mout/src/function/prop.js new file mode 100644 index 000000000..c9df78ca0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/prop.js @@ -0,0 +1,14 @@ +define(function () { + + /** + * Returns a function that gets a property of the passed object + */ + function prop(name){ + return function(obj){ + return obj[name]; + }; + } + + return prop; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/series.js b/node_modules/express-error-handler/node_modules/mout/src/function/series.js new file mode 100644 index 000000000..c8856a277 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/series.js @@ -0,0 +1,22 @@ +define(function () { + + /** + * Returns a function that will execute a list of functions in sequence + * passing the same arguments to each one. (useful for batch processing + * items during a forEach loop) + */ + function series(){ + var fns = arguments; + return function(){ + var i = 0, + n = fns.length; + while (i < n) { + fns[i].apply(this, arguments); + i += 1; + } + }; + } + + return series; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/throttle.js b/node_modules/express-error-handler/node_modules/mout/src/function/throttle.js new file mode 100644 index 000000000..1885fc6a6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/throttle.js @@ -0,0 +1,35 @@ +define(['../time/now'], function (now) { + + /** + */ + function throttle(fn, delay){ + var context, timeout, result, args, + cur, diff, prev = 0; + function delayed(){ + prev = now(); + timeout = null; + result = fn.apply(context, args); + } + function throttled(){ + context = this; + args = arguments; + cur = now(); + diff = delay - (cur - prev); + if (diff <= 0) { + clearTimeout(timeout); + prev = cur; + result = fn.apply(context, args); + } else if (! timeout) { + timeout = setTimeout(delayed, diff); + } + return result; + } + throttled.cancel = function(){ + clearTimeout(timeout); + }; + return throttled; + } + + return throttle; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/timeout.js b/node_modules/express-error-handler/node_modules/mout/src/function/timeout.js new file mode 100644 index 000000000..15388bdd3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/timeout.js @@ -0,0 +1,21 @@ +define(function () { + + function slice(arr, offset){ + return Array.prototype.slice.call(arr, offset || 0); + } + + /** + * Delays the call of a function within a given context. + */ + function timeout(fn, millis, context){ + + var args = slice(arguments, 3); + + return setTimeout(function() { + fn.apply(context, args); + }, millis); + } + + return timeout; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/function/times.js b/node_modules/express-error-handler/node_modules/mout/src/function/times.js new file mode 100644 index 000000000..ec10caeb4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/function/times.js @@ -0,0 +1,17 @@ +define(function () { + + /** + * Iterates over a callback a set amount of times + */ + function times(n, callback, thisObj){ + var i = -1; + while (++i < n) { + if ( callback.call(thisObj, i) === false ) { + break; + } + } + } + + return times; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/index.js b/node_modules/express-error-handler/node_modules/mout/src/index.js new file mode 100644 index 000000000..3098aff68 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/index.js @@ -0,0 +1,25 @@ +/**@license + * mout v0.7.1 | http://moutjs.com | MIT license + */ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'VERSION' : '0.7.1', + 'array' : require('./array'), + 'collection' : require('./collection'), + 'date' : require('./date'), + 'function' : require('./function'), + 'lang' : require('./lang'), + 'math' : require('./math'), + 'number' : require('./number'), + 'object' : require('./object'), + 'queryString' : require('./queryString'), + 'random' : require('./random'), + 'string' : require('./string'), + 'time' : require('./time'), + 'fn' : require('./function') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang.js b/node_modules/express-error-handler/node_modules/mout/src/lang.js new file mode 100644 index 000000000..434916a72 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang.js @@ -0,0 +1,37 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'clone' : require('./lang/clone'), + 'createObject' : require('./lang/createObject'), + 'ctorApply' : require('./lang/ctorApply'), + 'deepClone' : require('./lang/deepClone'), + 'defaults' : require('./lang/defaults'), + 'inheritPrototype' : require('./lang/inheritPrototype'), + 'is' : require('./lang/is'), + 'isArguments' : require('./lang/isArguments'), + 'isArray' : require('./lang/isArray'), + 'isBoolean' : require('./lang/isBoolean'), + 'isDate' : require('./lang/isDate'), + 'isEmpty' : require('./lang/isEmpty'), + 'isFinite' : require('./lang/isFinite'), + 'isFunction' : require('./lang/isFunction'), + 'isInteger' : require('./lang/isInteger'), + 'isKind' : require('./lang/isKind'), + 'isNaN' : require('./lang/isNaN'), + 'isNull' : require('./lang/isNull'), + 'isNumber' : require('./lang/isNumber'), + 'isObject' : require('./lang/isObject'), + 'isPlainObject' : require('./lang/isPlainObject'), + 'isRegExp' : require('./lang/isRegExp'), + 'isString' : require('./lang/isString'), + 'isUndefined' : require('./lang/isUndefined'), + 'isnt' : require('./lang/isnt'), + 'kindOf' : require('./lang/kindOf'), + 'toArray' : require('./lang/toArray'), + 'toNumber' : require('./lang/toNumber'), + 'toString' : require('./lang/toString') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/clone.js b/node_modules/express-error-handler/node_modules/mout/src/lang/clone.js new file mode 100644 index 000000000..468489a11 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/clone.js @@ -0,0 +1,47 @@ +define(['./kindOf', './isPlainObject', '../object/mixIn'], function (kindOf, isPlainObject, mixIn) { + + /** + * Clone native types. + */ + function clone(val){ + switch (kindOf(val)) { + case 'Object': + return cloneObject(val); + case 'Array': + return cloneArray(val); + case 'RegExp': + return cloneRegExp(val); + case 'Date': + return cloneDate(val); + default: + return val; + } + } + + function cloneObject(source) { + if (isPlainObject(source)) { + return mixIn({}, source); + } else { + return source; + } + } + + function cloneRegExp(r) { + var flags = ''; + flags += r.multiline ? 'm' : ''; + flags += r.global ? 'g' : ''; + flags += r.ignorecase ? 'i' : ''; + return new RegExp(r.source, flags); + } + + function cloneDate(date) { + return new Date(+date); + } + + function cloneArray(arr) { + return arr.slice(); + } + + return clone; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/createObject.js b/node_modules/express-error-handler/node_modules/mout/src/lang/createObject.js new file mode 100644 index 000000000..f7661500e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/createObject.js @@ -0,0 +1,18 @@ +define(['../object/mixIn'], function(mixIn){ + + /** + * Create Object using prototypal inheritance and setting custom properties. + * - Mix between Douglas Crockford Prototypal Inheritance and the EcmaScript 5 `Object.create()` method. + * @param {object} parent Parent Object. + * @param {object} [props] Object properties. + * @return {object} Created object. + */ + function createObject(parent, props){ + function F(){} + F.prototype = parent; + return mixIn(new F(), props); + + } + return createObject; +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/ctorApply.js b/node_modules/express-error-handler/node_modules/mout/src/lang/ctorApply.js new file mode 100644 index 000000000..a9ac1c548 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/ctorApply.js @@ -0,0 +1,17 @@ +define(function () { + + function F(){} + + /** + * Do fn.apply on a constructor. + */ + function ctorApply(ctor, args) { + F.prototype = ctor.prototype; + var instance = new F(); + ctor.apply(instance, args); + return instance; + } + + return ctorApply; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/deepClone.js b/node_modules/express-error-handler/node_modules/mout/src/lang/deepClone.js new file mode 100644 index 000000000..d45c10aae --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/deepClone.js @@ -0,0 +1,45 @@ +define(['./clone', '../object/forOwn', './kindOf', './isPlainObject'], function (clone, forOwn, kindOf, isPlainObject) { + + /** + * Recursively clone native types. + */ + function deepClone(val, instanceClone) { + switch ( kindOf(val) ) { + case 'Object': + return cloneObject(val, instanceClone); + case 'Array': + return cloneArray(val, instanceClone); + default: + return clone(val); + } + } + + function cloneObject(source, instanceClone) { + if (isPlainObject(source)) { + var out = {}; + forOwn(source, function(val, key) { + this[key] = deepClone(val, instanceClone); + }, out); + return out; + } else if (instanceClone) { + return instanceClone(source); + } else { + return source; + } + } + + function cloneArray(arr, instanceClone) { + var out = [], + i = -1, + n = arr.length, + val; + while (++i < n) { + out[i] = deepClone(arr[i], instanceClone); + } + return out; + } + + return deepClone; + +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/defaults.js b/node_modules/express-error-handler/node_modules/mout/src/lang/defaults.js new file mode 100644 index 000000000..5156b1bb3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/defaults.js @@ -0,0 +1,16 @@ +define(['./toArray', '../array/find'], function (toArray, find) { + + /** + * Return first non void argument + */ + function defaults(var_args){ + return find(toArray(arguments), nonVoid); + } + + function nonVoid(val){ + return val != null; + } + + return defaults; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/inheritPrototype.js b/node_modules/express-error-handler/node_modules/mout/src/lang/inheritPrototype.js new file mode 100644 index 000000000..d47d0fee6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/inheritPrototype.js @@ -0,0 +1,17 @@ +define(['./createObject'], function(createObject){ + + /** + * Inherit prototype from another Object. + * - inspired by Nicholas Zackas Solution + * @param {object} child Child object + * @param {object} parent Parent Object + */ + function inheritPrototype(child, parent){ + var p = createObject(parent.prototype); + p.constructor = child; + child.prototype = p; + child.super_ = parent; + } + + return inheritPrototype; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/is.js b/node_modules/express-error-handler/node_modules/mout/src/lang/is.js new file mode 100644 index 000000000..261a2077f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/is.js @@ -0,0 +1,23 @@ +define(function () { + + /** + * Check if both arguments are egal. + */ + function is(x, y){ + // implementation borrowed from harmony:egal spec + if (x === y) { + // 0 === -0, but they are not identical + return x !== 0 || 1 / x === 1 / y; + } + + // NaN !== NaN, but they are identical. + // NaNs are the only non-reflexive value, i.e., if x !== x, + // then x is a NaN. + // isNaN is broken: it converts its argument to number, so + // isNaN("foo") => true + return x !== x && y !== y; + } + + return is; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isArguments.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isArguments.js new file mode 100644 index 000000000..f889ee8e0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isArguments.js @@ -0,0 +1,15 @@ +define(['./isKind'], function (isKind) { + + /** + */ + var isArgs = isKind(arguments, 'Arguments')? + function(val){ + return isKind(val, 'Arguments'); + } : + function(val){ + // Arguments is an Object on IE7 + return !!(val && Object.prototype.hasOwnProperty.call(val, 'callee')); + }; + + return isArgs; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isArray.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isArray.js new file mode 100644 index 000000000..886e2aa5b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isArray.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + var isArray = Array.isArray || function (val) { + return isKind(val, 'Array'); + }; + return isArray; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isBoolean.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isBoolean.js new file mode 100644 index 000000000..1ca27a69b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isBoolean.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isBoolean(val) { + return isKind(val, 'Boolean'); + } + return isBoolean; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isDate.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isDate.js new file mode 100644 index 000000000..2708d6763 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isDate.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isDate(val) { + return isKind(val, 'Date'); + } + return isDate; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isEmpty.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isEmpty.js new file mode 100644 index 000000000..4cc3d2dbc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isEmpty.js @@ -0,0 +1,23 @@ +define(['../object/forOwn', './isArray'], function (forOwn, isArray) { + + function isEmpty(val){ + if (val == null) { + // typeof null == 'object' so we check it first + return false; + } else if ( typeof val === 'string' || isArray(val) ) { + return !val.length; + } else if ( typeof val === 'object' || typeof val === 'function' ) { + var result = true; + forOwn(val, function(){ + result = false; + return false; // break loop + }); + return result; + } else { + return false; + } + } + + return isEmpty; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isFinite.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isFinite.js new file mode 100644 index 000000000..5a982f4bf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isFinite.js @@ -0,0 +1,21 @@ +define(['./isNumber'], function (isNumber) { + + var global = this; + + /** + * Check if value is finite + */ + function isFinite(val){ + var is = false; + if (typeof val === 'string' && val !== '') { + is = global.isFinite( parseFloat(val) ); + } else if (isNumber(val)){ + // need to use isNumber because of Number constructor + is = global.isFinite( val ); + } + return is; + } + + return isFinite; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isFunction.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isFunction.js new file mode 100644 index 000000000..ff5df7f03 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isFunction.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isFunction(val) { + return isKind(val, 'Function'); + } + return isFunction; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isInteger.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isInteger.js new file mode 100644 index 000000000..1931f5165 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isInteger.js @@ -0,0 +1,12 @@ +define(['./isNumber'], function (isNumber) { + + /** + * Check if value is an integer + */ + function isInteger(val){ + return isNumber(val) && (val % 1 === 0); + } + + return isInteger; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isKind.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isKind.js new file mode 100644 index 000000000..6937a12ff --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isKind.js @@ -0,0 +1,9 @@ +define(['./kindOf'], function (kindOf) { + /** + * Check if value is from a specific "kind". + */ + function isKind(val, kind){ + return kindOf(val) === kind; + } + return isKind; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isNaN.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isNaN.js new file mode 100644 index 000000000..b25e8c36c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isNaN.js @@ -0,0 +1,16 @@ +define(['./isNumber'], function (isNumber) { + + /** + * Check if value is NaN for realz + */ + function isNaN(val){ + // based on the fact that NaN !== NaN + // need to check if it's a number to avoid conflicts with host objects + // also need to coerce ToNumber to avoid edge case `new Number(NaN)` + // jshint eqeqeq: false + return !isNumber(val) || val != +val; + } + + return isNaN; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isNull.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isNull.js new file mode 100644 index 000000000..506e05eaa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isNull.js @@ -0,0 +1,9 @@ +define(function () { + /** + */ + function isNull(val){ + return val === null; + } + return isNull; +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isNumber.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isNumber.js new file mode 100644 index 000000000..9a832c5f4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isNumber.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isNumber(val) { + return isKind(val, 'Number'); + } + return isNumber; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isObject.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isObject.js new file mode 100644 index 000000000..0befb0636 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isObject.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isObject(val) { + return isKind(val, 'Object'); + } + return isObject; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isPlainObject.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isPlainObject.js new file mode 100644 index 000000000..406a2797b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isPlainObject.js @@ -0,0 +1,13 @@ +define(function () { + + /** + * Checks if the value is created by the `Object` constructor. + */ + function isPlainObject(value) { + return (!!value && typeof value === 'object' && + value.constructor === Object); + } + + return isPlainObject; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isRegExp.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isRegExp.js new file mode 100644 index 000000000..d78a03da0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isRegExp.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isRegExp(val) { + return isKind(val, 'RegExp'); + } + return isRegExp; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isString.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isString.js new file mode 100644 index 000000000..8a42fe018 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isString.js @@ -0,0 +1,8 @@ +define(['./isKind'], function (isKind) { + /** + */ + function isString(val) { + return isKind(val, 'String'); + } + return isString; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isUndefined.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isUndefined.js new file mode 100644 index 000000000..c57b28ebf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isUndefined.js @@ -0,0 +1,10 @@ +define(function () { + var UNDEF; + + /** + */ + function isUndef(val){ + return val === UNDEF; + } + return isUndef; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/isnt.js b/node_modules/express-error-handler/node_modules/mout/src/lang/isnt.js new file mode 100644 index 000000000..d43362228 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/isnt.js @@ -0,0 +1,12 @@ +define(['./is'], function (is) { + + /** + * Check if both values are not identical/egal + */ + function isnt(x, y){ + return !is(x, y); + } + + return isnt; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/kindOf.js b/node_modules/express-error-handler/node_modules/mout/src/lang/kindOf.js new file mode 100644 index 000000000..97d21d151 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/kindOf.js @@ -0,0 +1,20 @@ +define(function () { + + var _rKind = /^\[object (.*)\]$/, + _toString = Object.prototype.toString, + UNDEF; + + /** + * Gets the "kind" of value. (e.g. "String", "Number", etc) + */ + function kindOf(val) { + if (val === null) { + return 'Null'; + } else if (val === UNDEF) { + return 'Undefined'; + } else { + return _rKind.exec( _toString.call(val) )[1]; + } + } + return kindOf; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/toArray.js b/node_modules/express-error-handler/node_modules/mout/src/lang/toArray.js new file mode 100644 index 000000000..552916f67 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/toArray.js @@ -0,0 +1,31 @@ +define(['./kindOf'], function (kindOf) { + + var _win = this; + + /** + * Convert array-like object into array + */ + function toArray(val){ + var ret = [], + kind = kindOf(val), + n; + + if (val != null) { + if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) { + //string, regexp, function have .length but user probably just want + //to wrap value into an array.. + ret[ret.length] = val; + } else { + //window returns true on isObject in IE7 and may have length + //property. `typeof NodeList` returns `function` on Safari so + //we can't use it (#58) + n = val.length; + while (n--) { + ret[n] = val[n]; + } + } + } + return ret; + } + return toArray; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/toNumber.js b/node_modules/express-error-handler/node_modules/mout/src/lang/toNumber.js new file mode 100644 index 000000000..397673864 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/toNumber.js @@ -0,0 +1,20 @@ +define(['./isArray'], function (isArray) { + + /** + * covert value into number if numeric + */ + function toNumber(val){ + // numberic values should come first because of -0 + if (typeof val === 'number') return val; + // we want all falsy values (besides -0) to return zero to avoid + // headaches + if (!val) return 0; + if (typeof val === 'string') return parseFloat(val); + // arrays are edge cases. `Number([4]) === 4` + if (isArray(val)) return NaN; + return Number(val); + } + + return toNumber; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/lang/toString.js b/node_modules/express-error-handler/node_modules/mout/src/lang/toString.js new file mode 100644 index 000000000..c28b89af6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/lang/toString.js @@ -0,0 +1,13 @@ +define(function () { + + /** + * Typecast a value to a String, using an empty string value for null or + * undefined. + */ + function toString(val){ + return val == null ? '' : val.toString(); + } + + return toString; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math.js b/node_modules/express-error-handler/node_modules/mout/src/math.js new file mode 100644 index 000000000..e2ba8705d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math.js @@ -0,0 +1,19 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'ceil' : require('./math/ceil'), + 'clamp' : require('./math/clamp'), + 'countSteps' : require('./math/countSteps'), + 'floor' : require('./math/floor'), + 'inRange' : require('./math/inRange'), + 'isNear' : require('./math/isNear'), + 'lerp' : require('./math/lerp'), + 'loop' : require('./math/loop'), + 'map' : require('./math/map'), + 'norm' : require('./math/norm'), + 'round' : require('./math/round') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/ceil.js b/node_modules/express-error-handler/node_modules/mout/src/math/ceil.js new file mode 100644 index 000000000..d73b05817 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/ceil.js @@ -0,0 +1,11 @@ +define(function(){ + /** + * Round value up with a custom radix. + */ + function ceil(val, step){ + step = Math.abs(step || 1); + return Math.ceil(val / step) * step; + } + + return ceil; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/clamp.js b/node_modules/express-error-handler/node_modules/mout/src/math/clamp.js new file mode 100644 index 000000000..fb5a14844 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/clamp.js @@ -0,0 +1,9 @@ +define(function(){ + /** + * Clamps value inside range. + */ + function clamp(val, min, max){ + return val < min? min : (val > max? max : val); + } + return clamp; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/countSteps.js b/node_modules/express-error-handler/node_modules/mout/src/math/countSteps.js new file mode 100644 index 000000000..0ecb32f68 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/countSteps.js @@ -0,0 +1,16 @@ +define(function(){ + /** + * Count number of full steps. + */ + function countSteps(val, step, overflow){ + val = Math.floor(val / step); + + if (overflow) { + return val % overflow; + } + + return val; + } + + return countSteps; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/floor.js b/node_modules/express-error-handler/node_modules/mout/src/math/floor.js new file mode 100644 index 000000000..8a4456b62 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/floor.js @@ -0,0 +1,10 @@ +define(function(){ + /** + * Floor value to full steps. + */ + function floor(val, step){ + step = Math.abs(step || 1); + return Math.floor(val / step) * step; + } + return floor; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/inRange.js b/node_modules/express-error-handler/node_modules/mout/src/math/inRange.js new file mode 100644 index 000000000..0c8905363 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/inRange.js @@ -0,0 +1,11 @@ +define(function(){ + /** + * Checks if value is inside the range. + */ + function inRange(val, min, max, threshold){ + threshold = threshold || 0; + return (val + threshold >= min && val - threshold <= max); + } + + return inRange; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/isNear.js b/node_modules/express-error-handler/node_modules/mout/src/math/isNear.js new file mode 100644 index 000000000..b308a0b0b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/isNear.js @@ -0,0 +1,9 @@ +define(function(){ + /** + * Check if value is close to target. + */ + function isNear(val, target, threshold){ + return (Math.abs(val - target) <= threshold); + } + return isNear; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/lerp.js b/node_modules/express-error-handler/node_modules/mout/src/math/lerp.js new file mode 100644 index 000000000..26b99d048 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/lerp.js @@ -0,0 +1,11 @@ +define(function(){ + /** + * Linear interpolation. + * IMPORTANT:will return `Infinity` if numbers overflow Number.MAX_VALUE + */ + function lerp(ratio, start, end){ + return start + (end - start) * ratio; + } + + return lerp; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/loop.js b/node_modules/express-error-handler/node_modules/mout/src/math/loop.js new file mode 100644 index 000000000..c735ecf65 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/loop.js @@ -0,0 +1,10 @@ +define(function(){ + /** + * Loops value inside range. + */ + function loop(val, min, max){ + return val < min? max : (val > max? min : val); + } + + return loop; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/map.js b/node_modules/express-error-handler/node_modules/mout/src/math/map.js new file mode 100644 index 000000000..bf7dc5d5f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/map.js @@ -0,0 +1,10 @@ +define(['./lerp', './norm'], function(lerp, norm){ + /** + * Maps a number from one scale to another. + * @example map(3, 0, 4, -1, 1) -> 0.5 + */ + function map(val, min1, max1, min2, max2){ + return lerp( norm(val, min1, max1), min2, max2 ); + } + return map; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/norm.js b/node_modules/express-error-handler/node_modules/mout/src/math/norm.js new file mode 100644 index 000000000..fccae20e7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/norm.js @@ -0,0 +1,9 @@ +define(function(){ + /** + * Gets normalized ratio of value inside range. + */ + function norm(val, min, max){ + return (val - min) / (max - min); + } + return norm; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/math/round.js b/node_modules/express-error-handler/node_modules/mout/src/math/round.js new file mode 100644 index 000000000..b43e4ac2b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/math/round.js @@ -0,0 +1,12 @@ +define(function () { + /** + * Round number to a specific radix + */ + function round(value, radix){ + radix = radix || 1; // default round 1 + return Math.round(value / radix) * radix; + } + + return round; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number.js b/node_modules/express-error-handler/node_modules/mout/src/number.js new file mode 100644 index 000000000..cb52fc751 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number.js @@ -0,0 +1,21 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'MAX_INT' : require('./number/MAX_INT'), + 'MAX_UINT' : require('./number/MAX_UINT'), + 'MIN_INT' : require('./number/MIN_INT'), + 'abbreviate' : require('./number/abbreviate'), + 'currencyFormat' : require('./number/currencyFormat'), + 'enforcePrecision' : require('./number/enforcePrecision'), + 'pad' : require('./number/pad'), + 'rol' : require('./number/rol'), + 'ror' : require('./number/ror'), + 'sign' : require('./number/sign'), + 'toInt' : require('./number/toInt'), + 'toUInt' : require('./number/toUInt'), + 'toUInt31' : require('./number/toUInt31') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/MAX_INT.js b/node_modules/express-error-handler/node_modules/mout/src/number/MAX_INT.js new file mode 100644 index 000000000..23a6e1a3e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/MAX_INT.js @@ -0,0 +1,6 @@ +/** + * @constant Maximum 32-bit signed integer value. (2^31 - 1) + */ +define(function(){ + return 2147483647; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/MAX_UINT.js b/node_modules/express-error-handler/node_modules/mout/src/number/MAX_UINT.js new file mode 100644 index 000000000..a035096cc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/MAX_UINT.js @@ -0,0 +1,6 @@ +/** + * @constant Maximum 32-bit unsigned integet value (2^32 - 1) + */ +define(function(){ + return 4294967295; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/MIN_INT.js b/node_modules/express-error-handler/node_modules/mout/src/number/MIN_INT.js new file mode 100644 index 000000000..9b3e97810 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/MIN_INT.js @@ -0,0 +1,6 @@ +/** + * @constant Minimum 32-bit signed integer value (-2^31). + */ +define(function(){ + return -2147483648; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/abbreviate.js b/node_modules/express-error-handler/node_modules/mout/src/number/abbreviate.js new file mode 100644 index 000000000..7e7405ade --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/abbreviate.js @@ -0,0 +1,35 @@ +define(['./enforcePrecision'], function (enforcePrecision) { + + var _defaultDict = { + thousand : 'K', + million : 'M', + billion : 'B' + }; + + /** + * Abbreviate number if bigger than 1000. (eg: 2.5K, 17.5M, 3.4B, ...) + */ + function abbreviateNumber(val, nDecimals, dict){ + nDecimals = nDecimals != null? nDecimals : 1; + dict = dict || _defaultDict; + val = enforcePrecision(val, nDecimals); + + var str, mod; + + if (val < 1000000) { + mod = enforcePrecision(val / 1000, nDecimals); + // might overflow to next scale during rounding + str = mod < 1000? mod + dict.thousand : 1 + dict.million; + } else if (val < 1000000000) { + mod = enforcePrecision(val / 1000000, nDecimals); + str = mod < 1000? mod + dict.million : 1 + dict.billion; + } else { + str = enforcePrecision(val / 1000000000, nDecimals) + dict.billion; + } + + return str; + } + + return abbreviateNumber; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/currencyFormat.js b/node_modules/express-error-handler/node_modules/mout/src/number/currencyFormat.js new file mode 100644 index 000000000..1e5fecba8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/currencyFormat.js @@ -0,0 +1,27 @@ +define(['../lang/toNumber'], function (toNumber) { + + /** + * Converts number into currency format + */ + function currencyFormat(val, nDecimalDigits, decimalSeparator, thousandsSeparator) { + val = toNumber(val); + nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits; + decimalSeparator = decimalSeparator == null? '.' : decimalSeparator; + thousandsSeparator = thousandsSeparator == null? ',' : thousandsSeparator; + + //can't use enforce precision since it returns a number and we are + //doing a RegExp over the string + var fixed = val.toFixed(nDecimalDigits), + //separate begin [$1], middle [$2] and decimal digits [$4] + parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); + + if(parts){ //val >= 1000 || val <= -1000 + return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : ''); + }else{ + return fixed.replace('.', decimalSeparator); + } + } + + return currencyFormat; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/enforcePrecision.js b/node_modules/express-error-handler/node_modules/mout/src/number/enforcePrecision.js new file mode 100644 index 000000000..1e65e5057 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/enforcePrecision.js @@ -0,0 +1,12 @@ +define(['../lang/toNumber'], function(toNumber){ + /** + * Enforce a specific amount of decimal digits and also fix floating + * point rounding issues. + */ + function enforcePrecision(val, nDecimalDigits){ + val = toNumber(val); + var pow = Math.pow(10, nDecimalDigits); + return +(Math.round(val * pow) / pow).toFixed(nDecimalDigits); + } + return enforcePrecision; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/pad.js b/node_modules/express-error-handler/node_modules/mout/src/number/pad.js new file mode 100644 index 000000000..194a3df3d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/pad.js @@ -0,0 +1,13 @@ +define(['../string/lpad', '../lang/toNumber'], function(lpad, toNumber){ + + /** + * Add padding zeros if n.length < minLength. + */ + function pad(n, minLength, char){ + n = toNumber(n); + return lpad(''+ n, minLength, char || '0'); + } + + return pad; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/rol.js b/node_modules/express-error-handler/node_modules/mout/src/number/rol.js new file mode 100644 index 000000000..a148f444d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/rol.js @@ -0,0 +1,10 @@ +define(function(){ + /** + * Bitwise circular shift left + * http://en.wikipedia.org/wiki/Circular_shift + */ + function rol(val, shift){ + return (val << shift) | (val >> (32 - shift)); + } + return rol; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/ror.js b/node_modules/express-error-handler/node_modules/mout/src/number/ror.js new file mode 100644 index 000000000..b5c66f92d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/ror.js @@ -0,0 +1,10 @@ +define(function(){ + /** + * Bitwise circular shift right + * http://en.wikipedia.org/wiki/Circular_shift + */ + function ror(val, shift){ + return (val >> shift) | (val << (32 - shift)); + } + return ror; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/sign.js b/node_modules/express-error-handler/node_modules/mout/src/number/sign.js new file mode 100644 index 000000000..b387c957a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/sign.js @@ -0,0 +1,15 @@ +define(['../lang/toNumber'], function (toNumber) { + + /** + * Get sign of the value. + */ + function sign(val) { + var num = toNumber(val); + if (num === 0) return num; // +0 and +0 === 0 + if (isNaN(num)) return num; // NaN + return num < 0? -1 : 1; + } + + return sign; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/toInt.js b/node_modules/express-error-handler/node_modules/mout/src/number/toInt.js new file mode 100644 index 000000000..5ea59e51e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/toInt.js @@ -0,0 +1,17 @@ +define(function(){ + + /** + * "Convert" value into an 32-bit integer. + * Works like `Math.floor` if val > 0 and `Math.ceil` if val < 0. + * IMPORTANT: val will wrap at 2^31 and -2^31. + * Perf tests: http://jsperf.com/vs-vs-parseint-bitwise-operators/7 + */ + function toInt(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return ~~val; + } + + return toInt; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/toUInt.js b/node_modules/express-error-handler/node_modules/mout/src/number/toUInt.js new file mode 100644 index 000000000..36bbdadd0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/toUInt.js @@ -0,0 +1,15 @@ +define(function () { + + /** + * "Convert" value into a 32-bit unsigned integer. + * IMPORTANT: Value will wrap at 2^32. + */ + function toUInt(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return val >>> 0; + } + + return toUInt; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/number/toUInt31.js b/node_modules/express-error-handler/node_modules/mout/src/number/toUInt31.js new file mode 100644 index 000000000..c1c4affd3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/number/toUInt31.js @@ -0,0 +1,15 @@ +define(['./MAX_INT'], function(MAX_INT){ + + /** + * "Convert" value into an 31-bit unsigned integer (since 1 bit is used for sign). + * IMPORTANT: value wil wrap at 2^31, if negative will return 0. + */ + function toUInt31(val){ + // we do not use lang/toNumber because of perf and also because it + // doesn't break the functionality + return (val <= 0)? 0 : (val > MAX_INT? ~~(val % (MAX_INT + 1)) : ~~val); + } + + return toUInt31; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object.js b/node_modules/express-error-handler/node_modules/mout/src/object.js new file mode 100644 index 000000000..343e78266 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object.js @@ -0,0 +1,42 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'bindAll' : require('./object/bindAll'), + 'contains' : require('./object/contains'), + 'deepEquals' : require('./object/deepEquals'), + 'deepFillIn' : require('./object/deepFillIn'), + 'deepMatches' : require('./object/deepMatches'), + 'deepMixIn' : require('./object/deepMixIn'), + 'equals' : require('./object/equals'), + 'every' : require('./object/every'), + 'fillIn' : require('./object/fillIn'), + 'filter' : require('./object/filter'), + 'find' : require('./object/find'), + 'forIn' : require('./object/forIn'), + 'forOwn' : require('./object/forOwn'), + 'functions' : require('./object/functions'), + 'get' : require('./object/get'), + 'has' : require('./object/has'), + 'hasOwn' : require('./object/hasOwn'), + 'keys' : require('./object/keys'), + 'map' : require('./object/map'), + 'matches' : require('./object/matches'), + 'max' : require('./object/max'), + 'merge' : require('./object/merge'), + 'min' : require('./object/min'), + 'mixIn' : require('./object/mixIn'), + 'namespace' : require('./object/namespace'), + 'pick' : require('./object/pick'), + 'pluck' : require('./object/pluck'), + 'reduce' : require('./object/reduce'), + 'reject' : require('./object/reject'), + 'set' : require('./object/set'), + 'size' : require('./object/size'), + 'some' : require('./object/some'), + 'unset' : require('./object/unset'), + 'values' : require('./object/values') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/bindAll.js b/node_modules/express-error-handler/node_modules/mout/src/object/bindAll.js new file mode 100644 index 000000000..b131ed159 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/bindAll.js @@ -0,0 +1,16 @@ +define(['./functions', '../function/bind', '../array/forEach'], function (functions, bind, forEach) { + + /** + * Binds methods of the object to be run in it's own context. + */ + function bindAll(obj, rest_methodNames){ + var keys = arguments.length > 1? + Array.prototype.slice.call(arguments, 1) : functions(obj); + forEach(keys, function(key){ + obj[key] = bind(obj[key], obj); + }); + } + + return bindAll; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/contains.js b/node_modules/express-error-handler/node_modules/mout/src/object/contains.js new file mode 100644 index 000000000..297e8986a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/contains.js @@ -0,0 +1,13 @@ +define(['./some'], function (some) { + + /** + * Check if object contains value + */ + function contains(obj, needle) { + return some(obj, function(val) { + return (val === needle); + }); + } + return contains; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/deepEquals.js b/node_modules/express-error-handler/node_modules/mout/src/object/deepEquals.js new file mode 100644 index 000000000..8b7d5d151 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/deepEquals.js @@ -0,0 +1,26 @@ +define(['../lang/isObject', './equals'], function (isObject, equals) { + + function defaultCompare(a, b) { + return a === b; + } + + /** + * Recursively checks for same properties and values. + */ + function deepEquals(a, b, callback){ + callback = callback || defaultCompare; + + if (!isObject(a) || !isObject(b)) { + return callback(a, b); + } + + function compare(a, b){ + return deepEquals(a, b, callback); + } + + return equals(a, b, compare); + } + + return deepEquals; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/deepFillIn.js b/node_modules/express-error-handler/node_modules/mout/src/object/deepFillIn.js new file mode 100644 index 000000000..ee69c3d56 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/deepFillIn.js @@ -0,0 +1,32 @@ +define(['./forOwn', '../lang/isPlainObject'], function (forOwn, isPlainObject) { + + /** + * Deeply copy missing properties in the target from the defaults. + */ + function deepFillIn(target, defaults){ + var i = 0, + n = arguments.length, + obj; + + while(++i < n) { + obj = arguments[i]; + if (obj) { + // jshint loopfunc: true + forOwn(obj, function(newValue, key) { + var curValue = target[key]; + if (curValue == null) { + target[key] = newValue; + } else if (isPlainObject(curValue) && + isPlainObject(newValue)) { + deepFillIn(curValue, newValue); + } + }); + } + } + + return target; + } + + return deepFillIn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/deepMatches.js b/node_modules/express-error-handler/node_modules/mout/src/object/deepMatches.js new file mode 100644 index 000000000..2eae62979 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/deepMatches.js @@ -0,0 +1,54 @@ +define(['./forOwn', '../lang/isArray'], function(forOwn, isArray) { + + function containsMatch(array, pattern) { + var i = -1, length = array.length; + while (++i < length) { + if (deepMatches(array[i], pattern)) { + return true; + } + } + + return false; + } + + function matchArray(target, pattern) { + var i = -1, patternLength = pattern.length; + while (++i < patternLength) { + if (!containsMatch(target, pattern[i])) { + return false; + } + } + + return true; + } + + function matchObject(target, pattern) { + var result = true; + forOwn(pattern, function(val, key) { + if (!deepMatches(target[key], val)) { + // Return false to break out of forOwn early + return (result = false); + } + }); + + return result; + } + + /** + * Recursively check if the objects match. + */ + function deepMatches(target, pattern){ + if (target && typeof target === 'object') { + if (isArray(target) && isArray(pattern)) { + return matchArray(target, pattern); + } else { + return matchObject(target, pattern); + } + } else { + return target === pattern; + } + } + + return deepMatches; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/deepMixIn.js b/node_modules/express-error-handler/node_modules/mout/src/object/deepMixIn.js new file mode 100644 index 000000000..1b4178ef8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/deepMixIn.js @@ -0,0 +1,33 @@ +define(['./forOwn', '../lang/isPlainObject'], function (forOwn, isPlainObject) { + + /** + * Mixes objects into the target object, recursively mixing existing child + * objects. + */ + function deepMixIn(target, objects) { + var i = 0, + n = arguments.length, + obj; + + while(++i < n){ + obj = arguments[i]; + if (obj) { + forOwn(obj, copyProp, target); + } + } + + return target; + } + + function copyProp(val, key) { + var existing = this[key]; + if (isPlainObject(val) && isPlainObject(existing)) { + deepMixIn(existing, val); + } else { + this[key] = val; + } + } + + return deepMixIn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/equals.js b/node_modules/express-error-handler/node_modules/mout/src/object/equals.js new file mode 100644 index 000000000..596cb9529 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/equals.js @@ -0,0 +1,34 @@ +define(['./hasOwn', './every', '../lang/isObject'], function(hasOwn, every, isObject) { + + function defaultCompare(a, b) { + return a === b; + } + + // Makes a function to compare the object values from the specified compare + // operation callback. + function makeCompare(callback) { + return function(value, key) { + return hasOwn(this, key) && callback(value, this[key]); + }; + } + + function checkProperties(value, key) { + return hasOwn(this, key); + } + + /** + * Checks if two objects have the same keys and values. + */ + function equals(a, b, callback) { + callback = callback || defaultCompare; + + if (!isObject(a) || !isObject(b)) { + return callback(a, b); + } + + return (every(a, makeCompare(callback), b) && + every(b, checkProperties, a)); + } + + return equals; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/every.js b/node_modules/express-error-handler/node_modules/mout/src/object/every.js new file mode 100644 index 000000000..52983a5e3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/every.js @@ -0,0 +1,22 @@ +define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) { + + /** + * Object every + */ + function every(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = true; + forOwn(obj, function(val, key) { + // we consider any falsy values as "false" on purpose so shorthand + // syntax can be used to check property existence + if (!callback(val, key, obj)) { + result = false; + return false; // break + } + }); + return result; + } + + return every; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/fillIn.js b/node_modules/express-error-handler/node_modules/mout/src/object/fillIn.js new file mode 100644 index 000000000..0845d3c20 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/fillIn.js @@ -0,0 +1,19 @@ +define(['../array/forEach', './forOwn'], function (forEach, forOwn) { + + /** + * Copy missing properties in the obj from the defaults. + */ + function fillIn(obj, var_defaults){ + forEach(Array.prototype.slice.call(arguments, 1), function(base){ + forOwn(base, function(val, key){ + if (obj[key] == null) { + obj[key] = val; + } + }); + }); + return obj; + } + + return fillIn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/filter.js b/node_modules/express-error-handler/node_modules/mout/src/object/filter.js new file mode 100644 index 000000000..f213b9158 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/filter.js @@ -0,0 +1,19 @@ +define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) { + + /** + * Creates a new object with all the properties where the callback returns + * true. + */ + function filterValues(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var output = {}; + forOwn(obj, function(value, key, obj) { + if (callback(value, key, obj)) { + output[key] = value; + } + }); + + return output; + } + return filterValues; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/find.js b/node_modules/express-error-handler/node_modules/mout/src/object/find.js new file mode 100644 index 000000000..47e6b09d5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/find.js @@ -0,0 +1,20 @@ +define(['./some', '../function/makeIterator_'], function(some, makeIterator) { + + /** + * Returns first item that matches criteria + */ + function find(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result; + some(obj, function(value, key, obj) { + if (callback(value, key, obj)) { + result = value; + return true; //break + } + }); + return result; + } + + return find; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/forIn.js b/node_modules/express-error-handler/node_modules/mout/src/object/forIn.js new file mode 100644 index 000000000..2058e9cbf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/forIn.js @@ -0,0 +1,62 @@ +define(function () { + + var _hasDontEnumBug, + _dontEnums; + + function checkDontEnum(){ + _dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + + _hasDontEnumBug = true; + + for (var key in {'toString': null}) { + _hasDontEnumBug = false; + } + } + + /** + * Similar to Array/forEach but works over object properties and fixes Don't + * Enum bug on IE. + * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation + */ + function forIn(obj, fn, thisObj){ + var key, i = 0; + // no need to check if argument is a real object that way we can use + // it for arrays, functions, date, etc. + + //post-pone check till needed + if (_hasDontEnumBug == null) checkDontEnum(); + + for (key in obj) { + if (exec(fn, obj, key, thisObj) === false) { + break; + } + } + + if (_hasDontEnumBug) { + while (key = _dontEnums[i++]) { + // since we aren't using hasOwn check we need to make sure the + // property was overwritten + if (obj[key] !== Object.prototype[key]) { + if (exec(fn, obj, key, thisObj) === false) { + break; + } + } + } + } + } + + function exec(fn, obj, key, thisObj){ + return fn.call(thisObj, obj[key], key, obj); + } + + return forIn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/forOwn.js b/node_modules/express-error-handler/node_modules/mout/src/object/forOwn.js new file mode 100644 index 000000000..b40cbaf18 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/forOwn.js @@ -0,0 +1,18 @@ +define(['./hasOwn', './forIn'], function (hasOwn, forIn) { + + /** + * Similar to Array/forEach but works over object properties and fixes Don't + * Enum bug on IE. + * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation + */ + function forOwn(obj, fn, thisObj){ + forIn(obj, function(val, key){ + if (hasOwn(obj, key)) { + return fn.call(thisObj, obj[key], key, obj); + } + }); + } + + return forOwn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/functions.js b/node_modules/express-error-handler/node_modules/mout/src/object/functions.js new file mode 100644 index 000000000..60fee3ddd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/functions.js @@ -0,0 +1,18 @@ +define(['./forIn'], function (forIn) { + + /** + * return a list of all enumerable properties that have function values + */ + function functions(obj){ + var keys = []; + forIn(obj, function(val, key){ + if (typeof val === 'function'){ + keys.push(key); + } + }); + return keys.sort(); + } + + return functions; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/get.js b/node_modules/express-error-handler/node_modules/mout/src/object/get.js new file mode 100644 index 000000000..b498153d2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/get.js @@ -0,0 +1,20 @@ +define(function () { + + /** + * get "nested" object property + */ + function get(obj, prop){ + var parts = prop.split('.'), + last = parts.pop(); + + while (prop = parts.shift()) { + obj = obj[prop]; + if (typeof obj !== 'object' || !obj) return; + } + + return obj[last]; + } + + return get; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/has.js b/node_modules/express-error-handler/node_modules/mout/src/object/has.js new file mode 100644 index 000000000..cc29817fb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/has.js @@ -0,0 +1,15 @@ +define(['./get'], function (get) { + + var UNDEF; + + /** + * Check if object has nested property. + */ + function has(obj, prop){ + return get(obj, prop) !== UNDEF; + } + + return has; + +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/hasOwn.js b/node_modules/express-error-handler/node_modules/mout/src/object/hasOwn.js new file mode 100644 index 000000000..5c53bcf2f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/hasOwn.js @@ -0,0 +1,12 @@ +define(function () { + + /** + * Safer Object.hasOwnProperty + */ + function hasOwn(obj, prop){ + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + return hasOwn; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/keys.js b/node_modules/express-error-handler/node_modules/mout/src/object/keys.js new file mode 100644 index 000000000..ed7c4f919 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/keys.js @@ -0,0 +1,16 @@ +define(['./forOwn'], function (forOwn) { + + /** + * Get object keys + */ + var keys = Object.keys || function (obj) { + var keys = []; + forOwn(obj, function(val, key){ + keys.push(key); + }); + return keys; + }; + + return keys; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/map.js b/node_modules/express-error-handler/node_modules/mout/src/object/map.js new file mode 100644 index 000000000..2958f6b09 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/map.js @@ -0,0 +1,17 @@ +define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) { + + /** + * Creates a new object where all the values are the result of calling + * `callback`. + */ + function mapValues(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var output = {}; + forOwn(obj, function(val, key, obj) { + output[key] = callback(val, key, obj); + }); + + return output; + } + return mapValues; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/matches.js b/node_modules/express-error-handler/node_modules/mout/src/object/matches.js new file mode 100644 index 000000000..73ff427c0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/matches.js @@ -0,0 +1,20 @@ +define(['./forOwn'], function (forOwn) { + + /** + * checks if a object contains all given properties/values + */ + function matches(target, props){ + // can't use "object/every" because of circular dependency + var result = true; + forOwn(props, function(val, key){ + if (target[key] !== val) { + // break loop at first difference + return (result = false); + } + }); + return result; + } + + return matches; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/max.js b/node_modules/express-error-handler/node_modules/mout/src/object/max.js new file mode 100644 index 000000000..ef311dcb8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/max.js @@ -0,0 +1,11 @@ +define(['../array/max', './values'], function(arrMax, values) { + + /** + * Returns maximum value inside object. + */ + function max(obj, compareFn) { + return arrMax(values(obj), compareFn); + } + + return max; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/merge.js b/node_modules/express-error-handler/node_modules/mout/src/object/merge.js new file mode 100644 index 000000000..d7cfedec4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/merge.js @@ -0,0 +1,38 @@ +define(['./hasOwn', '../lang/deepClone', '../lang/isObject'], function (hasOwn, deepClone, isObject) { + + /** + * Deep merge objects. + */ + function merge() { + var i = 1, + key, val, obj, target; + + // make sure we don't modify source element and it's properties + // objects are passed by reference + target = deepClone( arguments[0] ); + + while (obj = arguments[i++]) { + for (key in obj) { + if ( ! hasOwn(obj, key) ) { + continue; + } + + val = obj[key]; + + if ( isObject(val) && isObject(target[key]) ){ + // inception, deep merge objects + target[key] = merge(target[key], val); + } else { + // make sure arrays, regexp, date, objects are cloned + target[key] = deepClone(val); + } + + } + } + + return target; + } + + return merge; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/min.js b/node_modules/express-error-handler/node_modules/mout/src/object/min.js new file mode 100644 index 000000000..9fb4c1a3d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/min.js @@ -0,0 +1,11 @@ +define(['../array/min', './values'], function(arrMin, values) { + + /** + * Returns minimum value inside object. + */ + function min(obj, iterator) { + return arrMin(values(obj), iterator); + } + + return min; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/mixIn.js b/node_modules/express-error-handler/node_modules/mout/src/object/mixIn.js new file mode 100644 index 000000000..6210b7e77 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/mixIn.js @@ -0,0 +1,28 @@ +define(['./forOwn'], function(forOwn){ + + /** + * Combine properties from all the objects into first one. + * - This method affects target object in place, if you want to create a new Object pass an empty object as first param. + * @param {object} target Target Object + * @param {...object} objects Objects to be combined (0...n objects). + * @return {object} Target Object. + */ + function mixIn(target, objects){ + var i = 0, + n = arguments.length, + obj; + while(++i < n){ + obj = arguments[i]; + if (obj != null) { + forOwn(obj, copyProp, target); + } + } + return target; + } + + function copyProp(val, key){ + this[key] = val; + } + + return mixIn; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/namespace.js b/node_modules/express-error-handler/node_modules/mout/src/object/namespace.js new file mode 100644 index 000000000..7ed65db8c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/namespace.js @@ -0,0 +1,19 @@ +define(['../array/forEach'], function (forEach) { + + /** + * Create nested object if non-existent + */ + function namespace(obj, path){ + if (!path) return obj; + forEach(path.split('.'), function(key){ + if (!obj[key]) { + obj[key] = {}; + } + obj = obj[key]; + }); + return obj; + } + + return namespace; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/pick.js b/node_modules/express-error-handler/node_modules/mout/src/object/pick.js new file mode 100644 index 000000000..76e22bfc7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/pick.js @@ -0,0 +1,18 @@ +define(function(){ + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys. + */ + function pick(obj, var_keys){ + var keys = typeof arguments[1] !== 'string'? arguments[1] : Array.prototype.slice.call(arguments, 1), + out = {}, + i = 0, key; + while (key = keys[i++]) { + out[key] = obj[key]; + } + return out; + } + + return pick; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/pluck.js b/node_modules/express-error-handler/node_modules/mout/src/object/pluck.js new file mode 100644 index 000000000..d47744bd2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/pluck.js @@ -0,0 +1,12 @@ +define(['./map', '../function/prop'], function (map, prop) { + + /** + * Extract a list of property values. + */ + function pluck(obj, propName){ + return map(obj, prop(propName)); + } + + return pluck; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/reduce.js b/node_modules/express-error-handler/node_modules/mout/src/object/reduce.js new file mode 100644 index 000000000..d3a57788f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/reduce.js @@ -0,0 +1,28 @@ +define(['./forOwn', './size'], function(forOwn, size) { + + /** + * Object reduce + */ + function reduce(obj, callback, memo, thisObj) { + var initial = arguments.length > 2; + + if (!size(obj) && !initial) { + throw new Error('reduce of empty object with no initial value'); + } + + forOwn(obj, function(value, key, list) { + if (!initial) { + memo = value; + initial = true; + } + else { + memo = callback.call(thisObj, memo, value, key, list); + } + }); + + return memo; + } + + return reduce; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/reject.js b/node_modules/express-error-handler/node_modules/mout/src/object/reject.js new file mode 100644 index 000000000..84296428d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/reject.js @@ -0,0 +1,15 @@ +define(['./filter', '../function/makeIterator_'], function (filter, makeIterator) { + + /** + * Object reject + */ + function reject(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + return filter(obj, function(value, index, obj) { + return !callback(value, index, obj); + }, thisObj); + } + + return reject; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/set.js b/node_modules/express-error-handler/node_modules/mout/src/object/set.js new file mode 100644 index 000000000..b8fa25a35 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/set.js @@ -0,0 +1,17 @@ +define(['./namespace'], function (namespace) { + + /** + * set "nested" object property + */ + function set(obj, prop, val){ + var parts = (/^(.+)\.(.+)$/).exec(prop); + if (parts){ + namespace(obj, parts[1])[parts[2]] = val; + } else { + obj[prop] = val; + } + } + + return set; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/size.js b/node_modules/express-error-handler/node_modules/mout/src/object/size.js new file mode 100644 index 000000000..c6e377cf5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/size.js @@ -0,0 +1,16 @@ +define(['./forOwn'], function (forOwn) { + + /** + * Get object size + */ + function size(obj) { + var count = 0; + forOwn(obj, function(){ + count++; + }); + return count; + } + + return size; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/some.js b/node_modules/express-error-handler/node_modules/mout/src/object/some.js new file mode 100644 index 000000000..1bd6fdae0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/some.js @@ -0,0 +1,20 @@ +define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) { + + /** + * Object some + */ + function some(obj, callback, thisObj) { + callback = makeIterator(callback, thisObj); + var result = false; + forOwn(obj, function(val, key) { + if (callback(val, key, obj)) { + result = true; + return false; // break + } + }); + return result; + } + + return some; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/unset.js b/node_modules/express-error-handler/node_modules/mout/src/object/unset.js new file mode 100644 index 000000000..787fc19ae --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/unset.js @@ -0,0 +1,23 @@ +define(['./has'], function (has) { + + /** + * Unset object property. + */ + function unset(obj, prop){ + if (has(obj, prop)) { + var parts = prop.split('.'), + last = parts.pop(); + while (prop = parts.shift()) { + obj = obj[prop]; + } + return (delete obj[last]); + + } else { + // if property doesn't exist treat as deleted + return true; + } + } + + return unset; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/object/values.js b/node_modules/express-error-handler/node_modules/mout/src/object/values.js new file mode 100644 index 000000000..b311fd098 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/object/values.js @@ -0,0 +1,16 @@ +define(['./forOwn'], function (forOwn) { + + /** + * Get object values + */ + function values(obj) { + var vals = []; + forOwn(obj, function(val, key){ + vals.push(val); + }); + return vals; + } + + return values; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString.js b/node_modules/express-error-handler/node_modules/mout/src/queryString.js new file mode 100644 index 000000000..443461272 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString.js @@ -0,0 +1,15 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'contains' : require('./queryString/contains'), + 'decode' : require('./queryString/decode'), + 'encode' : require('./queryString/encode'), + 'getParam' : require('./queryString/getParam'), + 'getQuery' : require('./queryString/getQuery'), + 'parse' : require('./queryString/parse'), + 'setParam' : require('./queryString/setParam') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/contains.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/contains.js new file mode 100644 index 000000000..a6d11cce7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/contains.js @@ -0,0 +1,12 @@ +define(['./getQuery'], function (getQuery) { + + /** + * Checks if query string contains parameter. + */ + function contains(url, paramName) { + var regex = new RegExp('(\\?|&)'+ paramName +'=', 'g'); //matches `?param=` or `¶m=` + return regex.test(getQuery(url)); + } + + return contains; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/decode.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/decode.js new file mode 100644 index 000000000..50da3f666 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/decode.js @@ -0,0 +1,35 @@ +define(['../string/typecast', '../lang/isString', '../lang/isArray', '../object/hasOwn'], function (typecast, isString, isArray, hasOwn) { + + /** + * Decode query string into an object of keys => vals. + */ + function decode(queryStr, shouldTypecast) { + var queryArr = (queryStr || '').replace('?', '').split('&'), + count = -1, + length = queryArr.length, + obj = {}, + item, pValue, pName, toSet; + + while (++count < length) { + item = queryArr[count].split('='); + pName = item[0]; + if (!pName || !pName.length){ + continue; + } + pValue = shouldTypecast === false ? item[1] : typecast(item[1]); + toSet = isString(pValue) ? decodeURIComponent(pValue) : pValue; + if (hasOwn(obj,pName)){ + if(isArray(obj[pName])){ + obj[pName].push(toSet); + } else { + obj[pName] = [obj[pName],toSet]; + } + } else { + obj[pName] = toSet; + } + } + return obj; + } + + return decode; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/encode.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/encode.js new file mode 100644 index 000000000..c249287a0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/encode.js @@ -0,0 +1,25 @@ +define(['../object/forOwn','../lang/isArray','../array/forEach'], function (forOwn,isArray,forEach) { + + /** + * Encode object into a query string. + */ + function encode(obj){ + var query = [], + arrValues, reg; + forOwn(obj, function (val, key) { + if (isArray(val)) { + arrValues = key + '='; + reg = new RegExp('&'+key+'+=$'); + forEach(val, function (aValue) { + arrValues += encodeURIComponent(aValue) + '&' + key + '='; + }); + query.push(arrValues.replace(reg, '')); + } else { + query.push(key + '=' + encodeURIComponent(val)); + } + }); + return (query.length) ? '?' + query.join('&') : ''; + } + + return encode; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/getParam.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/getParam.js new file mode 100644 index 000000000..d9813724b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/getParam.js @@ -0,0 +1,14 @@ +define(['../string/typecast', './getQuery'], function (typecast, getQuery) { + + /** + * Get query parameter value. + */ + function getParam(url, param, shouldTypecast){ + var regexp = new RegExp('(\\?|&)'+ param + '=([^&]*)'), //matches `?param=value` or `¶m=value`, value = $2 + result = regexp.exec( getQuery(url) ), + val = (result && result[2])? result[2] : null; + return shouldTypecast === false? val : typecast(val); + } + + return getParam; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/getQuery.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/getQuery.js new file mode 100644 index 000000000..aa3d99f34 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/getQuery.js @@ -0,0 +1,13 @@ +define(function () { + + /** + * Gets full query as string with all special chars decoded. + */ + function getQuery(url) { + url = url.replace(/#.*/, ''); //removes hash (to avoid getting hash query) + var queryString = /\?[a-zA-Z0-9\=\&\%\$\-\_\.\+\!\*\'\(\)\,]+/.exec(url); //valid chars according to: http://www.ietf.org/rfc/rfc1738.txt + return (queryString)? decodeURIComponent(queryString[0]) : ''; + } + + return getQuery; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/parse.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/parse.js new file mode 100644 index 000000000..ac153e3f4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/parse.js @@ -0,0 +1,12 @@ +define(['./decode', './getQuery'], function (decode, getQuery) { + + /** + * Get query string, parses and decodes it. + */ + function parse(url, shouldTypecast) { + return decode(getQuery(url), shouldTypecast); + } + + return parse; +}); + diff --git a/node_modules/express-error-handler/node_modules/mout/src/queryString/setParam.js b/node_modules/express-error-handler/node_modules/mout/src/queryString/setParam.js new file mode 100644 index 000000000..97081aa7c --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/queryString/setParam.js @@ -0,0 +1,28 @@ +define(function () { + + /** + * Set query string parameter value + */ + function setParam(url, paramName, value){ + url = url || ''; + + var re = new RegExp('(\\?|&)'+ paramName +'=[^&]*' ); + var param = paramName +'='+ encodeURIComponent( value ); + + if ( re.test(url) ) { + return url.replace(re, '$1'+ param); + } else { + if (url.indexOf('?') === -1) { + url += '?'; + } + if (url.indexOf('=') !== -1) { + url += '&'; + } + return url + param; + } + + } + + return setParam; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random.js b/node_modules/express-error-handler/node_modules/mout/src/random.js new file mode 100644 index 000000000..b2641ee33 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random.js @@ -0,0 +1,16 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'choice' : require('./random/choice'), + 'guid' : require('./random/guid'), + 'rand' : require('./random/rand'), + 'randBit' : require('./random/randBit'), + 'randHex' : require('./random/randHex'), + 'randInt' : require('./random/randInt'), + 'randSign' : require('./random/randSign'), + 'random' : require('./random/random') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/choice.js b/node_modules/express-error-handler/node_modules/mout/src/random/choice.js new file mode 100644 index 000000000..0d0c38dff --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/choice.js @@ -0,0 +1,14 @@ +define(['./randInt', '../lang/isArray'], function (randInt, isArray) { + + /** + * Returns a random element from the supplied arguments + * or from the array (if single argument is an array). + */ + function choice(items) { + var target = (arguments.length === 1 && isArray(items))? items : arguments; + return target[ randInt(0, target.length - 1) ]; + } + + return choice; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/guid.js b/node_modules/express-error-handler/node_modules/mout/src/random/guid.js new file mode 100644 index 000000000..82f3a2db3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/guid.js @@ -0,0 +1,23 @@ +define(['./randHex', './choice'], function (randHex, choice) { + + /** + * Returns pseudo-random guid (UUID v4) + * IMPORTANT: it's not totally "safe" since randHex/choice uses Math.random + * by default and sequences can be predicted in some cases. See the + * "random/random" documentation for more info about it and how to replace + * the default PRNG. + */ + function guid() { + return ( + randHex(8)+'-'+ + randHex(4)+'-'+ + // v4 UUID always contain "4" at this position to specify it was + // randomly generated + '4' + randHex(3) +'-'+ + // v4 UUID always contain chars [a,b,8,9] at this position + choice(8, 9, 'a', 'b') + randHex(3)+'-'+ + randHex(12) + ); + } + return guid; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/rand.js b/node_modules/express-error-handler/node_modules/mout/src/random/rand.js new file mode 100644 index 000000000..b8c231dd2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/rand.js @@ -0,0 +1,13 @@ +define(['./random', '../number/MIN_INT', '../number/MAX_INT'], function(random, MIN_INT, MAX_INT){ + + /** + * Returns random number inside range + */ + function rand(min, max){ + min = min == null? MIN_INT : min; + max = max == null? MAX_INT : max; + return min + (max - min) * random(); + } + + return rand; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/randBit.js b/node_modules/express-error-handler/node_modules/mout/src/random/randBit.js new file mode 100644 index 000000000..b3422d2de --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/randBit.js @@ -0,0 +1,11 @@ +define(['./random'], function (random) { + + /** + * Returns random bit (0 or 1) + */ + function randomBit() { + return random() > 0.5? 1 : 0; + } + + return randomBit; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/randHex.js b/node_modules/express-error-handler/node_modules/mout/src/random/randHex.js new file mode 100644 index 000000000..6e9bf1c5d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/randHex.js @@ -0,0 +1,19 @@ +define(['./choice'], function (choice) { + + var _chars = '0123456789abcdef'.split(''); + + /** + * Returns a random hexadecimal string + */ + function randHex(size){ + size = size && size > 0? size : 6; + var str = ''; + while (size--) { + str += choice(_chars); + } + return str; + } + + return randHex; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/randInt.js b/node_modules/express-error-handler/node_modules/mout/src/random/randInt.js new file mode 100644 index 000000000..1750e9de4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/randInt.js @@ -0,0 +1,16 @@ +define(['../number/MIN_INT', '../number/MAX_INT', './rand'], function(MIN_INT, MAX_INT, rand){ + + /** + * Gets random integer inside range or snap to min/max values. + */ + function randInt(min, max){ + min = min == null? MIN_INT : ~~min; + max = max == null? MAX_INT : ~~max; + // can't be max + 0.5 otherwise it will round up if `rand` + // returns `max` causing it to overflow range. + // -0.5 and + 0.49 are required to avoid bias caused by rounding + return Math.round( rand(min - 0.5, max + 0.499999999999) ); + } + + return randInt; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/randSign.js b/node_modules/express-error-handler/node_modules/mout/src/random/randSign.js new file mode 100644 index 000000000..4141cdf67 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/randSign.js @@ -0,0 +1,11 @@ +define(['./random'], function (random) { + + /** + * Returns random sign (-1 or 1) + */ + function randomSign() { + return random() > 0.5? 1 : -1; + } + + return randomSign; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/random/random.js b/node_modules/express-error-handler/node_modules/mout/src/random/random.js new file mode 100644 index 000000000..4270822e2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/random/random.js @@ -0,0 +1,18 @@ +define(function () { + + /** + * Just a wrapper to Math.random. No methods inside mout/random should call + * Math.random() directly so we can inject the pseudo-random number + * generator if needed (ie. in case we need a seeded random or a better + * algorithm than the native one) + */ + function random(){ + return random.get(); + } + + // we expose the method so it can be swapped if needed + random.get = Math.random; + + return random; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string.js b/node_modules/express-error-handler/node_modules/mout/src/string.js new file mode 100644 index 000000000..a157e4cc8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string.js @@ -0,0 +1,46 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'WHITE_SPACES' : require('./string/WHITE_SPACES'), + 'camelCase' : require('./string/camelCase'), + 'contains' : require('./string/contains'), + 'crop' : require('./string/crop'), + 'endsWith' : require('./string/endsWith'), + 'escapeHtml' : require('./string/escapeHtml'), + 'escapeRegExp' : require('./string/escapeRegExp'), + 'escapeUnicode' : require('./string/escapeUnicode'), + 'hyphenate' : require('./string/hyphenate'), + 'insert' : require('./string/insert'), + 'interpolate' : require('./string/interpolate'), + 'lowerCase' : require('./string/lowerCase'), + 'lpad' : require('./string/lpad'), + 'ltrim' : require('./string/ltrim'), + 'makePath' : require('./string/makePath'), + 'normalizeLineBreaks' : require('./string/normalizeLineBreaks'), + 'pascalCase' : require('./string/pascalCase'), + 'properCase' : require('./string/properCase'), + 'removeNonASCII' : require('./string/removeNonASCII'), + 'removeNonWord' : require('./string/removeNonWord'), + 'repeat' : require('./string/repeat'), + 'replace' : require('./string/replace'), + 'replaceAccents' : require('./string/replaceAccents'), + 'rpad' : require('./string/rpad'), + 'rtrim' : require('./string/rtrim'), + 'sentenceCase' : require('./string/sentenceCase'), + 'slugify' : require('./string/slugify'), + 'startsWith' : require('./string/startsWith'), + 'stripHtmlTags' : require('./string/stripHtmlTags'), + 'trim' : require('./string/trim'), + 'truncate' : require('./string/truncate'), + 'typecast' : require('./string/typecast'), + 'unCamelCase' : require('./string/unCamelCase'), + 'underscore' : require('./string/underscore'), + 'unescapeHtml' : require('./string/unescapeHtml'), + 'unescapeUnicode' : require('./string/unescapeUnicode'), + 'unhyphenate' : require('./string/unhyphenate'), + 'upperCase' : require('./string/upperCase') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/WHITE_SPACES.js b/node_modules/express-error-handler/node_modules/mout/src/string/WHITE_SPACES.js new file mode 100644 index 000000000..e830d86df --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/WHITE_SPACES.js @@ -0,0 +1,12 @@ +define(function() { + /** + * Contains all Unicode white-spaces. Taken from + * http://en.wikipedia.org/wiki/Whitespace_character. + */ + return [ + ' ', '\n', '\r', '\t', '\f', '\v', '\u00A0', '\u1680', '\u180E', + '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', + '\u2007', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u202F', + '\u205F', '\u3000' + ]; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/camelCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/camelCase.js new file mode 100644 index 000000000..02e6c04d9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/camelCase.js @@ -0,0 +1,16 @@ +define(['../lang/toString', './replaceAccents', './removeNonWord', './upperCase', './lowerCase'], function(toString, replaceAccents, removeNonWord, upperCase, lowerCase){ + /** + * Convert string to camelCase text. + */ + function camelCase(str){ + str = toString(str); + str = replaceAccents(str); + str = removeNonWord(str) + .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces + .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE + .replace(/\s+/g, '') //remove spaces + .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase + return str; + } + return camelCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/contains.js b/node_modules/express-error-handler/node_modules/mout/src/string/contains.js new file mode 100644 index 000000000..825b5a5f6 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/contains.js @@ -0,0 +1,14 @@ +define(['../lang/toString'], function(toString) { + + /** + * Searches for a given substring + */ + function contains(str, substring, fromIndex){ + str = toString(str); + substring = toString(substring); + return str.indexOf(substring, fromIndex) !== -1; + } + + return contains; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/crop.js b/node_modules/express-error-handler/node_modules/mout/src/string/crop.js new file mode 100644 index 000000000..3c073f05d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/crop.js @@ -0,0 +1,11 @@ +define(['../lang/toString', './truncate'], function (toString, truncate) { + /** + * Truncate string at full words. + */ + function crop(str, maxChars, append) { + str = toString(str); + return truncate(str, maxChars, append, true); + } + + return crop; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/endsWith.js b/node_modules/express-error-handler/node_modules/mout/src/string/endsWith.js new file mode 100644 index 000000000..31a73f208 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/endsWith.js @@ -0,0 +1,13 @@ +define(['../lang/toString'], function(toString) { + /** + * Checks if string ends with specified suffix. + */ + function endsWith(str, suffix) { + str = toString(str); + suffix = toString(suffix); + + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + return endsWith; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/escapeHtml.js b/node_modules/express-error-handler/node_modules/mout/src/string/escapeHtml.js new file mode 100644 index 000000000..de34b61b0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/escapeHtml.js @@ -0,0 +1,18 @@ +define(['../lang/toString'], function(toString) { + + /** + * Escapes a string for insertion into HTML. + */ + function escapeHtml(str){ + str = toString(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/'/g, ''') + .replace(/"/g, '"'); + return str; + } + + return escapeHtml; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/escapeRegExp.js b/node_modules/express-error-handler/node_modules/mout/src/string/escapeRegExp.js new file mode 100644 index 000000000..32facac09 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/escapeRegExp.js @@ -0,0 +1,15 @@ +define(['../lang/toString'], function(toString) { + + var ESCAPE_CHARS = /[\\.+*?\^$\[\](){}\/'#]/g; + + /** + * Escape RegExp string chars. + */ + function escapeRegExp(str) { + str = toString(str); + return str.replace(ESCAPE_CHARS,'\\$&'); + } + + return escapeRegExp; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/escapeUnicode.js b/node_modules/express-error-handler/node_modules/mout/src/string/escapeUnicode.js new file mode 100644 index 000000000..bd5e8c4c0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/escapeUnicode.js @@ -0,0 +1,21 @@ +define(['../lang/toString'], function(toString) { + + /** + * Escape string into unicode sequences + */ + function escapeUnicode(str, shouldEscapePrintable){ + str = toString(str); + return str.replace(/[\s\S]/g, function(ch){ + // skip printable ASCII chars if we should not escape them + if (!shouldEscapePrintable && (/[\x20-\x7E]/).test(ch)) { + return ch; + } + // we use "000" and slice(-4) for brevity, need to pad zeros, + // unicode escape always have 4 chars after "\u" + return '\\u'+ ('000'+ ch.charCodeAt(0).toString(16)).slice(-4); + }); + } + + return escapeUnicode; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/hyphenate.js b/node_modules/express-error-handler/node_modules/mout/src/string/hyphenate.js new file mode 100644 index 000000000..679c405c3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/hyphenate.js @@ -0,0 +1,12 @@ +define(['../lang/toString', './slugify', './unCamelCase'], function(toString, slugify, unCamelCase){ + /** + * Replaces spaces with hyphens, split camelCase text, remove non-word chars, remove accents and convert to lower case. + */ + function hyphenate(str){ + str = toString(str); + str = unCamelCase(str); + return slugify(str, "-"); + } + + return hyphenate; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/insert.js b/node_modules/express-error-handler/node_modules/mout/src/string/insert.js new file mode 100644 index 000000000..79c45be7b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/insert.js @@ -0,0 +1,20 @@ +define(['../math/clamp', '../lang/toString'], function (clamp, toString) { + + /** + * Inserts a string at a given index. + */ + function insert(string, index, partial){ + string = toString(string); + + if (index < 0) { + index = string.length + index; + } + + index = clamp(index, 0, string.length); + + return string.substr(0, index) + partial + string.substr(index); + } + + return insert; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/interpolate.js b/node_modules/express-error-handler/node_modules/mout/src/string/interpolate.js new file mode 100644 index 000000000..ecb8ba80a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/interpolate.js @@ -0,0 +1,18 @@ +define(['../lang/toString'], function(toString) { + + var stache = /\{\{(\w+)\}\}/g; //mustache-like + + /** + * String interpolation + */ + function interpolate(template, replacements, syntax){ + template = toString(template); + var replaceFn = function(match, prop){ + return (prop in replacements)? toString(replacements[prop]) : ''; + }; + return template.replace(syntax || stache, replaceFn); + } + + return interpolate; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/lowerCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/lowerCase.js new file mode 100644 index 000000000..b045d69cd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/lowerCase.js @@ -0,0 +1,11 @@ +define(['../lang/toString'], function(toString){ + /** + * "Safer" String.toLowerCase() + */ + function lowerCase(str){ + str = toString(str); + return str.toLowerCase(); + } + + return lowerCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/lpad.js b/node_modules/express-error-handler/node_modules/mout/src/string/lpad.js new file mode 100644 index 000000000..134b4150b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/lpad.js @@ -0,0 +1,16 @@ +define(['../lang/toString', './repeat'], function(toString, repeat) { + + /** + * Pad string with `char` if its' length is smaller than `minLen` + */ + function lpad(str, minLen, ch) { + str = toString(str); + ch = ch || ' '; + + return (str.length < minLen) ? + repeat(ch, minLen - str.length) + str : str; + } + + return lpad; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/ltrim.js b/node_modules/express-error-handler/node_modules/mout/src/string/ltrim.js new file mode 100644 index 000000000..477df9539 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/ltrim.js @@ -0,0 +1,33 @@ +define(['../lang/toString', './WHITE_SPACES'], function(toString, WHITE_SPACES){ + /** + * Remove chars from beginning of string. + */ + function ltrim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + + var start = 0, + len = str.length, + charLen = chars.length, + found = true, + i, c; + + while (found && start < len) { + found = false; + i = -1; + c = str.charAt(start); + + while (++i < charLen) { + if (c === chars[i]) { + found = true; + start++; + break; + } + } + } + + return (start >= len) ? '' : str.substr(start, len); + } + + return ltrim; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/makePath.js b/node_modules/express-error-handler/node_modules/mout/src/string/makePath.js new file mode 100644 index 000000000..149275fdc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/makePath.js @@ -0,0 +1,14 @@ +define(['../array/join'], function(join){ + + /** + * Group arguments as path segments, if any of the args is `null` or an + * empty string it will be ignored from resulting path. + */ + function makePath(var_args){ + var result = join(Array.prototype.slice.call(arguments), '/'); + // need to disconsider duplicate '/' after protocol (eg: 'http://') + return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); + } + + return makePath; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/normalizeLineBreaks.js b/node_modules/express-error-handler/node_modules/mout/src/string/normalizeLineBreaks.js new file mode 100644 index 000000000..44e4194f8 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/normalizeLineBreaks.js @@ -0,0 +1,18 @@ +define(['../lang/toString'], function (toString) { + + /** + * Convert line-breaks from DOS/MAC to a single standard (UNIX by default) + */ + function normalizeLineBreaks(str, lineEnd) { + str = toString(str); + lineEnd = lineEnd || '\n'; + + return str + .replace(/\r\n/g, lineEnd) // DOS + .replace(/\r/g, lineEnd) // Mac + .replace(/\n/g, lineEnd); // Unix + } + + return normalizeLineBreaks; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/pascalCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/pascalCase.js new file mode 100644 index 000000000..ead9ead49 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/pascalCase.js @@ -0,0 +1,11 @@ +define(['../lang/toString', './camelCase', './upperCase'], function(toString, camelCase, upperCase){ + /** + * camelCase + UPPERCASE first char + */ + function pascalCase(str){ + str = toString(str); + return camelCase(str).replace(/^[a-z]/, upperCase); + } + + return pascalCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/properCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/properCase.js new file mode 100644 index 000000000..2987b507f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/properCase.js @@ -0,0 +1,11 @@ +define(['../lang/toString', './lowerCase', './upperCase'], function(toString, lowerCase, upperCase){ + /** + * UPPERCASE first char of each word. + */ + function properCase(str){ + str = toString(str); + return lowerCase(str).replace(/^\w|\s\w/g, upperCase); + } + + return properCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/removeNonASCII.js b/node_modules/express-error-handler/node_modules/mout/src/string/removeNonASCII.js new file mode 100644 index 000000000..4905869dc --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/removeNonASCII.js @@ -0,0 +1,14 @@ +define(['../lang/toString'], function(toString){ + /** + * Remove non-printable ASCII chars + */ + function removeNonASCII(str){ + str = toString(str); + + // Matches non-printable ASCII chars - + // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters + return str.replace(/[^\x20-\x7E]/g, ''); + } + + return removeNonASCII; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/removeNonWord.js b/node_modules/express-error-handler/node_modules/mout/src/string/removeNonWord.js new file mode 100644 index 000000000..2b1a20403 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/removeNonWord.js @@ -0,0 +1,11 @@ +define(['../lang/toString'], function(toString){ + /** + * Remove non-word chars. + */ + function removeNonWord(str){ + str = toString(str); + return str.replace(/[^0-9a-zA-Z\xC0-\xFF \-_]/g, ''); + } + + return removeNonWord; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/repeat.js b/node_modules/express-error-handler/node_modules/mout/src/string/repeat.js new file mode 100644 index 000000000..02f5659f9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/repeat.js @@ -0,0 +1,13 @@ +define(['../lang/toString'], function(toString){ + + /** + * Repeat string n times + */ + function repeat(str, n){ + str = toString(str); + return (new Array(n + 1)).join(str); + } + + return repeat; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/replace.js b/node_modules/express-error-handler/node_modules/mout/src/string/replace.js new file mode 100644 index 000000000..8b762fdcf --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/replace.js @@ -0,0 +1,32 @@ +define(['../lang/toString', '../lang/toArray'], function (toString, toArray) { + + /** + * Replace string(s) with the replacement(s) in the source. + */ + function replace(str, search, replacements) { + str = toString(str); + search = toArray(search); + replacements = toArray(replacements); + + var searchLength = search.length, + replacementsLength = replacements.length; + + if (replacementsLength !== 1 && searchLength !== replacementsLength) { + throw new Error('Unequal number of searches and replacements'); + } + + var i = -1; + while (++i < searchLength) { + // Use the first replacement for all searches if only one + // replacement is provided + str = str.replace( + search[i], + replacements[(replacementsLength === 1) ? 0 : i]); + } + + return str; + } + + return replace; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/replaceAccents.js b/node_modules/express-error-handler/node_modules/mout/src/string/replaceAccents.js new file mode 100644 index 000000000..3a63f55a5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/replaceAccents.js @@ -0,0 +1,36 @@ +define(['../lang/toString'], function(toString){ + /** + * Replaces all accented chars with regular ones + */ + function replaceAccents(str){ + str = toString(str); + + // verifies if the String has accents and replace them + if (str.search(/[\xC0-\xFF]/g) > -1) { + str = str + .replace(/[\xC0-\xC5]/g, "A") + .replace(/[\xC6]/g, "AE") + .replace(/[\xC7]/g, "C") + .replace(/[\xC8-\xCB]/g, "E") + .replace(/[\xCC-\xCF]/g, "I") + .replace(/[\xD0]/g, "D") + .replace(/[\xD1]/g, "N") + .replace(/[\xD2-\xD6\xD8]/g, "O") + .replace(/[\xD9-\xDC]/g, "U") + .replace(/[\xDD]/g, "Y") + .replace(/[\xDE]/g, "P") + .replace(/[\xE0-\xE5]/g, "a") + .replace(/[\xE6]/g, "ae") + .replace(/[\xE7]/g, "c") + .replace(/[\xE8-\xEB]/g, "e") + .replace(/[\xEC-\xEF]/g, "i") + .replace(/[\xF1]/g, "n") + .replace(/[\xF2-\xF6\xF8]/g, "o") + .replace(/[\xF9-\xFC]/g, "u") + .replace(/[\xFE]/g, "p") + .replace(/[\xFD\xFF]/g, "y"); + } + return str; + } + return replaceAccents; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/rpad.js b/node_modules/express-error-handler/node_modules/mout/src/string/rpad.js new file mode 100644 index 000000000..2efd9c882 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/rpad.js @@ -0,0 +1,14 @@ +define(['../lang/toString', './repeat'], function (toString, repeat) { + + /** + * Pad string with `char` if its' length is smaller than `minLen` + */ + function rpad(str, minLen, ch) { + str = toString(str); + ch = ch || ' '; + return (str.length < minLen)? str + repeat(ch, minLen - str.length) : str; + } + + return rpad; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/rtrim.js b/node_modules/express-error-handler/node_modules/mout/src/string/rtrim.js new file mode 100644 index 000000000..a4cc282d3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/rtrim.js @@ -0,0 +1,32 @@ +define(['../lang/toString', './WHITE_SPACES'], function(toString, WHITE_SPACES){ + /** + * Remove chars from end of string. + */ + function rtrim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + + var end = str.length - 1, + charLen = chars.length, + found = true, + i, c; + + while (found && end >= 0) { + found = false; + i = -1; + c = str.charAt(end); + + while (++i < charLen) { + if (c === chars[i]) { + found = true; + end--; + break; + } + } + } + + return (end >= 0) ? str.substring(0, end + 1) : ''; + } + + return rtrim; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/sentenceCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/sentenceCase.js new file mode 100644 index 000000000..cfe45af5f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/sentenceCase.js @@ -0,0 +1,13 @@ +define(['../lang/toString', './lowerCase', './upperCase'], function(toString, lowerCase, upperCase){ + /** + * UPPERCASE first char of each sentence and lowercase other chars. + */ + function sentenceCase(str){ + str = toString(str); + + // Replace first char of each sentence (new line or after '.\s+') to + // UPPERCASE + return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase); + } + return sentenceCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/slugify.js b/node_modules/express-error-handler/node_modules/mout/src/string/slugify.js new file mode 100644 index 000000000..c6d68c7eb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/slugify.js @@ -0,0 +1,21 @@ +define(['../lang/toString', './replaceAccents', './removeNonWord', './trim'], function(toString, replaceAccents, removeNonWord, trim){ + /** + * Convert to lower case, remove accents, remove non-word chars and + * replace spaces with the specified delimeter. + * Does not split camelCase text. + */ + function slugify(str, delimeter){ + str = toString(str); + + if (delimeter == null) { + delimeter = "-"; + } + str = replaceAccents(str); + str = removeNonWord(str); + str = trim(str) //should come after removeNonWord + .replace(/ +/g, delimeter) //replace spaces with delimeter + .toLowerCase(); + return str; + } + return slugify; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/startsWith.js b/node_modules/express-error-handler/node_modules/mout/src/string/startsWith.js new file mode 100644 index 000000000..88ae54536 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/startsWith.js @@ -0,0 +1,13 @@ +define(['../lang/toString'], function (toString) { + /** + * Checks if string starts with specified prefix. + */ + function startsWith(str, prefix) { + str = toString(str); + prefix = toString(prefix); + + return str.indexOf(prefix) === 0; + } + + return startsWith; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/stripHtmlTags.js b/node_modules/express-error-handler/node_modules/mout/src/string/stripHtmlTags.js new file mode 100644 index 000000000..e8da956d2 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/stripHtmlTags.js @@ -0,0 +1,11 @@ +define(['../lang/toString'], function(toString){ + /** + * Remove HTML tags from string. + */ + function stripHtmlTags(str){ + str = toString(str); + + return str.replace(/<[^>]*>/g, ''); + } + return stripHtmlTags; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/trim.js b/node_modules/express-error-handler/node_modules/mout/src/string/trim.js new file mode 100644 index 000000000..555260412 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/trim.js @@ -0,0 +1,12 @@ +define(['../lang/toString', './WHITE_SPACES', './ltrim', './rtrim'], function(toString, WHITE_SPACES, ltrim, rtrim){ + /** + * Remove white-spaces from beginning and end of string. + */ + function trim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + return ltrim(rtrim(str, chars), chars); + } + + return trim; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/truncate.js b/node_modules/express-error-handler/node_modules/mout/src/string/truncate.js new file mode 100644 index 000000000..34000d9f5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/truncate.js @@ -0,0 +1,20 @@ +define(['../lang/toString', './trim'], function(toString, trim){ + /** + * Limit number of chars. + */ + function truncate(str, maxChars, append, onlyFullWords){ + str = toString(str); + append = append || '...'; + maxChars = onlyFullWords? maxChars + 1 : maxChars; + + str = trim(str); + if(str.length <= maxChars){ + return str; + } + str = str.substr(0, maxChars - append.length); + //crop at last space or remove trailing whitespace + str = onlyFullWords? str.substr(0, str.lastIndexOf(' ')) : trim(str); + return str + append; + } + return truncate; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/typecast.js b/node_modules/express-error-handler/node_modules/mout/src/string/typecast.js new file mode 100644 index 000000000..a7c83153b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/typecast.js @@ -0,0 +1,29 @@ +define(function () { + + var UNDEF; + + /** + * Parses string and convert it into a native value. + */ + function typecast(val) { + var r; + if ( val === null || val === 'null' ) { + r = null; + } else if ( val === 'true' ) { + r = true; + } else if ( val === 'false' ) { + r = false; + } else if ( val === UNDEF || val === 'undefined' ) { + r = UNDEF; + } else if ( val === '' || isNaN(val) ) { + //isNaN('') returns false + r = val; + } else { + //parseFloat(null || '') returns NaN + r = parseFloat(val); + } + return r; + } + + return typecast; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/unCamelCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/unCamelCase.js new file mode 100644 index 000000000..eeef39b68 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/unCamelCase.js @@ -0,0 +1,23 @@ +define(['../lang/toString'], function(toString){ + + var CAMEL_CASE_BORDER = /([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g; + + /** + * Add space between camelCase text. + */ + function unCamelCase(str, delimiter){ + if (delimiter == null) { + delimiter = ' '; + } + + function join(str, c1, c2) { + return c1 + delimiter + c2; + } + + str = toString(str); + str = str.replace(CAMEL_CASE_BORDER, join); + str = str.toLowerCase(); //add space between camelCase text + return str; + } + return unCamelCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/underscore.js b/node_modules/express-error-handler/node_modules/mout/src/string/underscore.js new file mode 100644 index 000000000..75dd46498 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/underscore.js @@ -0,0 +1,11 @@ +define(['../lang/toString', './slugify', './unCamelCase'], function(toString, slugify, unCamelCase){ + /** + * Replaces spaces with underscores, split camelCase text, remove non-word chars, remove accents and convert to lower case. + */ + function underscore(str){ + str = toString(str); + str = unCamelCase(str); + return slugify(str, "_"); + } + return underscore; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/unescapeHtml.js b/node_modules/express-error-handler/node_modules/mout/src/string/unescapeHtml.js new file mode 100644 index 000000000..173c69c2f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/unescapeHtml.js @@ -0,0 +1,18 @@ +define(['../lang/toString'], function (toString) { + + /** + * Unescapes HTML special chars + */ + function unescapeHtml(str){ + str = toString(str) + .replace(/&/g , '&') + .replace(/</g , '<') + .replace(/>/g , '>') + .replace(/'/g , "'") + .replace(/"/g, '"'); + return str; + } + + return unescapeHtml; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/unescapeUnicode.js b/node_modules/express-error-handler/node_modules/mout/src/string/unescapeUnicode.js new file mode 100644 index 000000000..d4a7ba1da --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/unescapeUnicode.js @@ -0,0 +1,16 @@ +define(['../lang/toString'], function(toString) { + + /** + * Unescape unicode char sequences + */ + function unescapeUnicode(str){ + str = toString(str); + return str.replace(/\\u[0-9a-f]{4}/g, function(ch){ + var code = parseInt(ch.slice(2), 16); + return String.fromCharCode(code); + }); + } + + return unescapeUnicode; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/unhyphenate.js b/node_modules/express-error-handler/node_modules/mout/src/string/unhyphenate.js new file mode 100644 index 000000000..6ac2fa4c4 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/unhyphenate.js @@ -0,0 +1,10 @@ +define(['../lang/toString'], function(toString){ + /** + * Replaces hyphens with spaces. (only hyphens between word chars) + */ + function unhyphenate(str){ + str = toString(str); + return str.replace(/(\w)(-)(\w)/g, '$1 $3'); + } + return unhyphenate; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/string/upperCase.js b/node_modules/express-error-handler/node_modules/mout/src/string/upperCase.js new file mode 100644 index 000000000..8b2073e6d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/string/upperCase.js @@ -0,0 +1,10 @@ +define(['../lang/toString'], function(toString){ + /** + * "Safer" String.toUpperCase() + */ + function upperCase(str){ + str = toString(str); + return str.toUpperCase(); + } + return upperCase; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/time.js b/node_modules/express-error-handler/node_modules/mout/src/time.js new file mode 100644 index 000000000..67c906856 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/time.js @@ -0,0 +1,12 @@ +define(function(require){ + +//automatically generated, do not edit! +//run `node build` instead +return { + 'convert' : require('./time/convert'), + 'now' : require('./time/now'), + 'parseMs' : require('./time/parseMs'), + 'toTimeString' : require('./time/toTimeString') +}; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/time/convert.js b/node_modules/express-error-handler/node_modules/mout/src/time/convert.js new file mode 100644 index 000000000..2de0cf2e1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/time/convert.js @@ -0,0 +1,41 @@ +define(function () { + + /** + * convert time into another unit + */ + function convert(val, sourceUnitName, destinationUnitName){ + destinationUnitName = destinationUnitName || 'ms'; + return (val * getUnit(sourceUnitName)) / getUnit(destinationUnitName); + } + + + //TODO: maybe extract to a separate module + function getUnit(unitName){ + switch(unitName){ + case 'ms': + case 'millisecond': + return 1; + case 's': + case 'second': + return 1000; + case 'm': + case 'minute': + return 60000; + case 'h': + case 'hour': + return 3600000; + case 'd': + case 'day': + return 86400000; + case 'w': + case 'week': + return 604800000; + default: + throw new Error('"'+ unitName + '" is not a valid unit'); + } + } + + + return convert; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/time/now.js b/node_modules/express-error-handler/node_modules/mout/src/time/now.js new file mode 100644 index 000000000..a3a38bcb9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/time/now.js @@ -0,0 +1,12 @@ +define(function () { + + /** + * Get current time in miliseconds + */ + var now = (typeof Date.now === 'function')? Date.now : function(){ + return +(new Date()); + }; + + return now; + +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/time/parseMs.js b/node_modules/express-error-handler/node_modules/mout/src/time/parseMs.js new file mode 100644 index 000000000..964929ae5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/time/parseMs.js @@ -0,0 +1,17 @@ +define(['../math/countSteps'], function(countSteps){ + + /** + * Parse timestamp into an object. + */ + function parseMs(ms){ + return { + milliseconds : countSteps(ms, 1, 1000), + seconds : countSteps(ms, 1000, 60), + minutes : countSteps(ms, 60000, 60), + hours : countSteps(ms, 3600000, 24), + days : countSteps(ms, 86400000) + }; + } + + return parseMs; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/src/time/toTimeString.js b/node_modules/express-error-handler/node_modules/mout/src/time/toTimeString.js new file mode 100644 index 000000000..edf182180 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/src/time/toTimeString.js @@ -0,0 +1,23 @@ +define(['../math/countSteps', '../number/pad'], function(countSteps, pad){ + + var HOUR = 3600000, + MINUTE = 60000, + SECOND = 1000; + + /** + * Format timestamp into a time string. + */ + function toTimeString(ms){ + var h = ms < HOUR ? 0 : countSteps(ms, HOUR), + m = ms < MINUTE ? 0 : countSteps(ms, MINUTE, 60), + s = ms < SECOND ? 0 : countSteps(ms, SECOND, 60), + str = ''; + + str += h? h + ':' : ''; + str += pad(m, 2) + ':'; + str += pad(s, 2); + + return str; + } + return toTimeString; +}); diff --git a/node_modules/express-error-handler/node_modules/mout/string.js b/node_modules/express-error-handler/node_modules/mout/string.js new file mode 100644 index 000000000..6115811ae --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string.js @@ -0,0 +1,46 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'WHITE_SPACES' : require('./string/WHITE_SPACES'), + 'camelCase' : require('./string/camelCase'), + 'contains' : require('./string/contains'), + 'crop' : require('./string/crop'), + 'endsWith' : require('./string/endsWith'), + 'escapeHtml' : require('./string/escapeHtml'), + 'escapeRegExp' : require('./string/escapeRegExp'), + 'escapeUnicode' : require('./string/escapeUnicode'), + 'hyphenate' : require('./string/hyphenate'), + 'insert' : require('./string/insert'), + 'interpolate' : require('./string/interpolate'), + 'lowerCase' : require('./string/lowerCase'), + 'lpad' : require('./string/lpad'), + 'ltrim' : require('./string/ltrim'), + 'makePath' : require('./string/makePath'), + 'normalizeLineBreaks' : require('./string/normalizeLineBreaks'), + 'pascalCase' : require('./string/pascalCase'), + 'properCase' : require('./string/properCase'), + 'removeNonASCII' : require('./string/removeNonASCII'), + 'removeNonWord' : require('./string/removeNonWord'), + 'repeat' : require('./string/repeat'), + 'replace' : require('./string/replace'), + 'replaceAccents' : require('./string/replaceAccents'), + 'rpad' : require('./string/rpad'), + 'rtrim' : require('./string/rtrim'), + 'sentenceCase' : require('./string/sentenceCase'), + 'slugify' : require('./string/slugify'), + 'startsWith' : require('./string/startsWith'), + 'stripHtmlTags' : require('./string/stripHtmlTags'), + 'trim' : require('./string/trim'), + 'truncate' : require('./string/truncate'), + 'typecast' : require('./string/typecast'), + 'unCamelCase' : require('./string/unCamelCase'), + 'underscore' : require('./string/underscore'), + 'unescapeHtml' : require('./string/unescapeHtml'), + 'unescapeUnicode' : require('./string/unescapeUnicode'), + 'unhyphenate' : require('./string/unhyphenate'), + 'upperCase' : require('./string/upperCase') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/WHITE_SPACES.js b/node_modules/express-error-handler/node_modules/mout/string/WHITE_SPACES.js new file mode 100644 index 000000000..03e012547 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/WHITE_SPACES.js @@ -0,0 +1,12 @@ + + /** + * Contains all Unicode white-spaces. Taken from + * http://en.wikipedia.org/wiki/Whitespace_character. + */ + module.exports = [ + ' ', '\n', '\r', '\t', '\f', '\v', '\u00A0', '\u1680', '\u180E', + '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', + '\u2007', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u202F', + '\u205F', '\u3000' + ]; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/camelCase.js b/node_modules/express-error-handler/node_modules/mout/string/camelCase.js new file mode 100644 index 000000000..aadb69a20 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/camelCase.js @@ -0,0 +1,20 @@ +var toString = require('../lang/toString'); +var replaceAccents = require('./replaceAccents'); +var removeNonWord = require('./removeNonWord'); +var upperCase = require('./upperCase'); +var lowerCase = require('./lowerCase'); + /** + * Convert string to camelCase text. + */ + function camelCase(str){ + str = toString(str); + str = replaceAccents(str); + str = removeNonWord(str) + .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces + .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE + .replace(/\s+/g, '') //remove spaces + .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase + return str; + } + module.exports = camelCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/contains.js b/node_modules/express-error-handler/node_modules/mout/string/contains.js new file mode 100644 index 000000000..cb22cae48 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/contains.js @@ -0,0 +1,14 @@ +var toString = require('../lang/toString'); + + /** + * Searches for a given substring + */ + function contains(str, substring, fromIndex){ + str = toString(str); + substring = toString(substring); + return str.indexOf(substring, fromIndex) !== -1; + } + + module.exports = contains; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/crop.js b/node_modules/express-error-handler/node_modules/mout/string/crop.js new file mode 100644 index 000000000..53b93b49e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/crop.js @@ -0,0 +1,12 @@ +var toString = require('../lang/toString'); +var truncate = require('./truncate'); + /** + * Truncate string at full words. + */ + function crop(str, maxChars, append) { + str = toString(str); + return truncate(str, maxChars, append, true); + } + + module.exports = crop; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/endsWith.js b/node_modules/express-error-handler/node_modules/mout/string/endsWith.js new file mode 100644 index 000000000..d504e9dd3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/endsWith.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); + /** + * Checks if string ends with specified suffix. + */ + function endsWith(str, suffix) { + str = toString(str); + suffix = toString(suffix); + + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + module.exports = endsWith; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/escapeHtml.js b/node_modules/express-error-handler/node_modules/mout/string/escapeHtml.js new file mode 100644 index 000000000..e67c4b21e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/escapeHtml.js @@ -0,0 +1,18 @@ +var toString = require('../lang/toString'); + + /** + * Escapes a string for insertion into HTML. + */ + function escapeHtml(str){ + str = toString(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/'/g, ''') + .replace(/"/g, '"'); + return str; + } + + module.exports = escapeHtml; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/escapeRegExp.js b/node_modules/express-error-handler/node_modules/mout/string/escapeRegExp.js new file mode 100644 index 000000000..70cb84ff0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/escapeRegExp.js @@ -0,0 +1,15 @@ +var toString = require('../lang/toString'); + + var ESCAPE_CHARS = /[\\.+*?\^$\[\](){}\/'#]/g; + + /** + * Escape RegExp string chars. + */ + function escapeRegExp(str) { + str = toString(str); + return str.replace(ESCAPE_CHARS,'\\$&'); + } + + module.exports = escapeRegExp; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/escapeUnicode.js b/node_modules/express-error-handler/node_modules/mout/string/escapeUnicode.js new file mode 100644 index 000000000..ec649adf3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/escapeUnicode.js @@ -0,0 +1,21 @@ +var toString = require('../lang/toString'); + + /** + * Escape string into unicode sequences + */ + function escapeUnicode(str, shouldEscapePrintable){ + str = toString(str); + return str.replace(/[\s\S]/g, function(ch){ + // skip printable ASCII chars if we should not escape them + if (!shouldEscapePrintable && (/[\x20-\x7E]/).test(ch)) { + return ch; + } + // we use "000" and slice(-4) for brevity, need to pad zeros, + // unicode escape always have 4 chars after "\u" + return '\\u'+ ('000'+ ch.charCodeAt(0).toString(16)).slice(-4); + }); + } + + module.exports = escapeUnicode; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/hyphenate.js b/node_modules/express-error-handler/node_modules/mout/string/hyphenate.js new file mode 100644 index 000000000..95e324364 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/hyphenate.js @@ -0,0 +1,14 @@ +var toString = require('../lang/toString'); +var slugify = require('./slugify'); +var unCamelCase = require('./unCamelCase'); + /** + * Replaces spaces with hyphens, split camelCase text, remove non-word chars, remove accents and convert to lower case. + */ + function hyphenate(str){ + str = toString(str); + str = unCamelCase(str); + return slugify(str, "-"); + } + + module.exports = hyphenate; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/insert.js b/node_modules/express-error-handler/node_modules/mout/string/insert.js new file mode 100644 index 000000000..8f042c6d1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/insert.js @@ -0,0 +1,21 @@ +var clamp = require('../math/clamp'); +var toString = require('../lang/toString'); + + /** + * Inserts a string at a given index. + */ + function insert(string, index, partial){ + string = toString(string); + + if (index < 0) { + index = string.length + index; + } + + index = clamp(index, 0, string.length); + + return string.substr(0, index) + partial + string.substr(index); + } + + module.exports = insert; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/interpolate.js b/node_modules/express-error-handler/node_modules/mout/string/interpolate.js new file mode 100644 index 000000000..ac88fac2d --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/interpolate.js @@ -0,0 +1,18 @@ +var toString = require('../lang/toString'); + + var stache = /\{\{(\w+)\}\}/g; //mustache-like + + /** + * String interpolation + */ + function interpolate(template, replacements, syntax){ + template = toString(template); + var replaceFn = function(match, prop){ + return (prop in replacements)? toString(replacements[prop]) : ''; + }; + return template.replace(syntax || stache, replaceFn); + } + + module.exports = interpolate; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/lowerCase.js b/node_modules/express-error-handler/node_modules/mout/string/lowerCase.js new file mode 100644 index 000000000..30bb7ad9b --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/lowerCase.js @@ -0,0 +1,11 @@ +var toString = require('../lang/toString'); + /** + * "Safer" String.toLowerCase() + */ + function lowerCase(str){ + str = toString(str); + return str.toLowerCase(); + } + + module.exports = lowerCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/lpad.js b/node_modules/express-error-handler/node_modules/mout/string/lpad.js new file mode 100644 index 000000000..63641d3f5 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/lpad.js @@ -0,0 +1,17 @@ +var toString = require('../lang/toString'); +var repeat = require('./repeat'); + + /** + * Pad string with `char` if its' length is smaller than `minLen` + */ + function lpad(str, minLen, ch) { + str = toString(str); + ch = ch || ' '; + + return (str.length < minLen) ? + repeat(ch, minLen - str.length) + str : str; + } + + module.exports = lpad; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/ltrim.js b/node_modules/express-error-handler/node_modules/mout/string/ltrim.js new file mode 100644 index 000000000..23d7b33fa --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/ltrim.js @@ -0,0 +1,34 @@ +var toString = require('../lang/toString'); +var WHITE_SPACES = require('./WHITE_SPACES'); + /** + * Remove chars from beginning of string. + */ + function ltrim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + + var start = 0, + len = str.length, + charLen = chars.length, + found = true, + i, c; + + while (found && start < len) { + found = false; + i = -1; + c = str.charAt(start); + + while (++i < charLen) { + if (c === chars[i]) { + found = true; + start++; + break; + } + } + } + + return (start >= len) ? '' : str.substr(start, len); + } + + module.exports = ltrim; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/makePath.js b/node_modules/express-error-handler/node_modules/mout/string/makePath.js new file mode 100644 index 000000000..81a1a6e00 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/makePath.js @@ -0,0 +1,14 @@ +var join = require('../array/join'); + + /** + * Group arguments as path segments, if any of the args is `null` or an + * empty string it will be ignored from resulting path. + */ + function makePath(var_args){ + var result = join(Array.prototype.slice.call(arguments), '/'); + // need to disconsider duplicate '/' after protocol (eg: 'http://') + return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); + } + + module.exports = makePath; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/normalizeLineBreaks.js b/node_modules/express-error-handler/node_modules/mout/string/normalizeLineBreaks.js new file mode 100644 index 000000000..8a8dccfdd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/normalizeLineBreaks.js @@ -0,0 +1,18 @@ +var toString = require('../lang/toString'); + + /** + * Convert line-breaks from DOS/MAC to a single standard (UNIX by default) + */ + function normalizeLineBreaks(str, lineEnd) { + str = toString(str); + lineEnd = lineEnd || '\n'; + + return str + .replace(/\r\n/g, lineEnd) // DOS + .replace(/\r/g, lineEnd) // Mac + .replace(/\n/g, lineEnd); // Unix + } + + module.exports = normalizeLineBreaks; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/pascalCase.js b/node_modules/express-error-handler/node_modules/mout/string/pascalCase.js new file mode 100644 index 000000000..fd1903538 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/pascalCase.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); +var camelCase = require('./camelCase'); +var upperCase = require('./upperCase'); + /** + * camelCase + UPPERCASE first char + */ + function pascalCase(str){ + str = toString(str); + return camelCase(str).replace(/^[a-z]/, upperCase); + } + + module.exports = pascalCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/properCase.js b/node_modules/express-error-handler/node_modules/mout/string/properCase.js new file mode 100644 index 000000000..61636be47 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/properCase.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); +var lowerCase = require('./lowerCase'); +var upperCase = require('./upperCase'); + /** + * UPPERCASE first char of each word. + */ + function properCase(str){ + str = toString(str); + return lowerCase(str).replace(/^\w|\s\w/g, upperCase); + } + + module.exports = properCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/removeNonASCII.js b/node_modules/express-error-handler/node_modules/mout/string/removeNonASCII.js new file mode 100644 index 000000000..fb463816e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/removeNonASCII.js @@ -0,0 +1,14 @@ +var toString = require('../lang/toString'); + /** + * Remove non-printable ASCII chars + */ + function removeNonASCII(str){ + str = toString(str); + + // Matches non-printable ASCII chars - + // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters + return str.replace(/[^\x20-\x7E]/g, ''); + } + + module.exports = removeNonASCII; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/removeNonWord.js b/node_modules/express-error-handler/node_modules/mout/string/removeNonWord.js new file mode 100644 index 000000000..bdd153b9f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/removeNonWord.js @@ -0,0 +1,11 @@ +var toString = require('../lang/toString'); + /** + * Remove non-word chars. + */ + function removeNonWord(str){ + str = toString(str); + return str.replace(/[^0-9a-zA-Z\xC0-\xFF \-_]/g, ''); + } + + module.exports = removeNonWord; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/repeat.js b/node_modules/express-error-handler/node_modules/mout/string/repeat.js new file mode 100644 index 000000000..0f9b4754e --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/repeat.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); + + /** + * Repeat string n times + */ + function repeat(str, n){ + str = toString(str); + return (new Array(n + 1)).join(str); + } + + module.exports = repeat; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/replace.js b/node_modules/express-error-handler/node_modules/mout/string/replace.js new file mode 100644 index 000000000..14433fc72 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/replace.js @@ -0,0 +1,33 @@ +var toString = require('../lang/toString'); +var toArray = require('../lang/toArray'); + + /** + * Replace string(s) with the replacement(s) in the source. + */ + function replace(str, search, replacements) { + str = toString(str); + search = toArray(search); + replacements = toArray(replacements); + + var searchLength = search.length, + replacementsLength = replacements.length; + + if (replacementsLength !== 1 && searchLength !== replacementsLength) { + throw new Error('Unequal number of searches and replacements'); + } + + var i = -1; + while (++i < searchLength) { + // Use the first replacement for all searches if only one + // replacement is provided + str = str.replace( + search[i], + replacements[(replacementsLength === 1) ? 0 : i]); + } + + return str; + } + + module.exports = replace; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/replaceAccents.js b/node_modules/express-error-handler/node_modules/mout/string/replaceAccents.js new file mode 100644 index 000000000..bb2212655 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/replaceAccents.js @@ -0,0 +1,36 @@ +var toString = require('../lang/toString'); + /** + * Replaces all accented chars with regular ones + */ + function replaceAccents(str){ + str = toString(str); + + // verifies if the String has accents and replace them + if (str.search(/[\xC0-\xFF]/g) > -1) { + str = str + .replace(/[\xC0-\xC5]/g, "A") + .replace(/[\xC6]/g, "AE") + .replace(/[\xC7]/g, "C") + .replace(/[\xC8-\xCB]/g, "E") + .replace(/[\xCC-\xCF]/g, "I") + .replace(/[\xD0]/g, "D") + .replace(/[\xD1]/g, "N") + .replace(/[\xD2-\xD6\xD8]/g, "O") + .replace(/[\xD9-\xDC]/g, "U") + .replace(/[\xDD]/g, "Y") + .replace(/[\xDE]/g, "P") + .replace(/[\xE0-\xE5]/g, "a") + .replace(/[\xE6]/g, "ae") + .replace(/[\xE7]/g, "c") + .replace(/[\xE8-\xEB]/g, "e") + .replace(/[\xEC-\xEF]/g, "i") + .replace(/[\xF1]/g, "n") + .replace(/[\xF2-\xF6\xF8]/g, "o") + .replace(/[\xF9-\xFC]/g, "u") + .replace(/[\xFE]/g, "p") + .replace(/[\xFD\xFF]/g, "y"); + } + return str; + } + module.exports = replaceAccents; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/rpad.js b/node_modules/express-error-handler/node_modules/mout/string/rpad.js new file mode 100644 index 000000000..99f6378d9 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/rpad.js @@ -0,0 +1,15 @@ +var toString = require('../lang/toString'); +var repeat = require('./repeat'); + + /** + * Pad string with `char` if its' length is smaller than `minLen` + */ + function rpad(str, minLen, ch) { + str = toString(str); + ch = ch || ' '; + return (str.length < minLen)? str + repeat(ch, minLen - str.length) : str; + } + + module.exports = rpad; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/rtrim.js b/node_modules/express-error-handler/node_modules/mout/string/rtrim.js new file mode 100644 index 000000000..66ba80e98 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/rtrim.js @@ -0,0 +1,33 @@ +var toString = require('../lang/toString'); +var WHITE_SPACES = require('./WHITE_SPACES'); + /** + * Remove chars from end of string. + */ + function rtrim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + + var end = str.length - 1, + charLen = chars.length, + found = true, + i, c; + + while (found && end >= 0) { + found = false; + i = -1; + c = str.charAt(end); + + while (++i < charLen) { + if (c === chars[i]) { + found = true; + end--; + break; + } + } + } + + return (end >= 0) ? str.substring(0, end + 1) : ''; + } + + module.exports = rtrim; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/sentenceCase.js b/node_modules/express-error-handler/node_modules/mout/string/sentenceCase.js new file mode 100644 index 000000000..354104c65 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/sentenceCase.js @@ -0,0 +1,15 @@ +var toString = require('../lang/toString'); +var lowerCase = require('./lowerCase'); +var upperCase = require('./upperCase'); + /** + * UPPERCASE first char of each sentence and lowercase other chars. + */ + function sentenceCase(str){ + str = toString(str); + + // Replace first char of each sentence (new line or after '.\s+') to + // UPPERCASE + return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase); + } + module.exports = sentenceCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/slugify.js b/node_modules/express-error-handler/node_modules/mout/string/slugify.js new file mode 100644 index 000000000..142f0d9b7 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/slugify.js @@ -0,0 +1,24 @@ +var toString = require('../lang/toString'); +var replaceAccents = require('./replaceAccents'); +var removeNonWord = require('./removeNonWord'); +var trim = require('./trim'); + /** + * Convert to lower case, remove accents, remove non-word chars and + * replace spaces with the specified delimeter. + * Does not split camelCase text. + */ + function slugify(str, delimeter){ + str = toString(str); + + if (delimeter == null) { + delimeter = "-"; + } + str = replaceAccents(str); + str = removeNonWord(str); + str = trim(str) //should come after removeNonWord + .replace(/ +/g, delimeter) //replace spaces with delimeter + .toLowerCase(); + return str; + } + module.exports = slugify; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/startsWith.js b/node_modules/express-error-handler/node_modules/mout/string/startsWith.js new file mode 100644 index 000000000..bce2bd20a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/startsWith.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); + /** + * Checks if string starts with specified prefix. + */ + function startsWith(str, prefix) { + str = toString(str); + prefix = toString(prefix); + + return str.indexOf(prefix) === 0; + } + + module.exports = startsWith; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/stripHtmlTags.js b/node_modules/express-error-handler/node_modules/mout/string/stripHtmlTags.js new file mode 100644 index 000000000..01d17b0eb --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/stripHtmlTags.js @@ -0,0 +1,11 @@ +var toString = require('../lang/toString'); + /** + * Remove HTML tags from string. + */ + function stripHtmlTags(str){ + str = toString(str); + + return str.replace(/<[^>]*>/g, ''); + } + module.exports = stripHtmlTags; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/trim.js b/node_modules/express-error-handler/node_modules/mout/string/trim.js new file mode 100644 index 000000000..9652b0c74 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/trim.js @@ -0,0 +1,15 @@ +var toString = require('../lang/toString'); +var WHITE_SPACES = require('./WHITE_SPACES'); +var ltrim = require('./ltrim'); +var rtrim = require('./rtrim'); + /** + * Remove white-spaces from beginning and end of string. + */ + function trim(str, chars) { + str = toString(str); + chars = chars || WHITE_SPACES; + return ltrim(rtrim(str, chars), chars); + } + + module.exports = trim; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/truncate.js b/node_modules/express-error-handler/node_modules/mout/string/truncate.js new file mode 100644 index 000000000..a98d6c7d1 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/truncate.js @@ -0,0 +1,21 @@ +var toString = require('../lang/toString'); +var trim = require('./trim'); + /** + * Limit number of chars. + */ + function truncate(str, maxChars, append, onlyFullWords){ + str = toString(str); + append = append || '...'; + maxChars = onlyFullWords? maxChars + 1 : maxChars; + + str = trim(str); + if(str.length <= maxChars){ + return str; + } + str = str.substr(0, maxChars - append.length); + //crop at last space or remove trailing whitespace + str = onlyFullWords? str.substr(0, str.lastIndexOf(' ')) : trim(str); + return str + append; + } + module.exports = truncate; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/typecast.js b/node_modules/express-error-handler/node_modules/mout/string/typecast.js new file mode 100644 index 000000000..c1386a49f --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/typecast.js @@ -0,0 +1,29 @@ + + + var UNDEF; + + /** + * Parses string and convert it into a native value. + */ + function typecast(val) { + var r; + if ( val === null || val === 'null' ) { + r = null; + } else if ( val === 'true' ) { + r = true; + } else if ( val === 'false' ) { + r = false; + } else if ( val === UNDEF || val === 'undefined' ) { + r = UNDEF; + } else if ( val === '' || isNaN(val) ) { + //isNaN('') returns false + r = val; + } else { + //parseFloat(null || '') returns NaN + r = parseFloat(val); + } + return r; + } + + module.exports = typecast; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/unCamelCase.js b/node_modules/express-error-handler/node_modules/mout/string/unCamelCase.js new file mode 100644 index 000000000..4968f378a --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/unCamelCase.js @@ -0,0 +1,23 @@ +var toString = require('../lang/toString'); + + var CAMEL_CASE_BORDER = /([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g; + + /** + * Add space between camelCase text. + */ + function unCamelCase(str, delimiter){ + if (delimiter == null) { + delimiter = ' '; + } + + function join(str, c1, c2) { + return c1 + delimiter + c2; + } + + str = toString(str); + str = str.replace(CAMEL_CASE_BORDER, join); + str = str.toLowerCase(); //add space between camelCase text + return str; + } + module.exports = unCamelCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/underscore.js b/node_modules/express-error-handler/node_modules/mout/string/underscore.js new file mode 100644 index 000000000..ebd6e2b77 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/underscore.js @@ -0,0 +1,13 @@ +var toString = require('../lang/toString'); +var slugify = require('./slugify'); +var unCamelCase = require('./unCamelCase'); + /** + * Replaces spaces with underscores, split camelCase text, remove non-word chars, remove accents and convert to lower case. + */ + function underscore(str){ + str = toString(str); + str = unCamelCase(str); + return slugify(str, "_"); + } + module.exports = underscore; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/unescapeHtml.js b/node_modules/express-error-handler/node_modules/mout/string/unescapeHtml.js new file mode 100644 index 000000000..52cf3f454 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/unescapeHtml.js @@ -0,0 +1,18 @@ +var toString = require('../lang/toString'); + + /** + * Unescapes HTML special chars + */ + function unescapeHtml(str){ + str = toString(str) + .replace(/&/g , '&') + .replace(/</g , '<') + .replace(/>/g , '>') + .replace(/'/g , "'") + .replace(/"/g, '"'); + return str; + } + + module.exports = unescapeHtml; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/unescapeUnicode.js b/node_modules/express-error-handler/node_modules/mout/string/unescapeUnicode.js new file mode 100644 index 000000000..0b7fb73bd --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/unescapeUnicode.js @@ -0,0 +1,16 @@ +var toString = require('../lang/toString'); + + /** + * Unescape unicode char sequences + */ + function unescapeUnicode(str){ + str = toString(str); + return str.replace(/\\u[0-9a-f]{4}/g, function(ch){ + var code = parseInt(ch.slice(2), 16); + return String.fromCharCode(code); + }); + } + + module.exports = unescapeUnicode; + + diff --git a/node_modules/express-error-handler/node_modules/mout/string/unhyphenate.js b/node_modules/express-error-handler/node_modules/mout/string/unhyphenate.js new file mode 100644 index 000000000..311dfa173 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/unhyphenate.js @@ -0,0 +1,10 @@ +var toString = require('../lang/toString'); + /** + * Replaces hyphens with spaces. (only hyphens between word chars) + */ + function unhyphenate(str){ + str = toString(str); + return str.replace(/(\w)(-)(\w)/g, '$1 $3'); + } + module.exports = unhyphenate; + diff --git a/node_modules/express-error-handler/node_modules/mout/string/upperCase.js b/node_modules/express-error-handler/node_modules/mout/string/upperCase.js new file mode 100644 index 000000000..6c92552c3 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/string/upperCase.js @@ -0,0 +1,10 @@ +var toString = require('../lang/toString'); + /** + * "Safer" String.toUpperCase() + */ + function upperCase(str){ + str = toString(str); + return str.toUpperCase(); + } + module.exports = upperCase; + diff --git a/node_modules/express-error-handler/node_modules/mout/time.js b/node_modules/express-error-handler/node_modules/mout/time.js new file mode 100644 index 000000000..9f5332968 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/time.js @@ -0,0 +1,12 @@ + + +//automatically generated, do not edit! +//run `node build` instead +module.exports = { + 'convert' : require('./time/convert'), + 'now' : require('./time/now'), + 'parseMs' : require('./time/parseMs'), + 'toTimeString' : require('./time/toTimeString') +}; + + diff --git a/node_modules/express-error-handler/node_modules/mout/time/convert.js b/node_modules/express-error-handler/node_modules/mout/time/convert.js new file mode 100644 index 000000000..852a0f036 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/time/convert.js @@ -0,0 +1,41 @@ + + + /** + * convert time into another unit + */ + function convert(val, sourceUnitName, destinationUnitName){ + destinationUnitName = destinationUnitName || 'ms'; + return (val * getUnit(sourceUnitName)) / getUnit(destinationUnitName); + } + + + //TODO: maybe extract to a separate module + function getUnit(unitName){ + switch(unitName){ + case 'ms': + case 'millisecond': + return 1; + case 's': + case 'second': + return 1000; + case 'm': + case 'minute': + return 60000; + case 'h': + case 'hour': + return 3600000; + case 'd': + case 'day': + return 86400000; + case 'w': + case 'week': + return 604800000; + default: + throw new Error('"'+ unitName + '" is not a valid unit'); + } + } + + + module.exports = convert; + + diff --git a/node_modules/express-error-handler/node_modules/mout/time/now.js b/node_modules/express-error-handler/node_modules/mout/time/now.js new file mode 100644 index 000000000..effcfbe37 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/time/now.js @@ -0,0 +1,12 @@ + + + /** + * Get current time in miliseconds + */ + var now = (typeof Date.now === 'function')? Date.now : function(){ + return +(new Date()); + }; + + module.exports = now; + + diff --git a/node_modules/express-error-handler/node_modules/mout/time/parseMs.js b/node_modules/express-error-handler/node_modules/mout/time/parseMs.js new file mode 100644 index 000000000..6d9979769 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/time/parseMs.js @@ -0,0 +1,17 @@ +var countSteps = require('../math/countSteps'); + + /** + * Parse timestamp into an object. + */ + function parseMs(ms){ + return { + milliseconds : countSteps(ms, 1, 1000), + seconds : countSteps(ms, 1000, 60), + minutes : countSteps(ms, 60000, 60), + hours : countSteps(ms, 3600000, 24), + days : countSteps(ms, 86400000) + }; + } + + module.exports = parseMs; + diff --git a/node_modules/express-error-handler/node_modules/mout/time/toTimeString.js b/node_modules/express-error-handler/node_modules/mout/time/toTimeString.js new file mode 100644 index 000000000..101d69fc0 --- /dev/null +++ b/node_modules/express-error-handler/node_modules/mout/time/toTimeString.js @@ -0,0 +1,24 @@ +var countSteps = require('../math/countSteps'); +var pad = require('../number/pad'); + + var HOUR = 3600000, + MINUTE = 60000, + SECOND = 1000; + + /** + * Format timestamp into a time string. + */ + function toTimeString(ms){ + var h = ms < HOUR ? 0 : countSteps(ms, HOUR), + m = ms < MINUTE ? 0 : countSteps(ms, MINUTE, 60), + s = ms < SECOND ? 0 : countSteps(ms, SECOND, 60), + str = ''; + + str += h? h + ':' : ''; + str += pad(m, 2) + ':'; + str += pad(s, 2); + + return str; + } + module.exports = toTimeString; + diff --git a/node_modules/express-error-handler/package.json b/node_modules/express-error-handler/package.json new file mode 100644 index 000000000..a2dca69cd --- /dev/null +++ b/node_modules/express-error-handler/package.json @@ -0,0 +1,66 @@ +{ + "name": "express-error-handler", + "version": "0.5.4", + "description": "A graceful error handler for Express applications.", + "main": "error-handler.js", + "scripts": { + "test": "node ./test/runtests.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:dilvie/express-error-handler.git" + }, + "keywords": [ + "error", + "errors", + "handling", + "handler", + "express", + "connect" + ], + "author": { + "name": "Eric Elliott" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/dilvie/express-error-handler/issues" + }, + "dependencies": { + "mout": "~0.7.1", + "connect-domain": "~0.5.0" + }, + "devDependencies": { + "express": "~3.4.0", + "tape": "~1.1.1", + "supertest": "~0.8.0", + "grunt": "~0.4.1", + "grunt-contrib-jshint": "~0.6.4", + "bunyan-request-logger": "~0.1.1", + "connect-cache-control": "~0.1.0", + "through": "~2.3.4", + "restify": "~2.6.0" + }, + "readme": "express-error-handler\n=====================\n\nA graceful error handler for Express applications.\n\n## Quick start:\n\n```js\nvar express = require('express'),\n errorHandler = require('../error-handler.js'),\n app = express(),\n env = process.env,\n port = env.myapp_port || 3000,\n http = require('http'),\n server;\n\n// Route that triggers a sample error:\napp.get('/error', function createError(req,\n res, next) {\n var err = new Error('Sample error');\n err.status = 500;\n next(err);\n});\n\n// Create the server object that we can pass\n// in to the error handler:\nserver = http.createServer(app);\n\n// Log the error\napp.use(function (err, req, res, next) {\n console.log(err);\n next(err);\n});\n\n// Respond to errors and conditionally shut\n// down the server. Pass in the server object\n// so the error handler can shut it down\n// gracefully:\napp.use( errorHandler({server: server}) );\n\nserver.listen(port, function () {\n console.log('Listening on port ' + port);\n});\n```\n\n## Configuration errorHandler(options)\n\nHere are the parameters you can pass into the `errorHandler()` middleware:\n\n* @param {object} [options]\n\n* @param {object} [options.handlers] Custom handlers for specific status codes.\n* @param {object} [options.views] View files to render in response to specific status codes. Specify a default with `options.views.default`\n* @param {object} [options.static] Static files to send in response to specific status codes. Specify a default with options.static.default.\n* @param {number} [options.timeout] Delay between the graceful shutdown attempt and the forced shutdown timeout.\n* @param {number} [options.exitStatus] Custom process exit status code.\n* @param {object} [options.server] The app server object for graceful shutdowns.\n* @param {function} [options.shutdown] An alternative shutdown function if the graceful shutdown fails.\n* @param {function} serializer a function to customize the JSON error object. Usage: serializer(err) return errObj\n* @return {function} errorHandler Express error handling middleware.\n\n### Examples:\n\n`express-error-handler` lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:\n\n\n```js\n var errorHandler = require('express-error-handler'),\n handler = errorHandler({\n handlers: {\n '404': function err404() {\n // do some custom thing here...\n }\n }\n });\n\n // After all your routes...\n // Pass a 404 into next(err)\n app.use( errorHandler.httpError(404) );\n\n // Handle all unhandled errors:\n app.use( handler );\n\nOr for a static page:\n\n handler = errorHandler({\n static: {\n '404': function err404() {\n // do some custom thing here...\n }\n }\n });\n\nOr for a custom view:\n\n handler = errorHandler({\n views: {\n '404': function err404() {\n // do some custom thing here...\n }\n }\n });\n```\n\n[More examples](https://github.com/dilvie/express-error-handler/tree/master/examples) are available in the examples folder.\n\n## errorHandler.isClientError(status)\n\nReturn true if the error status represents a client error that should not trigger a restart.\n\n* @param {number} status\n* @return {boolean}\n\n\n### Example\n\n```js\nerrorHandler.isClientError(404); // returns true\nerrorHandler.isClientError(500); // returns false\n```\n\n\n## errorHandler.httpError(status, [message])\n\nTake an error status and return a route that sends an error with the appropriate status and message to an error handler via `next(err)`.\n\n* @param {number} status\n* @param {string} message\n* @return {function} Express route handler\n\n```js\n// Define supported routes\napp.get( '/foo', handleFoo() );\n// 405 for unsupported methods.\napp.all( '/foo', createHandler.httpError(405) );\n```\n\n## Restify support\n\nRestify error handling works different from\nExpress.\n\nFirst, `next(err)` is synonymous with `res.send(status, error)`. This means that you should *only use `next(err)` to report errors to users*, and not as a way to aggregate errors to a common error handler. Instead, you can invoke an error handler directly to aggregate your error handling in one place.\n\n* There is no error handling middleware. Instead, use `server.on(`uncaughtException`, handleError)`\n\nSee the examples in `./examples/restify.js`\n\n\n## Thanks\n\n* [Nam Nguyen](https://github.com/gdbtek) for bringing the Express DOS exploit to my attention.\n* [Samuel Reed](https://github.com/strml) for helpful suggestions.\n", + "readmeFilename": "README.md", + "_id": "express-error-handler@0.5.4", + "dist": { + "shasum": "9895d6d0301c738f4b7ba769707a65f408e3f21b", + "tarball": "http://registry.npmjs.org/express-error-handler/-/express-error-handler-0.5.4.tgz" + }, + "_from": "express-error-handler@^0.5.4", + "_npmVersion": "1.3.11", + "_npmUser": { + "name": "ericelliott", + "email": "eric@ericleads.com" + }, + "maintainers": [ + { + "name": "ericelliott", + "email": "eric@ericleads.com" + } + ], + "directories": {}, + "_shasum": "9895d6d0301c738f4b7ba769707a65f408e3f21b", + "_resolved": "https://registry.npmjs.org/express-error-handler/-/express-error-handler-0.5.4.tgz", + "homepage": "https://github.com/dilvie/express-error-handler" +} diff --git a/node_modules/express-error-handler/test/runtests.js b/node_modules/express-error-handler/test/runtests.js new file mode 100644 index 000000000..43116b9a7 --- /dev/null +++ b/node_modules/express-error-handler/test/runtests.js @@ -0,0 +1,383 @@ +'use strict'; + +var test = require('tape'), + createHandler = require('../error-handler.js'), + through = require('through'), + + format = function format (types) { + return types['text'](); + }, + + testError = new Error('Test error'), + testReq = function () { return {}; }, + testRes = function () { + return { + send: function send() {}, + format: format + }; + }, + testNext = function () {}; + + +test('Custom shutdown', function (t) { + var shutdown = function shutdown() { + t.pass('Should call custom shutdown'); + t.end(); + }, + + handler = createHandler({shutdown: shutdown}); + + handler( testError, testReq(), testRes(), + testNext ); +}); + +test('Custom exit status', function (t) { + var status = 11, + shutdown = function shutdown(options) { + t.strictEqual(options.exitStatus, status, + 'Should use custom exit status code'); + + t.end(); + }, + + handler = createHandler({ + shutdown: shutdown, + exitStatus: status + }); + + handler( testError, testReq(), testRes(), + testNext ); +}); + +test('Custom handler', function (t) { + var shutdown = function shutdown() {}, + e = new Error(), + + handler = createHandler({ + shutdown: shutdown, + handlers: { + '404': function err404() { + t.pass('Should use custom handlers ' + + 'for status codes'); + t.end(); + } + } + }); + + e.status = 404; + + handler( e, testReq(), testRes(), + testNext ); +}); + +test('Missing error status', function (t) { + var shutdown = function shutdown() {}, + e = new Error(), + + handler = createHandler({ + shutdown: shutdown, + handlers: { + '404': function err404() { + t.pass('Should get status from ' + + 'res.statusCode'); + t.end(); + } + } + }), + res = testRes(); + + res.statusCode = 404; + + handler( e, testReq(), res, + testNext ); +}); + +test('Custom views', function (t) { + var shutdown = function shutdown() {}, + e = new Error(), + + handler = createHandler({ + shutdown: shutdown, + views: { + '404': '404 view' + } + }); + + e.status = 404; + + handler(e, testReq(), { + render: function render() { + t.pass('Render should be called for ' + + 'custom views.'); + t.end(); + } + },testNext); +}); + +test('Error with status default behavior', + function (t) { + + var shutdown = function shutdown() { + t.fail('shutdown should not be called.'); + }, + e = new Error(), + handler = createHandler({ + shutdown: shutdown + }); + + e.status = 404; + + handler(e, testReq(), { + send: function send(status) { + t.equal(status, 404, + 'res.send() should be called ' + + 'with error status.'); + t.end(); + }, + format: format + }, testNext); +}); + +test('Default error status for non-user error', + function (t) { + + var shutdown = function shutdown() {}, + e = new Error(), + handler = createHandler({ + shutdown: shutdown + }); + + e.status = 511; + + handler(e, testReq(), { + send: function send(status) { + t.equal(status, 500, + 'res.send() should be called ' + + 'with default status.'); + t.end(); + }, + format: format + }, testNext); +}); + +test('Custom timeout', + function (t) { + + var shutdown = function shutdown(options) { + t.equal(options.timeout, 4 * 1000, + 'Custom timeout should be respected.'); + t.end(); + }, + handler = createHandler({ + timeout: 4 * 1000, + shutdown: shutdown + }); + + handler(testError, testReq(), testRes(), testNext); +}); + +test('Static file', function (t) { + var + buff = [], + sample = 'foo', + output, + + shutdown = function shutdown() {}, + + e = (function () { + var err = new Error(); + err.status = 505; + return err; + }()), + + handler = createHandler({ + static: { + '505': './test/test-static.html' + }, + shutdown: shutdown + }), + + res = through(function (data) { + buff.push(data); + }, function () { + output = Buffer.concat(buff).toString('utf8') + .trim(); + + t.strictEqual(output, sample, + 'Should send static file.'); + + t.end(); + }); + + handler(e, testReq(), res, testNext); +}); + +test('.isClientError()', function (t) { + var + serverPass = [399, 500].every(function (err) { + return !createHandler.isClientError(err); + }), + clientPass = [400, 401, 499].every(function(err) { + return createHandler.isClientError(err); + }); + + t.ok(serverPass, + 'Non client errors should be correctly identified.'); + t.ok(clientPass, + 'Client errors should be correctly identified.'); + + t.end(); +}); + +test('Default static file', function (t) { + var shutdown = function shutdown() {}, + + buff = [], + sample = 'foo', + output, + + e = (function () { + var err = new Error(); + err.status = 505; + return err; + }()), + + handler = createHandler({ + static: { + 'default': './test/test-static.html' + }, + shutdown: shutdown + }), + + res = through(function (data) { + buff.push(data); + }, function () { + output = Buffer.concat(buff).toString('utf8') + .trim(); + + t.strictEqual(output, sample, + 'Should send static file.'); + + t.end(); + }); + + handler(e, testReq(), res, testNext); +}); + +test('.restify()', function (t) { + var route, + shutdown = function shutdown() { + t.pass('Should return restify handler.'); + t.end(); + }, + + handler = createHandler({ + shutdown: shutdown, + framework: 'restify' + }); + + // Restify uses a different signature: + handler(testReq(), testRes(), route, testError); +}); + +test('.create() http error handler', function (t) { + var next = function (err) { + t.equal(err.status, 405, + 'Status message should be set on error.'); + t.equal(err.message, 'Method Not Allowed', + 'Should set message correctly.'); + t.end(); + }, + handler = createHandler.httpError(405); + + handler(null, null, next); +}); + +test('JSON error format', + function (t) { + + var shutdown = function shutdown() {}, + e = new Error(), + handler = createHandler({ + shutdown: shutdown + }); + + e.status = 500; + + handler(e, testReq(), { + send: function send(status, obj) { + t.equal(obj.status, 500, + 'res.send() should be called ' + + 'with status code as first param.'); + t.equal(obj.status, 500, + 'res.send() should be called ' + + 'with error status on response body.'); + t.equal(obj.message, 'Internal Server Error', + 'res.send() should be called ' + + 'with error message on response body.'); + t.end(); + }, + format: function format (types) { + return types['json'](); + } + }, testNext); +}); + +test('JSON with custom error message', + function (t) { + + var shutdown = function shutdown() {}, + e = new Error(), + handler = createHandler({ + shutdown: shutdown + }); + + e.status = 420; + e.message = 'half baked'; + + handler(e, testReq(), { + send: function send(status, obj) { + t.equal(obj.message, 'half baked', + 'res.send() should be called ' + + 'with custom error message.'); + t.end(); + }, + format: function format (types) { + return types['json'](); + } + }, testNext); +}); + + +test('JSON with serializer', + function (t) { + + var shutdown = function shutdown() {}, + e = new Error(), + handler = createHandler({ + shutdown: shutdown, + serializer: function (body) { + return { + status: body.status, + message: body.message, + links: [ + {self: '/foo'} + ] + }; + } + }); + + e.status = 500; + + handler(e, testReq(), { + send: function send(status, obj) { + t.equal(obj.links[0].self, '/foo', + 'Should be able to define a custom ' + + 'serializer for error responses.'); + t.end(); + }, + format: function format (types) { + return types['json'](); + } + }, testNext); +}); diff --git a/node_modules/express-error-handler/test/test-static.html b/node_modules/express-error-handler/test/test-static.html new file mode 100644 index 000000000..191028156 --- /dev/null +++ b/node_modules/express-error-handler/test/test-static.html @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/node_modules/express/.npmignore b/node_modules/express/.npmignore new file mode 100644 index 000000000..a9465cfba --- /dev/null +++ b/node_modules/express/.npmignore @@ -0,0 +1,11 @@ +.git* +benchmarks/ +docs/ +examples/ +support/ +test/ +testing.js +.DS_Store +.travis.yml +coverage.html +lib-cov diff --git a/node_modules/express/History.md b/node_modules/express/History.md new file mode 100644 index 000000000..eb812c2c5 --- /dev/null +++ b/node_modules/express/History.md @@ -0,0 +1,1337 @@ +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + * update cookie to 0.1.2 + * update send to 0.3.0 + * update serve-static to 1.1.0 + * update type-is to 1.1.0 + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes chraset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Cloases #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delmited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error reponse support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independant specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE new file mode 100644 index 000000000..0f3c76789 --- /dev/null +++ b/node_modules/express/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk + +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/express/Makefile b/node_modules/express/Makefile new file mode 100644 index 000000000..a1f33a702 --- /dev/null +++ b/node_modules/express/Makefile @@ -0,0 +1,34 @@ + +MOCHA_OPTS= --check-leaks +REPORTER = dot + +check: test + +test: test-unit test-acceptance + +test-unit: + @NODE_ENV=test ./node_modules/.bin/mocha \ + --reporter $(REPORTER) \ + --globals setImmediate,clearImmediate \ + $(MOCHA_OPTS) + +test-acceptance: + @NODE_ENV=test ./node_modules/.bin/mocha \ + --reporter $(REPORTER) \ + --bail \ + test/acceptance/*.js + +test-cov: lib-cov + @EXPRESS_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html + +lib-cov: + @jscoverage lib lib-cov + +bench: + @$(MAKE) -C benchmarks + +clean: + rm -f coverage.html + rm -fr lib-cov + +.PHONY: test test-unit test-acceptance bench clean diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md new file mode 100644 index 000000000..ac90eb9a5 --- /dev/null +++ b/node_modules/express/Readme.md @@ -0,0 +1,108 @@ +[![express logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![Build Status](https://travis-ci.org/visionmedia/express.svg?branch=master)](https://travis-ci.org/visionmedia/express) [![Gittip](https://img.shields.io/gittip/visionmedia.svg)](https://www.gittip.com/visionmedia/) + +```js +var express = require('express'); +var app = express(); + +app.get('/', function(req, res){ + res.send('Hello World'); +}); + +app.listen(3000); +``` + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/visionmedia/express/wiki/New-features-in-4.x). + +## Installation + + $ npm install express + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](http://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + + $ npm install -g express-generator@3 + + Create the app: + + $ express /tmp/foo && cd /tmp/foo + + Install dependencies: + + $ npm install + + Start the server: + + $ npm start + +## Features + + * Robust routing + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Focus on high performance + * Executable for generating applications quickly + * High test coverage + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js), + you can quickly craft your perfect framework. + +## More Information + + * [Website and Documentation](http://expressjs.com/) stored at [visionmedia/expressjs.com](https://github.com/visionmedia/expressjs.com) + * Join #express on freenode + * [Google Group](http://groups.google.com/group/express-js) for discussion + * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) and [defunctzombie](https://twitter.com/defunctzombie) on twitter for updates + * Visit the [Wiki](http://github.com/visionmedia/express/wiki) + * [Русскоязычная документация](http://jsman.ru/express/) + * Run express examples [online](https://runnable.com/express) + +## Viewing Examples + +Clone the Express repo, then install the dev dependencies to install all the example / test suite dependencies: + + $ git clone git://github.com/visionmedia/express.git --depth 1 + $ cd express + $ npm install + +Then run whichever tests you want: + + $ node examples/content-negotiation + +You can also view live examples here: + + + +## Running Tests + +To run the test suite, first invoke the following command within the repo, installing the development dependencies: + + $ npm install + +Then run the tests: + + $ make test + +## Contributors + + Author: [TJ Holowaychuk](http://github.com/visionmedia) + Lead Maintainer: [Roman Shtylman](https://github.com/defunctzombie) + Contributors: https://github.com/visionmedia/express/graphs/contributors + +## License + +MIT diff --git a/node_modules/express/index.js b/node_modules/express/index.js new file mode 100644 index 000000000..bfe99345b --- /dev/null +++ b/node_modules/express/index.js @@ -0,0 +1,4 @@ + +module.exports = process.env.EXPRESS_COV + ? require('./lib-cov/express') + : require('./lib/express'); \ No newline at end of file diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js new file mode 100644 index 000000000..c12b8f150 --- /dev/null +++ b/node_modules/express/lib/application.js @@ -0,0 +1,532 @@ +/** + * Module dependencies. + */ + +var mixin = require('utils-merge'); +var escapeHtml = require('escape-html'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @api private + */ + +app.init = function(){ + this.cache = {}; + this.settings = {}; + this.engines = {}; + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * + * @api private + */ + +app.defaultConfiguration = function(){ + // default settings + this.enable('x-powered-by'); + this.enable('etag'); + var env = process.env.NODE_ENV || 'development'; + this.set('env', env); + this.set('subdomain offset', 2); + + debug('booting in %s mode', env); + + // inherit protos + this.on('mount', function(parent){ + this.request.__proto__ = parent.request; + this.response.__proto__ = parent.response; + this.engines.__proto__ = parent.engines; + this.settings.__proto__ = parent.settings; + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', process.cwd() + '/views'); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @api private + */ +app.lazyrouter = function() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query()); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no _done_ callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @api private + */ + +app.handle = function(req, res, done) { + var env = this.get('env'); + + this._router.handle(req, res, function(err) { + if (done) { + return done(err); + } + + // unhandled error + if (err) { + // default to 500 + if (res.statusCode < 400) res.statusCode = 500; + debug('default %s', res.statusCode); + + // respect err.status + if (err.status) res.statusCode = err.status; + + // production gets a basic error message + var msg = 'production' == env + ? http.STATUS_CODES[res.statusCode] + : err.stack || err.toString(); + msg = escapeHtml(msg); + + // log to stderr in a non-test env + if ('test' != env) console.error(err.stack || err.toString()); + if (res.headersSent) return req.socket.destroy(); + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Content-Length', Buffer.byteLength(msg)); + if ('HEAD' == req.method) return res.end(); + res.end(msg); + return; + } + + // 404 + debug('default 404'); + res.statusCode = 404; + res.setHeader('Content-Type', 'text/html'); + if ('HEAD' == req.method) return res.end(); + res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n'); + }); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @param {String|Function|Server} route + * @param {Function|Server} fn + * @return {app} for chaining + * @api public + */ + +app.use = function(route, fn){ + var mount_app; + + // default route to '/' + if ('string' != typeof route) fn = route, route = '/'; + + // express app + if (fn.handle && fn.set) mount_app = fn; + + // restore .app property on req and res + if (mount_app) { + debug('.use app under %s', route); + mount_app.mountpath = route; + fn = function(req, res, next) { + var orig = req.app; + mount_app.handle(req, res, function(err) { + req.__proto__ = orig.request; + res.__proto__ = orig.response; + next(err); + }); + }; + } + + this.lazyrouter(); + this._router.use(route, fn); + + // mounted an app + if (mount_app) { + mount_app.parent = this; + mount_app.emit('mount', this); + } + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @api public + */ + +app.route = function(path){ + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @api public + */ + +app.engine = function(ext, fn){ + if ('function' != typeof fn) throw new Error('callback function required'); + if ('.' != ext[0]) ext = '.' + ext; + this.engines[ext] = fn; + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @api public + */ + +app.param = function(name, fn){ + var self = this; + self.lazyrouter(); + + if (Array.isArray(name)) { + name.forEach(function(key) { + self.param(key, fn); + }); + return this; + } + + self._router.param(name, fn); + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @api public + */ + +app.set = function(setting, val){ + if (1 == arguments.length) { + return this.settings[setting]; + } else { + this.settings[setting] = val; + return this; + } +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @api private + */ + +app.path = function(){ + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @api public + */ + +app.enabled = function(setting){ + return !!this.set(setting); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @api public + */ + +app.disabled = function(setting){ + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @api public + */ + +app.enable = function(setting){ + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @api public + */ + +app.disable = function(setting){ + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if ('get' == method && 1 == arguments.length) return this.set(path); + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, [].slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @api public + */ + +app.all = function(path){ + this.lazyrouter(); + + var route = this._router.route(path); + var args = [].slice.call(arguments, 1); + methods.forEach(function(method){ + route[method].apply(route, args); + }); + + return this; +}; + +// del -> delete alias + +app.del = app.delete; + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {String|Function} options or fn + * @param {Function} fn + * @api public + */ + +app.render = function(name, options, fn){ + var opts = {}; + var cache = this.cache; + var engines = this.engines; + var view; + + // support callback function as second arg + if ('function' == typeof options) { + fn = options, options = {}; + } + + // merge app.locals + mixin(opts, this.locals); + + // merge options._locals + if (options._locals) mixin(opts, options._locals); + + // merge options + mixin(opts, options); + + // set .cache unless explicitly provided + opts.cache = null == opts.cache + ? this.enabled('view cache') + : opts.cache; + + // primed cache + if (opts.cache) view = cache[name]; + + // view + if (!view) { + view = new (this.get('view'))(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"'); + err.view = view; + return fn(err); + } + + // prime the cache + if (opts.cache) cache[name] = view; + } + + // render + try { + view.render(opts, fn); + } catch (err) { + fn(err); + } +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @api public + */ + +app.listen = function(){ + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js new file mode 100644 index 000000000..7be6832fb --- /dev/null +++ b/node_modules/express/lib/express.js @@ -0,0 +1,93 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var mixin = require('utils-merge'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, proto); + mixin(app, EventEmitter.prototype); + + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); + +/** + * Replace removed middleware with an appropriate error message. + */ + +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/node_modules/express/lib/middleware/init.js b/node_modules/express/lib/middleware/init.js new file mode 100644 index 000000000..c09cf0c69 --- /dev/null +++ b/node_modules/express/lib/middleware/init.js @@ -0,0 +1,26 @@ +/** + * Initialization middleware, exposing the + * request and response to eachother, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + req.__proto__ = app.request; + res.__proto__ = app.response; + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/node_modules/express/lib/middleware/query.js b/node_modules/express/lib/middleware/query.js new file mode 100644 index 000000000..b828c85ef --- /dev/null +++ b/node_modules/express/lib/middleware/query.js @@ -0,0 +1,39 @@ +/** + * Module dependencies. + */ + +var qs = require('qs'); +var parseUrl = require('parseurl'); + +/** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object using + * [qs](https://github.com/visionmedia/node-querystring). + * + * Examples: + * + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + * + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options){ + return function query(req, res, next){ + if (!req.query) { + req.query = ~req.url.indexOf('?') + ? qs.parse(parseUrl(req).query, options) + : {}; + } + + next(); + }; +}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js new file mode 100644 index 000000000..de62e9de8 --- /dev/null +++ b/node_modules/express/lib/request.js @@ -0,0 +1,407 @@ +/** + * Module dependencies. + */ + +var accepts = require('accepts'); +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @api public + */ + +req.get = +req.header = function(name){ + switch (name = name.toLowerCase()) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[name]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String} + * @api public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding` is accepted. + * + * @param {String} encoding + * @return {Boolean} + * @api public + */ + +req.acceptsEncoding = // backwards compatibility +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +/** + * To do: update docs. + * + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} charset + * @return {Boolean} + * @api public + */ + +req.acceptsCharset = // backwards compatibility +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +/** + * To do: update docs. + * + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} lang + * @return {Boolean} + * @api public + */ + +req.acceptsLanguage = // backwards compatibility +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +/** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param {Number} size + * @return {Array} + * @api public + */ + +req.range = function(size){ + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @api public + */ + +req.param = function(name, defaultValue){ + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String} type + * @return {Boolean} + * @api public + */ + +req.is = function(types){ + if (!Array.isArray(types)) types = [].slice.call(arguments); + return typeis(this, types); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + * + * @return {String} + * @api public + */ + +req.__defineGetter__('protocol', function(){ + var trustProxy = this.app.get('trust proxy'); + if (this.connection.encrypted) return 'https'; + if (!trustProxy) return 'http'; + var proto = this.get('X-Forwarded-Proto') || 'http'; + return proto.split(/\s*,\s*/)[0]; +}); + +/** + * Short-hand for: + * + * req.protocol == 'https' + * + * @return {Boolean} + * @api public + */ + +req.__defineGetter__('secure', function(){ + return 'https' == this.protocol; +}); + +/** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + * + * @return {String} + * @api public + */ + +req.__defineGetter__('ip', function(){ + return this.ips[0] || this.connection.remoteAddress; +}); + +/** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + * + * @return {Array} + * @api public + */ + +req.__defineGetter__('ips', function(){ + var trustProxy = this.app.get('trust proxy'); + var val = this.get('X-Forwarded-For'); + return trustProxy && val + ? val.split(/ *, */) + : []; +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @api public + */ + +req.__defineGetter__('subdomains', function(){ + var offset = this.app.get('subdomain offset'); + return (this.host || '') + .split('.') + .reverse() + .slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @api public + */ + +req.__defineGetter__('path', function(){ + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field hostname. + * + * @return {String} + * @api public + */ + +req.__defineGetter__('host', function(){ + var trustProxy = this.app.get('trust proxy'); + var host = trustProxy && this.get('X-Forwarded-Host'); + host = host || this.get('Host'); + if (!host) return; + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + return ~index + ? host.substring(0, index) + : host; +}); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @api public + */ + +req.__defineGetter__('fresh', function(){ + var method = this.method; + var s = this.res.statusCode; + + // GET or HEAD for weak freshness validation only + if ('GET' != method && 'HEAD' != method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((s >= 200 && s < 300) || 304 == s) { + return fresh(this.headers, this.res._headers); + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @api public + */ + +req.__defineGetter__('stale', function(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @api public + */ + +req.__defineGetter__('xhr', function(){ + var val = this.get('X-Requested-With') || ''; + return 'xmlhttprequest' == val.toLowerCase(); +}); diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js new file mode 100644 index 000000000..a83bbd706 --- /dev/null +++ b/node_modules/express/lib/response.js @@ -0,0 +1,784 @@ +/** + * Module dependencies. + */ + +var http = require('http'); +var path = require('path'); +var mixin = require('utils-merge'); +var escapeHtml = require('escape-html'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var contentDisposition = require('./utils').contentDisposition; +var etag = require('./utils').etag; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var basename = path.basename; +var extname = path.extname; +var mime = send.mime; + +/** + * Response prototype. + */ + +var res = module.exports = { + __proto__: http.ServerResponse.prototype +}; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @api public + */ + +res.status = function(code){ + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @api public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + * + * @param {Mixed} body or status + * @param {Mixed} body + * @return {ServerResponse} + * @api public + */ + +res.send = function(body){ + var req = this.req; + var head = 'HEAD' == req.method; + var len; + + // settings + var app = this.app; + + // allow status / body + if (2 == arguments.length) { + // res.send(body, status) backwards compat + if ('number' != typeof body && 'number' == typeof arguments[1]) { + this.statusCode = arguments[1]; + } else { + this.statusCode = body; + body = arguments[1]; + } + } + + switch (typeof body) { + // response status + case 'number': + this.get('Content-Type') || this.type('txt'); + this.statusCode = body; + body = http.STATUS_CODES[body]; + break; + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) this.type('html'); + break; + case 'boolean': + case 'object': + if (null == body) { + body = ''; + } else if (Buffer.isBuffer(body)) { + this.get('Content-Type') || this.type('bin'); + } else { + return this.json(body); + } + break; + } + + // populate Content-Length + if (undefined !== body && !this.get('Content-Length')) { + this.set('Content-Length', len = Buffer.isBuffer(body) + ? body.length + : Buffer.byteLength(body)); + } + + // ETag support + // TODO: W/ support + if (app.settings.etag && len && 'GET' == req.method) { + if (!this.get('ETag')) { + this.set('ETag', etag(body)); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 == this.statusCode || 304 == this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + body = ''; + } + + // respond + this.end(head ? null : body); + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + * + * @param {Mixed} obj or status + * @param {Mixed} obj + * @return {ServerResponse} + * @api public + */ + +res.json = function(obj){ + // allow status / body + if (2 == arguments.length) { + // res.json(body, status) backwards compat + if ('number' == typeof arguments[1]) { + this.statusCode = arguments[1]; + } else { + this.statusCode = obj; + obj = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(obj, replacer, spaces); + + // content-type + this.get('Content-Type') || this.set('Content-Type', 'application/json'); + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + * + * @param {Mixed} obj or status + * @param {Mixed} obj + * @return {ServerResponse} + * @api public + */ + +res.jsonp = function(obj){ + // allow status / body + if (2 == arguments.length) { + // res.json(body, status) backwards compat + if ('number' == typeof arguments[1]) { + this.statusCode = arguments[1]; + } else { + this.statusCode = obj; + obj = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(obj, replacer, spaces) + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + this.set('Content-Type', 'application/json'); + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (callback && 'string' === typeof callback) { + this.set('Content-Type', 'text/javascript'); + var cb = callback.replace(/[^\[\]\w$.]/g, ''); + body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 + * - `root` root directory for relative filenames + * - `hidden` serve hidden files, defaulting to false + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @param {String} path + * @param {Object|Function} options or fn + * @param {Function} fn + * @api public + */ + +res.sendfile = function(path, options, fn){ + options = options || {}; + var self = this; + var req = self.req; + var next = this.req.next; + var done; + + + // support function as second arg + if ('function' == typeof options) { + fn = options; + options = {}; + } + + // socket errors + req.socket.on('error', error); + + // errors + function error(err) { + if (done) return; + done = true; + + // clean up + cleanup(); + if (!self.headersSent) self.removeHeader('Content-Disposition'); + + // callback available + if (fn) return fn(err); + + // list in limbo if there's no callback + if (self.headersSent) return; + + // delegate + next(err); + } + + // streaming + function stream(stream) { + if (done) return; + cleanup(); + if (fn) stream.on('end', fn); + } + + // cleanup + function cleanup() { + req.socket.removeListener('error', error); + } + + // Back-compat + options.maxage = options.maxage || options.maxAge || 0; + + // transfer + var file = send(req, path, options); + file.on('error', error); + file.on('directory', next); + file.on('stream', stream); + file.pipe(this); + this.on('finish', cleanup); +}; + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + * + * @param {String} path + * @param {String|Function} filename or fn + * @param {Function} fn + * @api public + */ + +res.download = function(path, filename, fn){ + // support function as second arg + if ('function' == typeof filename) { + fn = filename; + filename = null; + } + + filename = filename || path; + this.set('Content-Disposition', contentDisposition(filename)); + return this.sendfile(path, fn); +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @api public + */ + +res.contentType = +res.type = function(type){ + return this.set('Content-Type', ~type.indexOf('/') + ? type + : mime.lookup(type)); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @api public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); + + var key = req.accepts(keys); + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @api public + */ + +res.attachment = function(filename){ + if (filename) this.type(extname(filename)); + this.set('Content-Disposition', contentDisposition(filename)); + return this; +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object|Array} field + * @param {String} val + * @return {ServerResponse} for chaining + * @api public + */ + +res.set = +res.header = function(field, val){ + if (2 == arguments.length) { + if (Array.isArray(val)) val = val.map(String); + else val = String(val); + if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) { + var charset = mime.charsets.lookup(val.split(';')[0]); + if (charset) val += '; charset=' + charset.toLowerCase(); + } + this.setHeader(field, val); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @api public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} options + * @param {ServerResponse} for chaining + * @api public + */ + +res.clearCookie = function(name, options){ + var opts = { expires: new Date(1), path: '/' }; + return this.cookie(name, '', options + ? mixin(opts, options) + : opts); +}; + +/** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} val + * @param {Options} options + * @api public + */ + +res.cookie = function(name, val, options){ + options = mixin({}, options); + var secret = this.req.secret; + var signed = options.signed; + if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies'); + if ('number' == typeof val) val = val.toString(); + if ('object' == typeof val) val = 'j:' + JSON.stringify(val); + if (signed) val = 's:' + sign(val, secret); + if ('maxAge' in options) { + options.expires = new Date(Date.now() + options.maxAge); + options.maxAge /= 1000; + } + if (null == options.path) options.path = '/'; + var headerVal = cookie.serialize(name, String(val), options); + + // supports multiple 'res.cookie' calls by getting previous value + var prev = this.get('Set-Cookie'); + if (prev) { + if (Array.isArray(prev)) { + headerVal = prev.concat(headerVal); + } else { + headerVal = [prev, headerVal]; + } + } + this.set('Set-Cookie', headerVal); + return this; +}; + + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @api public + */ + +res.location = function(url){ + var req = this.req; + + // "back" is an alias for the referrer + if ('back' == url) url = req.get('Referrer') || '/'; + + // Respond + this.set('Location', url); + return this; +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @param {String} url + * @param {Number} code + * @api public + */ + +res.redirect = function(url){ + var head = 'HEAD' == this.req.method; + var status = 302; + var body; + + // allow status / url + if (2 == arguments.length) { + if ('number' == typeof url) { + status = url; + url = arguments[1]; + } else { + status = arguments[1]; + } + } + + // Set location header + this.location(url); + url = this.get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statusCodes[status] + '. Redirecting to ' + encodeURI(url); + }, + + html: function(){ + var u = escapeHtml(url); + body = '

' + statusCodes[status] + '. Redirecting to ' + u + '

'; + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + this.end(head ? null : body); +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @param {ServerResponse} for chaining + * @api public + */ + +res.vary = function(field){ + var self = this; + + // nothing + if (!field) return this; + + // array + if (Array.isArray(field)) { + field.forEach(function(field){ + self.vary(field); + }); + return; + } + + var vary = this.get('Vary'); + + // append + if (vary) { + vary = vary.split(/ *, */); + if (!~vary.indexOf(field)) vary.push(field); + this.set('Vary', vary.join(', ')); + return this; + } + + // set + this.set('Vary', field); + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @param {String} view + * @param {Object|Function} options or callback function + * @param {Function} fn + * @api public + */ + +res.render = function(view, options, fn){ + options = options || {}; + var self = this; + var req = this.req; + var app = req.app; + + // support callback function as second arg + if ('function' == typeof options) { + fn = options, options = {}; + } + + // merge res.locals + options._locals = self.locals; + + // default callback to respond + fn = fn || function(err, str){ + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, options, fn); +}; diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js new file mode 100644 index 000000000..7dc479e89 --- /dev/null +++ b/node_modules/express/lib/router/index.js @@ -0,0 +1,385 @@ +/** + * Module dependencies. + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var debug = require('debug')('express:router'); +var parseUrl = require('parseurl'); + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @api public + */ + +var proto = module.exports = function(options) { + options = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = options.caseSensitive; + router.strict = options.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @api public + */ + +proto.param = function(name, fn){ + // param logic + if ('function' == typeof name) { + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + name = name.substr(1); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' != typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * + * @api private + */ + +proto.handle = function(req, res, done) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var method = req.method.toLowerCase(); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // for options requests, respond with a default if nothing else responds + if (method === 'options') { + var old = done; + done = function(err) { + if (err || options.length === 0) return old(err); + + var body = options.join(','); + return res.set('Allow', body).send(body); + }; + } + + (function next(err) { + if (err === 'route') { + err = undefined; + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } + + req.url = protohost + removed + req.url.substr(protohost.length); + req.originalUrl = req.originalUrl || req.url; + removed = ''; + + try { + var path = parseUrl(req).pathname; + if (undefined == path) path = '/'; + + if (!layer.match(path)) return next(err); + + // route object and not middleware + var route = layer.route; + + // if final route, then we support options + if (route) { + // we don't run any routes with error first + if (err) { + return next(err); + } + + req.route = route; + + // we can now dispatch to the route + if (method === 'options' && !route.methods['options']) { + options.push.apply(options, route._options()); + } + } + + req.params = layer.params; + + // this should be done for the layer + return self.process_params(layer, req, res, function(err) { + if (err) { + return next(err); + } + + if (route) { + return layer.handle(req, res, next); + } + + trim_prefix(); + }); + + } catch (err) { + next(err); + } + + function trim_prefix() { + var c = path[layer.path.length]; + if (c && '/' != c && '.' != c) return next(err); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', removed, req.url); + removed = layer.path; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && '/' != req.url[0]) { + req.url = '/' + req.url; + slashAdded = true; + } + + debug('%s %s : %s', layer.handle.name || 'anonymous', layer.path, req.originalUrl); + var arity = layer.handle.length; + if (err) { + if (arity === 4) { + layer.handle(err, req, res, next); + } else { + next(err); + } + } else if (arity < 4) { + layer.handle(req, res, next); + } else { + next(err); + } + } + + })(); +}; + +/** + * Process any parameters for the route. + * + * @api private + */ + +proto.process_params = function(route, req, res, done) { + var params = this.params; + + // captured parameters from the route, keys and values + var keys = route.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + paramVal = key && req.params[key.name]; + paramCallbacks = key && params[key.name]; + + try { + if (paramCallbacks && undefined !== paramVal) { + return paramCallback(); + } else if (key) { + return param(); + } + } catch (err) { + return done(err); + } + + done(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + if (err || !fn) return param(err); + fn(req, res, paramCallback, paramVal, key.name); + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @param {String|Function} route + * @param {Function} fn + * @return {app} for chaining + * @api public + */ + +proto.use = function(route, fn){ + // default route to '/' + if ('string' != typeof route) { + fn = route; + route = '/'; + } + + if (typeof fn !== 'function') { + var type = {}.toString.call(fn); + var msg = 'Router.use() requires callback functions but got a ' + type; + throw new Error(msg); + } + + // strip trailing slash + if ('/' == route[route.length - 1]) { + route = route.slice(0, -1); + } + + var layer = new Layer(route, { + sensitive: this.caseSensitive, + strict: this.strict, + end: false + }, fn); + + // add the middleware + debug('use %s %s', route || '/', fn.name || 'anonymous'); + + this.stack.push(layer); + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @api public + */ + +proto.route = function(path){ + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, [].slice.call(arguments, 1)); + return this; + }; +}); diff --git a/node_modules/express/lib/router/layer.js b/node_modules/express/lib/router/layer.js new file mode 100644 index 000000000..2dcb288b2 --- /dev/null +++ b/node_modules/express/lib/router/layer.js @@ -0,0 +1,67 @@ +/** + * Module dependencies. + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Expose `Layer`. + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %s', path); + options = options || {}; + this.regexp = pathRegexp(path, this.keys = [], options); + this.handle = fn; +} + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function(path){ + var keys = this.keys; + var params = this.params = {}; + var m = this.regexp.exec(path); + var n = 0; + var key; + var val; + + if (!m) return false; + + this.path = m[0]; + + for (var i = 1, len = m.length; i < len; ++i) { + key = keys[i - 1]; + + try { + val = 'string' == typeof m[i] + ? decodeURIComponent(m[i]) + : m[i]; + } catch(e) { + var err = new Error("Failed to decode param '" + m[i] + "'"); + err.status = 400; + throw err; + } + + if (key) { + params[key.name] = val; + } else { + params[n++] = val; + } + } + + return true; +}; diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js new file mode 100644 index 000000000..dca4b1b22 --- /dev/null +++ b/node_modules/express/lib/router/route.js @@ -0,0 +1,191 @@ +/** + * Module dependencies. + */ + +var debug = require('debug')('express:router:route'); +var methods = require('methods'); +var utils = require('../utils'); + +/** + * Expose `Route`. + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @api private + */ + +function Route(path) { + debug('new %s', path); + this.path = path; + this.stack = undefined; + + // route handlers for various http methods + this.methods = {}; +} + +/** + * @return {Array} supported HTTP methods + * @api private + */ + +Route.prototype._options = function(){ + return Object.keys(this.methods).map(function(method) { + return method.toUpperCase(); + }); +}; + +/** + * dispatch req, res into this route + * + * @api private + */ + +Route.prototype.dispatch = function(req, res, done){ + var self = this; + var method = req.method.toLowerCase(); + + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = self; + + // single middleware route case + if (typeof this.stack === 'function') { + this.stack(req, res, done); + return; + } + + var stack = self.stack; + if (!stack) { + return done(); + } + + var idx = 0; + (function next_layer(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next_layer(err); + } + + var arity = layer.handle.length; + if (err) { + if (arity < 4) { + return next_layer(err); + } + + try { + layer.handle(err, req, res, next_layer); + } catch (err) { + next_layer(err); + } + return; + } + + if (arity > 3) { + return next_layer(); + } + + try { + layer.handle(req, res, next_layer); + } catch (err) { + next_layer(err); + } + })(); +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function(){ + var self = this; + var callbacks = utils.flatten([].slice.call(arguments)); + callbacks.forEach(function(fn) { + if (typeof fn !== 'function') { + var type = {}.toString.call(fn); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new Error(msg); + } + + if (!self.stack) { + self.stack = fn; + } + else if (typeof self.stack === 'function') { + self.stack = [{ handle: self.stack }, { handle: fn }]; + } + else { + self.stack.push({ handle: fn }); + } + }); + + return self; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var self = this; + var callbacks = utils.flatten([].slice.call(arguments)); + + callbacks.forEach(function(fn) { + if (typeof fn !== 'function') { + var type = {}.toString.call(fn); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, self.path); + + if (!self.methods[method]) { + self.methods[method] = true; + } + + if (!self.stack) { + self.stack = []; + } + else if (typeof self.stack === 'function') { + self.stack = [{ handle: self.stack }]; + } + + self.stack.push({ method: method, handle: fn }); + }); + return self; + }; +}); diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js new file mode 100644 index 000000000..4297cbce7 --- /dev/null +++ b/node_modules/express/lib/utils.js @@ -0,0 +1,134 @@ +/** + * Module dependencies. + */ + +var mime = require('send').mime; +var crc32 = require('buffer-crc32'); +var basename = require('path').basename; + +/** + * Return ETag for `body`. + * + * @param {String|Buffer} body + * @return {String} + * @api private + */ + +exports.etag = function(body){ + return '"' + crc32.signed(body) + '"'; +}; + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' == path[0]) return true; + if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = function(arr, ret){ + ret = ret || []; + var len = arr.length; + for (var i = 0; i < len; ++i) { + if (Array.isArray(arr[i])) { + exports.flatten(arr[i], ret); + } else { + ret.push(arr[i]); + } + } + return ret; +}; + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = function(filename){ + var ret = 'attachment'; + if (filename) { + filename = basename(filename); + // if filename contains non-ascii characters, add a utf-8 version ala RFC 5987 + ret = /[^\040-\176]/.test(filename) + ? 'attachment; filename=' + encodeURI(filename) + '; filename*=UTF-8\'\'' + encodeURI(filename) + : 'attachment; filename="' + filename + '"'; + } + + return ret; +}; + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js new file mode 100644 index 000000000..989e8bb25 --- /dev/null +++ b/node_modules/express/lib/view.js @@ -0,0 +1,77 @@ +/** + * Module dependencies. + */ + +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var exists = fs.existsSync || path.existsSync; +var join = path.join; + +/** + * Expose `View`. + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {String} name + * @param {Object} options + * @api private + */ + +function View(name, options) { + options = options || {}; + this.name = name; + this.root = options.root; + var engines = options.engines; + this.defaultEngine = options.defaultEngine; + var ext = this.ext = extname(name); + if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); + if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine); + this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); + this.path = this.lookup(name); +} + +/** + * Lookup view by the given `path` + * + * @param {String} path + * @return {String} + * @api private + */ + +View.prototype.lookup = function(path){ + var ext = this.ext; + + // . + if (!utils.isAbsolute(path)) path = join(this.root, path); + if (exists(path)) return path; + + // /index. + path = join(dirname(path), basename(path, ext), 'index' + ext); + if (exists(path)) return path; +}; + +/** + * Render with the given `options` and callback `fn(err, str)`. + * + * @param {Object} options + * @param {Function} fn + * @api private + */ + +View.prototype.render = function(options, fn){ + this.engine(this.path, options, fn); +}; diff --git a/node_modules/express/node_modules/accepts/.npmignore b/node_modules/express/node_modules/accepts/.npmignore new file mode 100644 index 000000000..b59f7e3a9 --- /dev/null +++ b/node_modules/express/node_modules/accepts/.npmignore @@ -0,0 +1 @@ +test/ \ No newline at end of file diff --git a/node_modules/express/node_modules/accepts/.travis.yml b/node_modules/express/node_modules/accepts/.travis.yml new file mode 100644 index 000000000..3e3646a12 --- /dev/null +++ b/node_modules/express/node_modules/accepts/.travis.yml @@ -0,0 +1,4 @@ +node_js: +- "0.10" +- "0.11" +language: node_js \ No newline at end of file diff --git a/node_modules/express/node_modules/accepts/Makefile b/node_modules/express/node_modules/accepts/Makefile new file mode 100644 index 000000000..f2aa0be42 --- /dev/null +++ b/node_modules/express/node_modules/accepts/Makefile @@ -0,0 +1,8 @@ +BIN = ./node_modules/.bin/ + +test: + @${BIN}mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/accepts/README.md b/node_modules/express/node_modules/accepts/README.md new file mode 100644 index 000000000..97598956f --- /dev/null +++ b/node_modules/express/node_modules/accepts/README.md @@ -0,0 +1,97 @@ +# Accepts [![Build Status](https://travis-ci.org/expressjs/accepts.png)](https://travis-ci.org/expressjs/accepts) + +Higher level content negotation based on [negotiator](https://github.com/federomero/negotiator). Extracted from [koa](https://github.com/koajs/koa) for general use. + +In addition to negotatior, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## API + +### var accept = new Accepts(req) + +```js +var accepts = require('accepts') + +http.createServer(function (req, res) { + var accept = accepts(req) +}) +``` + +### accept\[property\]\(\) + +Returns all the explicitly accepted content property as an array in descending priority. + +- `accept.types()` +- `accept.encodings()` +- `accept.charsets()` +- `accept.languages()` + +They are also aliased in singular form such as `accept.type()`. `accept.languages()` is also aliased as `accept.langs()`, etc. + +Note: you should almost never do this in a real app as it defeats the purpose of content negotiation. + +Example: + +```js +// in Google Chrome +var encodings = accept.encodings() // -> ['sdch', 'gzip', 'deflate'] +``` + +Since you probably don't support `sdch`, you should just supply the encodings you support: + +```js +var encoding = accept.encodings('gzip', 'deflate') // -> 'gzip', probably +``` + +### accept\[property\]\(values, ...\) + +You can either have `values` be an array or have an argument list of values. + +If the client does not accept any `values`, `false` will be returned. +If the client accepts any `values`, the preferred `value` will be return. + +For `accept.types()`, shorthand mime types are allowed. + +Example: + +```js +// req.headers.accept = 'application/json' + +accept.types('json') // -> 'json' +accept.types('html', 'json') // -> 'json' +accept.types('html') // -> false + +// req.headers.accept = '' +// which is equivalent to `*` + +accept.types() // -> [], no explicit types +accept.types('text/html', 'text/json') // -> 'text/html', since it was first +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2013 Jonathan Ong me@jongleberry.com + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/accepts/index.js b/node_modules/express/node_modules/accepts/index.js new file mode 100644 index 000000000..226f051ce --- /dev/null +++ b/node_modules/express/node_modules/accepts/index.js @@ -0,0 +1,148 @@ +var Negotiator = require('negotiator') +var mime = require('mime') + +var slice = [].slice + +module.exports = Accepts + +function Accepts(req) { + if (!(this instanceof Accepts)) + return new Accepts(req) + + this.headers = req.headers + this.negotiator = Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.accepts('html'); + * // => "html" + * this.accepts('text/html'); + * // => "text/html" + * this.accepts('json', 'text'); + * // => "json" + * this.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.accepts('image/png'); + * this.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.accepts(['html', 'json']); + * this.accepts('html', 'json'); + * // => "json" + * + * @param {String|Array} type(s)... + * @return {String|Array|Boolean} + * @api public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types) { + if (!Array.isArray(types)) types = slice.call(arguments); + var n = this.negotiator; + if (!types.length) return n.mediaTypes(); + if (!this.headers.accept) return types[0]; + var mimes = types.map(extToMime); + var accepts = n.mediaTypes(mimes); + var first = accepts[0]; + if (!first) return false; + return types[mimes.indexOf(first)]; +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encoding(s)... + * @return {String|Array} + * @api public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings) { + if (!Array.isArray(encodings)) encodings = slice.call(arguments); + var n = this.negotiator; + if (!encodings.length) return n.encodings(); + return n.encodings(encodings)[0] || false; +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charset(s)... + * @return {String|Array} + * @api public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets) { + if (!Array.isArray(charsets)) charsets = [].slice.call(arguments); + var n = this.negotiator; + if (!charsets.length) return n.charsets(); + if (!this.headers['accept-charset']) return charsets[0]; + return n.charsets(charsets)[0] || false; +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} lang(s)... + * @return {Array|String} + * @api public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (langs) { + if (!Array.isArray(langs)) langs = slice.call(arguments); + var n = this.negotiator; + if (!langs.length) return n.languages(); + if (!this.headers['accept-language']) return langs[0]; + return n.languages(langs)[0] || false; +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @api private + */ + +function extToMime(type) { + if (~type.indexOf('/')) return type; + return mime.lookup(type); +} diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/LICENSE b/node_modules/express/node_modules/accepts/node_modules/mime/LICENSE new file mode 100644 index 000000000..451fc4550 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/express/node_modules/accepts/node_modules/mime/README.md b/node_modules/express/node_modules/accepts/node_modules/mime/README.md new file mode 100644 index 000000000..6ca19bd1e --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/README.md @@ -0,0 +1,66 @@ +# mime + +Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + + var mime = require('mime'); + + mime.lookup('/path/to/file.txt'); // => 'text/plain' + mime.lookup('file.txt'); // => 'text/plain' + mime.lookup('.TXT'); // => 'text/plain' + mime.lookup('htm'); // => 'text/html' + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + + mime.extension('text/html'); // => 'html' + mime.extension('application/octet-stream'); // => 'bin' + +### mime.charsets.lookup() + +Map mime-type to charset + + mime.charsets.lookup('text/plain'); // => 'UTF-8' + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). + +### mime.define() + +Add custom mime/extension mappings + + mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... + }); + + mime.lookup('x-sft'); // => 'text/x-some-format' + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + + mime.extension('text/x-some-format'); // => 'x-sf' + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + + mime.load('./my_project.types'); + +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/mime.js b/node_modules/express/node_modules/accepts/node_modules/mime/mime.js new file mode 100644 index 000000000..48be0c5e4 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/mime.js @@ -0,0 +1,114 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Load local copy of +// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +mime.load(path.join(__dirname, 'types/mime.types')); + +// Load additional types from node.js community +mime.load(path.join(__dirname, 'types/node.types')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/package.json b/node_modules/express/node_modules/accepts/node_modules/mime/package.json new file mode 100644 index 000000000..259822b78 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/package.json @@ -0,0 +1,58 @@ +{ + "author": { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "dependencies": {}, + "description": "A comprehensive library for mime-type mapping", + "devDependencies": {}, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.2.11", + "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.default_type\nSets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "_id": "mime@1.2.11", + "dist": { + "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + }, + "_from": "mime@~1.2.11", + "_npmVersion": "1.3.6", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "directories": {}, + "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "homepage": "https://github.com/broofa/node-mime" +} diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/test.js b/node_modules/express/node_modules/accepts/node_modules/mime/test.js new file mode 100644 index 000000000..2cda1c7ad --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/test.js @@ -0,0 +1,84 @@ +/** + * Usage: node test.js + */ + +var mime = require('./mime'); +var assert = require('assert'); +var path = require('path'); + +function eq(a, b) { + console.log('Test: ' + a + ' === ' + b); + assert.strictEqual.apply(null, arguments); +} + +console.log(Object.keys(mime.extensions).length + ' types'); +console.log(Object.keys(mime.types).length + ' extensions\n'); + +// +// Test mime lookups +// + +eq('text/plain', mime.lookup('text.txt')); // normal file +eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase +eq('text/plain', mime.lookup('dir/text.txt')); // dir + file +eq('text/plain', mime.lookup('.text.txt')); // hidden file +eq('text/plain', mime.lookup('.txt')); // nameless +eq('text/plain', mime.lookup('txt')); // extension-only +eq('text/plain', mime.lookup('/txt')); // extension-less () +eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less +eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized +eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +eq('txt', mime.extension(mime.types.text)); +eq('html', mime.extension(mime.types.htm)); +eq('bin', mime.extension('application/octet-stream')); +eq('bin', mime.extension('application/octet-stream ')); +eq('html', mime.extension(' text/html; charset=UTF-8')); +eq('html', mime.extension('text/html; charset=UTF-8 ')); +eq('html', mime.extension('text/html; charset=UTF-8')); +eq('html', mime.extension('text/html ; charset=UTF-8')); +eq('html', mime.extension('text/html;charset=UTF-8')); +eq('html', mime.extension('text/Html;charset=UTF-8')); +eq(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +eq('application/font-woff', mime.lookup('file.woff')); +eq('application/octet-stream', mime.lookup('file.buffer')); +eq('audio/mp4', mime.lookup('file.m4a')); +eq('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +eq('UTF-8', mime.charsets.lookup('text/plain')); +eq(undefined, mime.charsets.lookup(mime.types.js)); +eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +// +// Test for overlaps between mime.types and node.types +// + +var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); +apacheTypes.load(path.join(__dirname, 'types/mime.types')); +nodeTypes.load(path.join(__dirname, 'types/node.types')); + +var keys = [].concat(Object.keys(apacheTypes.types)) + .concat(Object.keys(nodeTypes.types)); +keys.sort(); +for (var i = 1; i < keys.length; i++) { + if (keys[i] == keys[i-1]) { + console.warn('Warning: ' + + 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + + ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); + } +} + +console.log('\nOK'); diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/types/mime.types b/node_modules/express/node_modules/accepts/node_modules/mime/types/mime.types new file mode 100644 index 000000000..da8cd6918 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/types/mime.types @@ -0,0 +1,1588 @@ +# This file maps Internet media types to unique file extension(s). +# Although created for httpd, this file is used by many software systems +# and has been placed in the public domain for unlimited redisribution. +# +# The table below contains both registered and (common) unregistered types. +# A type that has no unique extension can be ignored -- they are listed +# here to guide configurations toward known types and to make it easier to +# identify "new" types. File extensions are also commonly used to indicate +# content languages and encodings, so choose them carefully. +# +# Internet media types should be registered as described in RFC 4288. +# The registry is at . +# +# MIME type (lowercased) Extensions +# ============================================ ========== +# application/1d-interleaved-parityfec +# application/3gpp-ims+xml +# application/activemessage +application/andrew-inset ez +# application/applefile +application/applixware aw +application/atom+xml atom +application/atomcat+xml atomcat +# application/atomicmail +application/atomsvc+xml atomsvc +# application/auth-policy+xml +# application/batch-smtp +# application/beep+xml +# application/calendar+xml +# application/cals-1840 +# application/ccmp+xml +application/ccxml+xml ccxml +application/cdmi-capability cdmia +application/cdmi-container cdmic +application/cdmi-domain cdmid +application/cdmi-object cdmio +application/cdmi-queue cdmiq +# application/cea-2018+xml +# application/cellml+xml +# application/cfw +# application/cnrp+xml +# application/commonground +# application/conference-info+xml +# application/cpl+xml +# application/csta+xml +# application/cstadata+xml +application/cu-seeme cu +# application/cybercash +application/davmount+xml davmount +# application/dca-rft +# application/dec-dx +# application/dialog-info+xml +# application/dicom +# application/dns +application/docbook+xml dbk +# application/dskpp+xml +application/dssc+der dssc +application/dssc+xml xdssc +# application/dvcs +application/ecmascript ecma +# application/edi-consent +# application/edi-x12 +# application/edifact +application/emma+xml emma +# application/epp+xml +application/epub+zip epub +# application/eshop +# application/example +application/exi exi +# application/fastinfoset +# application/fastsoap +# application/fits +application/font-tdpfr pfr +# application/framework-attributes+xml +application/gml+xml gml +application/gpx+xml gpx +application/gxf gxf +# application/h224 +# application/held+xml +# application/http +application/hyperstudio stk +# application/ibe-key-request+xml +# application/ibe-pkg-reply+xml +# application/ibe-pp-data +# application/iges +# application/im-iscomposing+xml +# application/index +# application/index.cmd +# application/index.obj +# application/index.response +# application/index.vnd +application/inkml+xml ink inkml +# application/iotp +application/ipfix ipfix +# application/ipp +# application/isup +application/java-archive jar +application/java-serialized-object ser +application/java-vm class +application/javascript js +application/json json +application/jsonml+json jsonml +# application/kpml-request+xml +# application/kpml-response+xml +application/lost+xml lostxml +application/mac-binhex40 hqx +application/mac-compactpro cpt +# application/macwriteii +application/mads+xml mads +application/marc mrc +application/marcxml+xml mrcx +application/mathematica ma nb mb +# application/mathml-content+xml +# application/mathml-presentation+xml +application/mathml+xml mathml +# application/mbms-associated-procedure-description+xml +# application/mbms-deregister+xml +# application/mbms-envelope+xml +# application/mbms-msk+xml +# application/mbms-msk-response+xml +# application/mbms-protection-description+xml +# application/mbms-reception-report+xml +# application/mbms-register+xml +# application/mbms-register-response+xml +# application/mbms-user-service-description+xml +application/mbox mbox +# application/media_control+xml +application/mediaservercontrol+xml mscml +application/metalink+xml metalink +application/metalink4+xml meta4 +application/mets+xml mets +# application/mikey +application/mods+xml mods +# application/moss-keys +# application/moss-signature +# application/mosskey-data +# application/mosskey-request +application/mp21 m21 mp21 +application/mp4 mp4s +# application/mpeg4-generic +# application/mpeg4-iod +# application/mpeg4-iod-xmt +# application/msc-ivr+xml +# application/msc-mixer+xml +application/msword doc dot +application/mxf mxf +# application/nasdata +# application/news-checkgroups +# application/news-groupinfo +# application/news-transmission +# application/nss +# application/ocsp-request +# application/ocsp-response +application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy +application/oda oda +application/oebps-package+xml opf +application/ogg ogx +application/omdoc+xml omdoc +application/onenote onetoc onetoc2 onetmp onepkg +application/oxps oxps +# application/parityfec +application/patch-ops-error+xml xer +application/pdf pdf +application/pgp-encrypted pgp +# application/pgp-keys +application/pgp-signature asc sig +application/pics-rules prf +# application/pidf+xml +# application/pidf-diff+xml +application/pkcs10 p10 +application/pkcs7-mime p7m p7c +application/pkcs7-signature p7s +application/pkcs8 p8 +application/pkix-attr-cert ac +application/pkix-cert cer +application/pkix-crl crl +application/pkix-pkipath pkipath +application/pkixcmp pki +application/pls+xml pls +# application/poc-settings+xml +application/postscript ai eps ps +# application/prs.alvestrand.titrax-sheet +application/prs.cww cww +# application/prs.nprend +# application/prs.plucker +# application/prs.rdf-xml-crypt +# application/prs.xsf+xml +application/pskc+xml pskcxml +# application/qsig +application/rdf+xml rdf +application/reginfo+xml rif +application/relax-ng-compact-syntax rnc +# application/remote-printing +application/resource-lists+xml rl +application/resource-lists-diff+xml rld +# application/riscos +# application/rlmi+xml +application/rls-services+xml rs +application/rpki-ghostbusters gbr +application/rpki-manifest mft +application/rpki-roa roa +# application/rpki-updown +application/rsd+xml rsd +application/rss+xml rss +application/rtf rtf +# application/rtx +# application/samlassertion+xml +# application/samlmetadata+xml +application/sbml+xml sbml +application/scvp-cv-request scq +application/scvp-cv-response scs +application/scvp-vp-request spq +application/scvp-vp-response spp +application/sdp sdp +# application/set-payment +application/set-payment-initiation setpay +# application/set-registration +application/set-registration-initiation setreg +# application/sgml +# application/sgml-open-catalog +application/shf+xml shf +# application/sieve +# application/simple-filter+xml +# application/simple-message-summary +# application/simplesymbolcontainer +# application/slate +# application/smil +application/smil+xml smi smil +# application/soap+fastinfoset +# application/soap+xml +application/sparql-query rq +application/sparql-results+xml srx +# application/spirits-event+xml +application/srgs gram +application/srgs+xml grxml +application/sru+xml sru +application/ssdl+xml ssdl +application/ssml+xml ssml +# application/tamp-apex-update +# application/tamp-apex-update-confirm +# application/tamp-community-update +# application/tamp-community-update-confirm +# application/tamp-error +# application/tamp-sequence-adjust +# application/tamp-sequence-adjust-confirm +# application/tamp-status-query +# application/tamp-status-response +# application/tamp-update +# application/tamp-update-confirm +application/tei+xml tei teicorpus +application/thraud+xml tfi +# application/timestamp-query +# application/timestamp-reply +application/timestamped-data tsd +# application/tve-trigger +# application/ulpfec +# application/vcard+xml +# application/vemmi +# application/vividence.scriptfile +# application/vnd.3gpp.bsf+xml +application/vnd.3gpp.pic-bw-large plb +application/vnd.3gpp.pic-bw-small psb +application/vnd.3gpp.pic-bw-var pvb +# application/vnd.3gpp.sms +# application/vnd.3gpp2.bcmcsinfo+xml +# application/vnd.3gpp2.sms +application/vnd.3gpp2.tcap tcap +application/vnd.3m.post-it-notes pwn +application/vnd.accpac.simply.aso aso +application/vnd.accpac.simply.imp imp +application/vnd.acucobol acu +application/vnd.acucorp atc acutc +application/vnd.adobe.air-application-installer-package+zip air +application/vnd.adobe.formscentral.fcdt fcdt +application/vnd.adobe.fxp fxp fxpl +# application/vnd.adobe.partial-upload +application/vnd.adobe.xdp+xml xdp +application/vnd.adobe.xfdf xfdf +# application/vnd.aether.imp +# application/vnd.ah-barcode +application/vnd.ahead.space ahead +application/vnd.airzip.filesecure.azf azf +application/vnd.airzip.filesecure.azs azs +application/vnd.amazon.ebook azw +application/vnd.americandynamics.acc acc +application/vnd.amiga.ami ami +# application/vnd.amundsen.maze+xml +application/vnd.android.package-archive apk +application/vnd.anser-web-certificate-issue-initiation cii +application/vnd.anser-web-funds-transfer-initiation fti +application/vnd.antix.game-component atx +application/vnd.apple.installer+xml mpkg +application/vnd.apple.mpegurl m3u8 +# application/vnd.arastra.swi +application/vnd.aristanetworks.swi swi +application/vnd.astraea-software.iota iota +application/vnd.audiograph aep +# application/vnd.autopackage +# application/vnd.avistar+xml +application/vnd.blueice.multipass mpm +# application/vnd.bluetooth.ep.oob +application/vnd.bmi bmi +application/vnd.businessobjects rep +# application/vnd.cab-jscript +# application/vnd.canon-cpdl +# application/vnd.canon-lips +# application/vnd.cendio.thinlinc.clientconf +application/vnd.chemdraw+xml cdxml +application/vnd.chipnuts.karaoke-mmd mmd +application/vnd.cinderella cdy +# application/vnd.cirpack.isdn-ext +application/vnd.claymore cla +application/vnd.cloanto.rp9 rp9 +application/vnd.clonk.c4group c4g c4d c4f c4p c4u +application/vnd.cluetrust.cartomobile-config c11amc +application/vnd.cluetrust.cartomobile-config-pkg c11amz +# application/vnd.collection+json +# application/vnd.commerce-battelle +application/vnd.commonspace csp +application/vnd.contact.cmsg cdbcmsg +application/vnd.cosmocaller cmc +application/vnd.crick.clicker clkx +application/vnd.crick.clicker.keyboard clkk +application/vnd.crick.clicker.palette clkp +application/vnd.crick.clicker.template clkt +application/vnd.crick.clicker.wordbank clkw +application/vnd.criticaltools.wbs+xml wbs +application/vnd.ctc-posml pml +# application/vnd.ctct.ws+xml +# application/vnd.cups-pdf +# application/vnd.cups-postscript +application/vnd.cups-ppd ppd +# application/vnd.cups-raster +# application/vnd.cups-raw +# application/vnd.curl +application/vnd.curl.car car +application/vnd.curl.pcurl pcurl +# application/vnd.cybank +application/vnd.dart dart +application/vnd.data-vision.rdz rdz +application/vnd.dece.data uvf uvvf uvd uvvd +application/vnd.dece.ttml+xml uvt uvvt +application/vnd.dece.unspecified uvx uvvx +application/vnd.dece.zip uvz uvvz +application/vnd.denovo.fcselayout-link fe_launch +# application/vnd.dir-bi.plate-dl-nosuffix +application/vnd.dna dna +application/vnd.dolby.mlp mlp +# application/vnd.dolby.mobile.1 +# application/vnd.dolby.mobile.2 +application/vnd.dpgraph dpg +application/vnd.dreamfactory dfac +application/vnd.ds-keypoint kpxx +application/vnd.dvb.ait ait +# application/vnd.dvb.dvbj +# application/vnd.dvb.esgcontainer +# application/vnd.dvb.ipdcdftnotifaccess +# application/vnd.dvb.ipdcesgaccess +# application/vnd.dvb.ipdcesgaccess2 +# application/vnd.dvb.ipdcesgpdd +# application/vnd.dvb.ipdcroaming +# application/vnd.dvb.iptv.alfec-base +# application/vnd.dvb.iptv.alfec-enhancement +# application/vnd.dvb.notif-aggregate-root+xml +# application/vnd.dvb.notif-container+xml +# application/vnd.dvb.notif-generic+xml +# application/vnd.dvb.notif-ia-msglist+xml +# application/vnd.dvb.notif-ia-registration-request+xml +# application/vnd.dvb.notif-ia-registration-response+xml +# application/vnd.dvb.notif-init+xml +# application/vnd.dvb.pfr +application/vnd.dvb.service svc +# application/vnd.dxr +application/vnd.dynageo geo +# application/vnd.easykaraoke.cdgdownload +# application/vnd.ecdis-update +application/vnd.ecowin.chart mag +# application/vnd.ecowin.filerequest +# application/vnd.ecowin.fileupdate +# application/vnd.ecowin.series +# application/vnd.ecowin.seriesrequest +# application/vnd.ecowin.seriesupdate +# application/vnd.emclient.accessrequest+xml +application/vnd.enliven nml +# application/vnd.eprints.data+xml +application/vnd.epson.esf esf +application/vnd.epson.msf msf +application/vnd.epson.quickanime qam +application/vnd.epson.salt slt +application/vnd.epson.ssf ssf +# application/vnd.ericsson.quickcall +application/vnd.eszigno3+xml es3 et3 +# application/vnd.etsi.aoc+xml +# application/vnd.etsi.cug+xml +# application/vnd.etsi.iptvcommand+xml +# application/vnd.etsi.iptvdiscovery+xml +# application/vnd.etsi.iptvprofile+xml +# application/vnd.etsi.iptvsad-bc+xml +# application/vnd.etsi.iptvsad-cod+xml +# application/vnd.etsi.iptvsad-npvr+xml +# application/vnd.etsi.iptvservice+xml +# application/vnd.etsi.iptvsync+xml +# application/vnd.etsi.iptvueprofile+xml +# application/vnd.etsi.mcid+xml +# application/vnd.etsi.overload-control-policy-dataset+xml +# application/vnd.etsi.sci+xml +# application/vnd.etsi.simservs+xml +# application/vnd.etsi.tsl+xml +# application/vnd.etsi.tsl.der +# application/vnd.eudora.data +application/vnd.ezpix-album ez2 +application/vnd.ezpix-package ez3 +# application/vnd.f-secure.mobile +application/vnd.fdf fdf +application/vnd.fdsn.mseed mseed +application/vnd.fdsn.seed seed dataless +# application/vnd.ffsns +# application/vnd.fints +application/vnd.flographit gph +application/vnd.fluxtime.clip ftc +# application/vnd.font-fontforge-sfd +application/vnd.framemaker fm frame maker book +application/vnd.frogans.fnc fnc +application/vnd.frogans.ltf ltf +application/vnd.fsc.weblaunch fsc +application/vnd.fujitsu.oasys oas +application/vnd.fujitsu.oasys2 oa2 +application/vnd.fujitsu.oasys3 oa3 +application/vnd.fujitsu.oasysgp fg5 +application/vnd.fujitsu.oasysprs bh2 +# application/vnd.fujixerox.art-ex +# application/vnd.fujixerox.art4 +# application/vnd.fujixerox.hbpl +application/vnd.fujixerox.ddd ddd +application/vnd.fujixerox.docuworks xdw +application/vnd.fujixerox.docuworks.binder xbd +# application/vnd.fut-misnet +application/vnd.fuzzysheet fzs +application/vnd.genomatix.tuxedo txd +# application/vnd.geocube+xml +application/vnd.geogebra.file ggb +application/vnd.geogebra.tool ggt +application/vnd.geometry-explorer gex gre +application/vnd.geonext gxt +application/vnd.geoplan g2w +application/vnd.geospace g3w +# application/vnd.globalplatform.card-content-mgt +# application/vnd.globalplatform.card-content-mgt-response +application/vnd.gmx gmx +application/vnd.google-earth.kml+xml kml +application/vnd.google-earth.kmz kmz +application/vnd.grafeq gqf gqs +# application/vnd.gridmp +application/vnd.groove-account gac +application/vnd.groove-help ghf +application/vnd.groove-identity-message gim +application/vnd.groove-injector grv +application/vnd.groove-tool-message gtm +application/vnd.groove-tool-template tpl +application/vnd.groove-vcard vcg +# application/vnd.hal+json +application/vnd.hal+xml hal +application/vnd.handheld-entertainment+xml zmm +application/vnd.hbci hbci +# application/vnd.hcl-bireports +application/vnd.hhe.lesson-player les +application/vnd.hp-hpgl hpgl +application/vnd.hp-hpid hpid +application/vnd.hp-hps hps +application/vnd.hp-jlyt jlt +application/vnd.hp-pcl pcl +application/vnd.hp-pclxl pclxl +# application/vnd.httphone +application/vnd.hydrostatix.sof-data sfd-hdstx +# application/vnd.hzn-3d-crossword +# application/vnd.ibm.afplinedata +# application/vnd.ibm.electronic-media +application/vnd.ibm.minipay mpy +application/vnd.ibm.modcap afp listafp list3820 +application/vnd.ibm.rights-management irm +application/vnd.ibm.secure-container sc +application/vnd.iccprofile icc icm +application/vnd.igloader igl +application/vnd.immervision-ivp ivp +application/vnd.immervision-ivu ivu +# application/vnd.informedcontrol.rms+xml +# application/vnd.informix-visionary +# application/vnd.infotech.project +# application/vnd.infotech.project+xml +# application/vnd.innopath.wamp.notification +application/vnd.insors.igm igm +application/vnd.intercon.formnet xpw xpx +application/vnd.intergeo i2g +# application/vnd.intertrust.digibox +# application/vnd.intertrust.nncp +application/vnd.intu.qbo qbo +application/vnd.intu.qfx qfx +# application/vnd.iptc.g2.conceptitem+xml +# application/vnd.iptc.g2.knowledgeitem+xml +# application/vnd.iptc.g2.newsitem+xml +# application/vnd.iptc.g2.newsmessage+xml +# application/vnd.iptc.g2.packageitem+xml +# application/vnd.iptc.g2.planningitem+xml +application/vnd.ipunplugged.rcprofile rcprofile +application/vnd.irepository.package+xml irp +application/vnd.is-xpr xpr +application/vnd.isac.fcs fcs +application/vnd.jam jam +# application/vnd.japannet-directory-service +# application/vnd.japannet-jpnstore-wakeup +# application/vnd.japannet-payment-wakeup +# application/vnd.japannet-registration +# application/vnd.japannet-registration-wakeup +# application/vnd.japannet-setstore-wakeup +# application/vnd.japannet-verification +# application/vnd.japannet-verification-wakeup +application/vnd.jcp.javame.midlet-rms rms +application/vnd.jisp jisp +application/vnd.joost.joda-archive joda +application/vnd.kahootz ktz ktr +application/vnd.kde.karbon karbon +application/vnd.kde.kchart chrt +application/vnd.kde.kformula kfo +application/vnd.kde.kivio flw +application/vnd.kde.kontour kon +application/vnd.kde.kpresenter kpr kpt +application/vnd.kde.kspread ksp +application/vnd.kde.kword kwd kwt +application/vnd.kenameaapp htke +application/vnd.kidspiration kia +application/vnd.kinar kne knp +application/vnd.koan skp skd skt skm +application/vnd.kodak-descriptor sse +application/vnd.las.las+xml lasxml +# application/vnd.liberty-request+xml +application/vnd.llamagraphics.life-balance.desktop lbd +application/vnd.llamagraphics.life-balance.exchange+xml lbe +application/vnd.lotus-1-2-3 123 +application/vnd.lotus-approach apr +application/vnd.lotus-freelance pre +application/vnd.lotus-notes nsf +application/vnd.lotus-organizer org +application/vnd.lotus-screencam scm +application/vnd.lotus-wordpro lwp +application/vnd.macports.portpkg portpkg +# application/vnd.marlin.drm.actiontoken+xml +# application/vnd.marlin.drm.conftoken+xml +# application/vnd.marlin.drm.license+xml +# application/vnd.marlin.drm.mdcf +application/vnd.mcd mcd +application/vnd.medcalcdata mc1 +application/vnd.mediastation.cdkey cdkey +# application/vnd.meridian-slingshot +application/vnd.mfer mwf +application/vnd.mfmp mfm +application/vnd.micrografx.flo flo +application/vnd.micrografx.igx igx +application/vnd.mif mif +# application/vnd.minisoft-hp3000-save +# application/vnd.mitsubishi.misty-guard.trustweb +application/vnd.mobius.daf daf +application/vnd.mobius.dis dis +application/vnd.mobius.mbk mbk +application/vnd.mobius.mqy mqy +application/vnd.mobius.msl msl +application/vnd.mobius.plc plc +application/vnd.mobius.txf txf +application/vnd.mophun.application mpn +application/vnd.mophun.certificate mpc +# application/vnd.motorola.flexsuite +# application/vnd.motorola.flexsuite.adsi +# application/vnd.motorola.flexsuite.fis +# application/vnd.motorola.flexsuite.gotap +# application/vnd.motorola.flexsuite.kmr +# application/vnd.motorola.flexsuite.ttc +# application/vnd.motorola.flexsuite.wem +# application/vnd.motorola.iprm +application/vnd.mozilla.xul+xml xul +application/vnd.ms-artgalry cil +# application/vnd.ms-asf +application/vnd.ms-cab-compressed cab +# application/vnd.ms-color.iccprofile +application/vnd.ms-excel xls xlm xla xlc xlt xlw +application/vnd.ms-excel.addin.macroenabled.12 xlam +application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb +application/vnd.ms-excel.sheet.macroenabled.12 xlsm +application/vnd.ms-excel.template.macroenabled.12 xltm +application/vnd.ms-fontobject eot +application/vnd.ms-htmlhelp chm +application/vnd.ms-ims ims +application/vnd.ms-lrm lrm +# application/vnd.ms-office.activex+xml +application/vnd.ms-officetheme thmx +# application/vnd.ms-opentype +# application/vnd.ms-package.obfuscated-opentype +application/vnd.ms-pki.seccat cat +application/vnd.ms-pki.stl stl +# application/vnd.ms-playready.initiator+xml +application/vnd.ms-powerpoint ppt pps pot +application/vnd.ms-powerpoint.addin.macroenabled.12 ppam +application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm +application/vnd.ms-powerpoint.slide.macroenabled.12 sldm +application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm +application/vnd.ms-powerpoint.template.macroenabled.12 potm +# application/vnd.ms-printing.printticket+xml +application/vnd.ms-project mpp mpt +# application/vnd.ms-tnef +# application/vnd.ms-wmdrm.lic-chlg-req +# application/vnd.ms-wmdrm.lic-resp +# application/vnd.ms-wmdrm.meter-chlg-req +# application/vnd.ms-wmdrm.meter-resp +application/vnd.ms-word.document.macroenabled.12 docm +application/vnd.ms-word.template.macroenabled.12 dotm +application/vnd.ms-works wps wks wcm wdb +application/vnd.ms-wpl wpl +application/vnd.ms-xpsdocument xps +application/vnd.mseq mseq +# application/vnd.msign +# application/vnd.multiad.creator +# application/vnd.multiad.creator.cif +# application/vnd.music-niff +application/vnd.musician mus +application/vnd.muvee.style msty +application/vnd.mynfc taglet +# application/vnd.ncd.control +# application/vnd.ncd.reference +# application/vnd.nervana +# application/vnd.netfpx +application/vnd.neurolanguage.nlu nlu +application/vnd.nitf ntf nitf +application/vnd.noblenet-directory nnd +application/vnd.noblenet-sealer nns +application/vnd.noblenet-web nnw +# application/vnd.nokia.catalogs +# application/vnd.nokia.conml+wbxml +# application/vnd.nokia.conml+xml +# application/vnd.nokia.isds-radio-presets +# application/vnd.nokia.iptv.config+xml +# application/vnd.nokia.landmark+wbxml +# application/vnd.nokia.landmark+xml +# application/vnd.nokia.landmarkcollection+xml +# application/vnd.nokia.n-gage.ac+xml +application/vnd.nokia.n-gage.data ngdat +application/vnd.nokia.n-gage.symbian.install n-gage +# application/vnd.nokia.ncd +# application/vnd.nokia.pcd+wbxml +# application/vnd.nokia.pcd+xml +application/vnd.nokia.radio-preset rpst +application/vnd.nokia.radio-presets rpss +application/vnd.novadigm.edm edm +application/vnd.novadigm.edx edx +application/vnd.novadigm.ext ext +# application/vnd.ntt-local.file-transfer +# application/vnd.ntt-local.sip-ta_remote +# application/vnd.ntt-local.sip-ta_tcp_stream +application/vnd.oasis.opendocument.chart odc +application/vnd.oasis.opendocument.chart-template otc +application/vnd.oasis.opendocument.database odb +application/vnd.oasis.opendocument.formula odf +application/vnd.oasis.opendocument.formula-template odft +application/vnd.oasis.opendocument.graphics odg +application/vnd.oasis.opendocument.graphics-template otg +application/vnd.oasis.opendocument.image odi +application/vnd.oasis.opendocument.image-template oti +application/vnd.oasis.opendocument.presentation odp +application/vnd.oasis.opendocument.presentation-template otp +application/vnd.oasis.opendocument.spreadsheet ods +application/vnd.oasis.opendocument.spreadsheet-template ots +application/vnd.oasis.opendocument.text odt +application/vnd.oasis.opendocument.text-master odm +application/vnd.oasis.opendocument.text-template ott +application/vnd.oasis.opendocument.text-web oth +# application/vnd.obn +# application/vnd.oftn.l10n+json +# application/vnd.oipf.contentaccessdownload+xml +# application/vnd.oipf.contentaccessstreaming+xml +# application/vnd.oipf.cspg-hexbinary +# application/vnd.oipf.dae.svg+xml +# application/vnd.oipf.dae.xhtml+xml +# application/vnd.oipf.mippvcontrolmessage+xml +# application/vnd.oipf.pae.gem +# application/vnd.oipf.spdiscovery+xml +# application/vnd.oipf.spdlist+xml +# application/vnd.oipf.ueprofile+xml +# application/vnd.oipf.userprofile+xml +application/vnd.olpc-sugar xo +# application/vnd.oma-scws-config +# application/vnd.oma-scws-http-request +# application/vnd.oma-scws-http-response +# application/vnd.oma.bcast.associated-procedure-parameter+xml +# application/vnd.oma.bcast.drm-trigger+xml +# application/vnd.oma.bcast.imd+xml +# application/vnd.oma.bcast.ltkm +# application/vnd.oma.bcast.notification+xml +# application/vnd.oma.bcast.provisioningtrigger +# application/vnd.oma.bcast.sgboot +# application/vnd.oma.bcast.sgdd+xml +# application/vnd.oma.bcast.sgdu +# application/vnd.oma.bcast.simple-symbol-container +# application/vnd.oma.bcast.smartcard-trigger+xml +# application/vnd.oma.bcast.sprov+xml +# application/vnd.oma.bcast.stkm +# application/vnd.oma.cab-address-book+xml +# application/vnd.oma.cab-feature-handler+xml +# application/vnd.oma.cab-pcc+xml +# application/vnd.oma.cab-user-prefs+xml +# application/vnd.oma.dcd +# application/vnd.oma.dcdc +application/vnd.oma.dd2+xml dd2 +# application/vnd.oma.drm.risd+xml +# application/vnd.oma.group-usage-list+xml +# application/vnd.oma.pal+xml +# application/vnd.oma.poc.detailed-progress-report+xml +# application/vnd.oma.poc.final-report+xml +# application/vnd.oma.poc.groups+xml +# application/vnd.oma.poc.invocation-descriptor+xml +# application/vnd.oma.poc.optimized-progress-report+xml +# application/vnd.oma.push +# application/vnd.oma.scidm.messages+xml +# application/vnd.oma.xcap-directory+xml +# application/vnd.omads-email+xml +# application/vnd.omads-file+xml +# application/vnd.omads-folder+xml +# application/vnd.omaloc-supl-init +application/vnd.openofficeorg.extension oxt +# application/vnd.openxmlformats-officedocument.custom-properties+xml +# application/vnd.openxmlformats-officedocument.customxmlproperties+xml +# application/vnd.openxmlformats-officedocument.drawing+xml +# application/vnd.openxmlformats-officedocument.drawingml.chart+xml +# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml +# application/vnd.openxmlformats-officedocument.extended-properties+xml +# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml +# application/vnd.openxmlformats-officedocument.presentationml.comments+xml +# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml +application/vnd.openxmlformats-officedocument.presentationml.presentation pptx +# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml +application/vnd.openxmlformats-officedocument.presentationml.slide sldx +# application/vnd.openxmlformats-officedocument.presentationml.slide+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml +application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx +# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml +# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml +# application/vnd.openxmlformats-officedocument.presentationml.tags+xml +application/vnd.openxmlformats-officedocument.presentationml.template potx +# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx +# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml +# application/vnd.openxmlformats-officedocument.theme+xml +# application/vnd.openxmlformats-officedocument.themeoverride+xml +# application/vnd.openxmlformats-officedocument.vmldrawing +# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.document docx +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx +# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml +# application/vnd.openxmlformats-package.core-properties+xml +# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml +# application/vnd.openxmlformats-package.relationships+xml +# application/vnd.quobject-quoxdocument +# application/vnd.osa.netdeploy +application/vnd.osgeo.mapguide.package mgp +# application/vnd.osgi.bundle +application/vnd.osgi.dp dp +application/vnd.osgi.subsystem esa +# application/vnd.otps.ct-kip+xml +application/vnd.palm pdb pqa oprc +# application/vnd.paos.xml +application/vnd.pawaafile paw +application/vnd.pg.format str +application/vnd.pg.osasli ei6 +# application/vnd.piaccess.application-licence +application/vnd.picsel efif +application/vnd.pmi.widget wg +# application/vnd.poc.group-advertisement+xml +application/vnd.pocketlearn plf +application/vnd.powerbuilder6 pbd +# application/vnd.powerbuilder6-s +# application/vnd.powerbuilder7 +# application/vnd.powerbuilder7-s +# application/vnd.powerbuilder75 +# application/vnd.powerbuilder75-s +# application/vnd.preminet +application/vnd.previewsystems.box box +application/vnd.proteus.magazine mgz +application/vnd.publishare-delta-tree qps +application/vnd.pvi.ptid1 ptid +# application/vnd.pwg-multiplexed +# application/vnd.pwg-xhtml-print+xml +# application/vnd.qualcomm.brew-app-res +application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb +# application/vnd.radisys.moml+xml +# application/vnd.radisys.msml+xml +# application/vnd.radisys.msml-audit+xml +# application/vnd.radisys.msml-audit-conf+xml +# application/vnd.radisys.msml-audit-conn+xml +# application/vnd.radisys.msml-audit-dialog+xml +# application/vnd.radisys.msml-audit-stream+xml +# application/vnd.radisys.msml-conf+xml +# application/vnd.radisys.msml-dialog+xml +# application/vnd.radisys.msml-dialog-base+xml +# application/vnd.radisys.msml-dialog-fax-detect+xml +# application/vnd.radisys.msml-dialog-fax-sendrecv+xml +# application/vnd.radisys.msml-dialog-group+xml +# application/vnd.radisys.msml-dialog-speech+xml +# application/vnd.radisys.msml-dialog-transform+xml +# application/vnd.rainstor.data +# application/vnd.rapid +application/vnd.realvnc.bed bed +application/vnd.recordare.musicxml mxl +application/vnd.recordare.musicxml+xml musicxml +# application/vnd.renlearn.rlprint +application/vnd.rig.cryptonote cryptonote +application/vnd.rim.cod cod +application/vnd.rn-realmedia rm +application/vnd.rn-realmedia-vbr rmvb +application/vnd.route66.link66+xml link66 +# application/vnd.rs-274x +# application/vnd.ruckus.download +# application/vnd.s3sms +application/vnd.sailingtracker.track st +# application/vnd.sbm.cid +# application/vnd.sbm.mid2 +# application/vnd.scribus +# application/vnd.sealed.3df +# application/vnd.sealed.csf +# application/vnd.sealed.doc +# application/vnd.sealed.eml +# application/vnd.sealed.mht +# application/vnd.sealed.net +# application/vnd.sealed.ppt +# application/vnd.sealed.tiff +# application/vnd.sealed.xls +# application/vnd.sealedmedia.softseal.html +# application/vnd.sealedmedia.softseal.pdf +application/vnd.seemail see +application/vnd.sema sema +application/vnd.semd semd +application/vnd.semf semf +application/vnd.shana.informed.formdata ifm +application/vnd.shana.informed.formtemplate itp +application/vnd.shana.informed.interchange iif +application/vnd.shana.informed.package ipk +application/vnd.simtech-mindmapper twd twds +application/vnd.smaf mmf +# application/vnd.smart.notebook +application/vnd.smart.teacher teacher +# application/vnd.software602.filler.form+xml +# application/vnd.software602.filler.form-xml-zip +application/vnd.solent.sdkm+xml sdkm sdkd +application/vnd.spotfire.dxp dxp +application/vnd.spotfire.sfs sfs +# application/vnd.sss-cod +# application/vnd.sss-dtf +# application/vnd.sss-ntf +application/vnd.stardivision.calc sdc +application/vnd.stardivision.draw sda +application/vnd.stardivision.impress sdd +application/vnd.stardivision.math smf +application/vnd.stardivision.writer sdw vor +application/vnd.stardivision.writer-global sgl +application/vnd.stepmania.package smzip +application/vnd.stepmania.stepchart sm +# application/vnd.street-stream +application/vnd.sun.xml.calc sxc +application/vnd.sun.xml.calc.template stc +application/vnd.sun.xml.draw sxd +application/vnd.sun.xml.draw.template std +application/vnd.sun.xml.impress sxi +application/vnd.sun.xml.impress.template sti +application/vnd.sun.xml.math sxm +application/vnd.sun.xml.writer sxw +application/vnd.sun.xml.writer.global sxg +application/vnd.sun.xml.writer.template stw +# application/vnd.sun.wadl+xml +application/vnd.sus-calendar sus susp +application/vnd.svd svd +# application/vnd.swiftview-ics +application/vnd.symbian.install sis sisx +application/vnd.syncml+xml xsm +application/vnd.syncml.dm+wbxml bdm +application/vnd.syncml.dm+xml xdm +# application/vnd.syncml.dm.notification +# application/vnd.syncml.ds.notification +application/vnd.tao.intent-module-archive tao +application/vnd.tcpdump.pcap pcap cap dmp +application/vnd.tmobile-livetv tmo +application/vnd.trid.tpt tpt +application/vnd.triscape.mxs mxs +application/vnd.trueapp tra +# application/vnd.truedoc +# application/vnd.ubisoft.webplayer +application/vnd.ufdl ufd ufdl +application/vnd.uiq.theme utz +application/vnd.umajin umj +application/vnd.unity unityweb +application/vnd.uoml+xml uoml +# application/vnd.uplanet.alert +# application/vnd.uplanet.alert-wbxml +# application/vnd.uplanet.bearer-choice +# application/vnd.uplanet.bearer-choice-wbxml +# application/vnd.uplanet.cacheop +# application/vnd.uplanet.cacheop-wbxml +# application/vnd.uplanet.channel +# application/vnd.uplanet.channel-wbxml +# application/vnd.uplanet.list +# application/vnd.uplanet.list-wbxml +# application/vnd.uplanet.listcmd +# application/vnd.uplanet.listcmd-wbxml +# application/vnd.uplanet.signal +application/vnd.vcx vcx +# application/vnd.vd-study +# application/vnd.vectorworks +# application/vnd.verimatrix.vcas +# application/vnd.vidsoft.vidconference +application/vnd.visio vsd vst vss vsw +application/vnd.visionary vis +# application/vnd.vividence.scriptfile +application/vnd.vsf vsf +# application/vnd.wap.sic +# application/vnd.wap.slc +application/vnd.wap.wbxml wbxml +application/vnd.wap.wmlc wmlc +application/vnd.wap.wmlscriptc wmlsc +application/vnd.webturbo wtb +# application/vnd.wfa.wsc +# application/vnd.wmc +# application/vnd.wmf.bootstrap +# application/vnd.wolfram.mathematica +# application/vnd.wolfram.mathematica.package +application/vnd.wolfram.player nbp +application/vnd.wordperfect wpd +application/vnd.wqd wqd +# application/vnd.wrq-hp3000-labelled +application/vnd.wt.stf stf +# application/vnd.wv.csp+wbxml +# application/vnd.wv.csp+xml +# application/vnd.wv.ssp+xml +application/vnd.xara xar +application/vnd.xfdl xfdl +# application/vnd.xfdl.webform +# application/vnd.xmi+xml +# application/vnd.xmpie.cpkg +# application/vnd.xmpie.dpkg +# application/vnd.xmpie.plan +# application/vnd.xmpie.ppkg +# application/vnd.xmpie.xlim +application/vnd.yamaha.hv-dic hvd +application/vnd.yamaha.hv-script hvs +application/vnd.yamaha.hv-voice hvp +application/vnd.yamaha.openscoreformat osf +application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg +# application/vnd.yamaha.remote-setup +application/vnd.yamaha.smaf-audio saf +application/vnd.yamaha.smaf-phrase spf +# application/vnd.yamaha.through-ngn +# application/vnd.yamaha.tunnel-udpencap +application/vnd.yellowriver-custom-menu cmp +application/vnd.zul zir zirz +application/vnd.zzazz.deck+xml zaz +application/voicexml+xml vxml +# application/vq-rtcpxr +# application/watcherinfo+xml +# application/whoispp-query +# application/whoispp-response +application/widget wgt +application/winhlp hlp +# application/wita +# application/wordperfect5.1 +application/wsdl+xml wsdl +application/wspolicy+xml wspolicy +application/x-7z-compressed 7z +application/x-abiword abw +application/x-ace-compressed ace +# application/x-amf +application/x-apple-diskimage dmg +application/x-authorware-bin aab x32 u32 vox +application/x-authorware-map aam +application/x-authorware-seg aas +application/x-bcpio bcpio +application/x-bittorrent torrent +application/x-blorb blb blorb +application/x-bzip bz +application/x-bzip2 bz2 boz +application/x-cbr cbr cba cbt cbz cb7 +application/x-cdlink vcd +application/x-cfs-compressed cfs +application/x-chat chat +application/x-chess-pgn pgn +application/x-conference nsc +# application/x-compress +application/x-cpio cpio +application/x-csh csh +application/x-debian-package deb udeb +application/x-dgc-compressed dgc +application/x-director dir dcr dxr cst cct cxt w3d fgd swa +application/x-doom wad +application/x-dtbncx+xml ncx +application/x-dtbook+xml dtb +application/x-dtbresource+xml res +application/x-dvi dvi +application/x-envoy evy +application/x-eva eva +application/x-font-bdf bdf +# application/x-font-dos +# application/x-font-framemaker +application/x-font-ghostscript gsf +# application/x-font-libgrx +application/x-font-linux-psf psf +application/x-font-otf otf +application/x-font-pcf pcf +application/x-font-snf snf +# application/x-font-speedo +# application/x-font-sunos-news +application/x-font-ttf ttf ttc +application/x-font-type1 pfa pfb pfm afm +application/font-woff woff +# application/x-font-vfont +application/x-freearc arc +application/x-futuresplash spl +application/x-gca-compressed gca +application/x-glulx ulx +application/x-gnumeric gnumeric +application/x-gramps-xml gramps +application/x-gtar gtar +# application/x-gzip +application/x-hdf hdf +application/x-install-instructions install +application/x-iso9660-image iso +application/x-java-jnlp-file jnlp +application/x-latex latex +application/x-lzh-compressed lzh lha +application/x-mie mie +application/x-mobipocket-ebook prc mobi +application/x-ms-application application +application/x-ms-shortcut lnk +application/x-ms-wmd wmd +application/x-ms-wmz wmz +application/x-ms-xbap xbap +application/x-msaccess mdb +application/x-msbinder obd +application/x-mscardfile crd +application/x-msclip clp +application/x-msdownload exe dll com bat msi +application/x-msmediaview mvb m13 m14 +application/x-msmetafile wmf wmz emf emz +application/x-msmoney mny +application/x-mspublisher pub +application/x-msschedule scd +application/x-msterminal trm +application/x-mswrite wri +application/x-netcdf nc cdf +application/x-nzb nzb +application/x-pkcs12 p12 pfx +application/x-pkcs7-certificates p7b spc +application/x-pkcs7-certreqresp p7r +application/x-rar-compressed rar +application/x-research-info-systems ris +application/x-sh sh +application/x-shar shar +application/x-shockwave-flash swf +application/x-silverlight-app xap +application/x-sql sql +application/x-stuffit sit +application/x-stuffitx sitx +application/x-subrip srt +application/x-sv4cpio sv4cpio +application/x-sv4crc sv4crc +application/x-t3vm-image t3 +application/x-tads gam +application/x-tar tar +application/x-tcl tcl +application/x-tex tex +application/x-tex-tfm tfm +application/x-texinfo texinfo texi +application/x-tgif obj +application/x-ustar ustar +application/x-wais-source src +application/x-x509-ca-cert der crt +application/x-xfig fig +application/x-xliff+xml xlf +application/x-xpinstall xpi +application/x-xz xz +application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 +# application/x400-bp +application/xaml+xml xaml +# application/xcap-att+xml +# application/xcap-caps+xml +application/xcap-diff+xml xdf +# application/xcap-el+xml +# application/xcap-error+xml +# application/xcap-ns+xml +# application/xcon-conference-info-diff+xml +# application/xcon-conference-info+xml +application/xenc+xml xenc +application/xhtml+xml xhtml xht +# application/xhtml-voice+xml +application/xml xml xsl +application/xml-dtd dtd +# application/xml-external-parsed-entity +# application/xmpp+xml +application/xop+xml xop +application/xproc+xml xpl +application/xslt+xml xslt +application/xspf+xml xspf +application/xv+xml mxml xhvml xvml xvm +application/yang yang +application/yin+xml yin +application/zip zip +# audio/1d-interleaved-parityfec +# audio/32kadpcm +# audio/3gpp +# audio/3gpp2 +# audio/ac3 +audio/adpcm adp +# audio/amr +# audio/amr-wb +# audio/amr-wb+ +# audio/asc +# audio/atrac-advanced-lossless +# audio/atrac-x +# audio/atrac3 +audio/basic au snd +# audio/bv16 +# audio/bv32 +# audio/clearmode +# audio/cn +# audio/dat12 +# audio/dls +# audio/dsr-es201108 +# audio/dsr-es202050 +# audio/dsr-es202211 +# audio/dsr-es202212 +# audio/dv +# audio/dvi4 +# audio/eac3 +# audio/evrc +# audio/evrc-qcp +# audio/evrc0 +# audio/evrc1 +# audio/evrcb +# audio/evrcb0 +# audio/evrcb1 +# audio/evrcwb +# audio/evrcwb0 +# audio/evrcwb1 +# audio/example +# audio/fwdred +# audio/g719 +# audio/g722 +# audio/g7221 +# audio/g723 +# audio/g726-16 +# audio/g726-24 +# audio/g726-32 +# audio/g726-40 +# audio/g728 +# audio/g729 +# audio/g7291 +# audio/g729d +# audio/g729e +# audio/gsm +# audio/gsm-efr +# audio/gsm-hr-08 +# audio/ilbc +# audio/ip-mr_v2.5 +# audio/isac +# audio/l16 +# audio/l20 +# audio/l24 +# audio/l8 +# audio/lpc +audio/midi mid midi kar rmi +# audio/mobile-xmf +audio/mp4 mp4a +# audio/mp4a-latm +# audio/mpa +# audio/mpa-robust +audio/mpeg mpga mp2 mp2a mp3 m2a m3a +# audio/mpeg4-generic +# audio/musepack +audio/ogg oga ogg spx +# audio/opus +# audio/parityfec +# audio/pcma +# audio/pcma-wb +# audio/pcmu-wb +# audio/pcmu +# audio/prs.sid +# audio/qcelp +# audio/red +# audio/rtp-enc-aescm128 +# audio/rtp-midi +# audio/rtx +audio/s3m s3m +audio/silk sil +# audio/smv +# audio/smv0 +# audio/smv-qcp +# audio/sp-midi +# audio/speex +# audio/t140c +# audio/t38 +# audio/telephone-event +# audio/tone +# audio/uemclip +# audio/ulpfec +# audio/vdvi +# audio/vmr-wb +# audio/vnd.3gpp.iufp +# audio/vnd.4sb +# audio/vnd.audiokoz +# audio/vnd.celp +# audio/vnd.cisco.nse +# audio/vnd.cmles.radio-events +# audio/vnd.cns.anp1 +# audio/vnd.cns.inf1 +audio/vnd.dece.audio uva uvva +audio/vnd.digital-winds eol +# audio/vnd.dlna.adts +# audio/vnd.dolby.heaac.1 +# audio/vnd.dolby.heaac.2 +# audio/vnd.dolby.mlp +# audio/vnd.dolby.mps +# audio/vnd.dolby.pl2 +# audio/vnd.dolby.pl2x +# audio/vnd.dolby.pl2z +# audio/vnd.dolby.pulse.1 +audio/vnd.dra dra +audio/vnd.dts dts +audio/vnd.dts.hd dtshd +# audio/vnd.dvb.file +# audio/vnd.everad.plj +# audio/vnd.hns.audio +audio/vnd.lucent.voice lvp +audio/vnd.ms-playready.media.pya pya +# audio/vnd.nokia.mobile-xmf +# audio/vnd.nortel.vbk +audio/vnd.nuera.ecelp4800 ecelp4800 +audio/vnd.nuera.ecelp7470 ecelp7470 +audio/vnd.nuera.ecelp9600 ecelp9600 +# audio/vnd.octel.sbc +# audio/vnd.qcelp +# audio/vnd.rhetorex.32kadpcm +audio/vnd.rip rip +# audio/vnd.sealedmedia.softseal.mpeg +# audio/vnd.vmx.cvsd +# audio/vorbis +# audio/vorbis-config +audio/webm weba +audio/x-aac aac +audio/x-aiff aif aiff aifc +audio/x-caf caf +audio/x-flac flac +audio/x-matroska mka +audio/x-mpegurl m3u +audio/x-ms-wax wax +audio/x-ms-wma wma +audio/x-pn-realaudio ram ra +audio/x-pn-realaudio-plugin rmp +# audio/x-tta +audio/x-wav wav +audio/xm xm +chemical/x-cdx cdx +chemical/x-cif cif +chemical/x-cmdf cmdf +chemical/x-cml cml +chemical/x-csml csml +# chemical/x-pdb +chemical/x-xyz xyz +image/bmp bmp +image/cgm cgm +# image/example +# image/fits +image/g3fax g3 +image/gif gif +image/ief ief +# image/jp2 +image/jpeg jpeg jpg jpe +# image/jpm +# image/jpx +image/ktx ktx +# image/naplps +image/png png +image/prs.btif btif +# image/prs.pti +image/sgi sgi +image/svg+xml svg svgz +# image/t38 +image/tiff tiff tif +# image/tiff-fx +image/vnd.adobe.photoshop psd +# image/vnd.cns.inf2 +image/vnd.dece.graphic uvi uvvi uvg uvvg +image/vnd.dvb.subtitle sub +image/vnd.djvu djvu djv +image/vnd.dwg dwg +image/vnd.dxf dxf +image/vnd.fastbidsheet fbs +image/vnd.fpx fpx +image/vnd.fst fst +image/vnd.fujixerox.edmics-mmr mmr +image/vnd.fujixerox.edmics-rlc rlc +# image/vnd.globalgraphics.pgb +# image/vnd.microsoft.icon +# image/vnd.mix +image/vnd.ms-modi mdi +image/vnd.ms-photo wdp +image/vnd.net-fpx npx +# image/vnd.radiance +# image/vnd.sealed.png +# image/vnd.sealedmedia.softseal.gif +# image/vnd.sealedmedia.softseal.jpg +# image/vnd.svf +image/vnd.wap.wbmp wbmp +image/vnd.xiff xif +image/webp webp +image/x-3ds 3ds +image/x-cmu-raster ras +image/x-cmx cmx +image/x-freehand fh fhc fh4 fh5 fh7 +image/x-icon ico +image/x-mrsid-image sid +image/x-pcx pcx +image/x-pict pic pct +image/x-portable-anymap pnm +image/x-portable-bitmap pbm +image/x-portable-graymap pgm +image/x-portable-pixmap ppm +image/x-rgb rgb +image/x-tga tga +image/x-xbitmap xbm +image/x-xpixmap xpm +image/x-xwindowdump xwd +# message/cpim +# message/delivery-status +# message/disposition-notification +# message/example +# message/external-body +# message/feedback-report +# message/global +# message/global-delivery-status +# message/global-disposition-notification +# message/global-headers +# message/http +# message/imdn+xml +# message/news +# message/partial +message/rfc822 eml mime +# message/s-http +# message/sip +# message/sipfrag +# message/tracking-status +# message/vnd.si.simp +# model/example +model/iges igs iges +model/mesh msh mesh silo +model/vnd.collada+xml dae +model/vnd.dwf dwf +# model/vnd.flatland.3dml +model/vnd.gdl gdl +# model/vnd.gs-gdl +# model/vnd.gs.gdl +model/vnd.gtw gtw +# model/vnd.moml+xml +model/vnd.mts mts +# model/vnd.parasolid.transmit.binary +# model/vnd.parasolid.transmit.text +model/vnd.vtu vtu +model/vrml wrl vrml +model/x3d+binary x3db x3dbz +model/x3d+vrml x3dv x3dvz +model/x3d+xml x3d x3dz +# multipart/alternative +# multipart/appledouble +# multipart/byteranges +# multipart/digest +# multipart/encrypted +# multipart/example +# multipart/form-data +# multipart/header-set +# multipart/mixed +# multipart/parallel +# multipart/related +# multipart/report +# multipart/signed +# multipart/voice-message +# text/1d-interleaved-parityfec +text/cache-manifest appcache +text/calendar ics ifb +text/css css +text/csv csv +# text/directory +# text/dns +# text/ecmascript +# text/enriched +# text/example +# text/fwdred +text/html html htm +# text/javascript +text/n3 n3 +# text/parityfec +text/plain txt text conf def list log in +# text/prs.fallenstein.rst +text/prs.lines.tag dsc +# text/vnd.radisys.msml-basic-layout +# text/red +# text/rfc822-headers +text/richtext rtx +# text/rtf +# text/rtp-enc-aescm128 +# text/rtx +text/sgml sgml sgm +# text/t140 +text/tab-separated-values tsv +text/troff t tr roff man me ms +text/turtle ttl +# text/ulpfec +text/uri-list uri uris urls +text/vcard vcard +# text/vnd.abc +text/vnd.curl curl +text/vnd.curl.dcurl dcurl +text/vnd.curl.scurl scurl +text/vnd.curl.mcurl mcurl +# text/vnd.dmclientscript +text/vnd.dvb.subtitle sub +# text/vnd.esmertec.theme-descriptor +text/vnd.fly fly +text/vnd.fmi.flexstor flx +text/vnd.graphviz gv +text/vnd.in3d.3dml 3dml +text/vnd.in3d.spot spot +# text/vnd.iptc.newsml +# text/vnd.iptc.nitf +# text/vnd.latex-z +# text/vnd.motorola.reflex +# text/vnd.ms-mediapackage +# text/vnd.net2phone.commcenter.command +# text/vnd.si.uricatalogue +text/vnd.sun.j2me.app-descriptor jad +# text/vnd.trolltech.linguist +# text/vnd.wap.si +# text/vnd.wap.sl +text/vnd.wap.wml wml +text/vnd.wap.wmlscript wmls +text/x-asm s asm +text/x-c c cc cxx cpp h hh dic +text/x-fortran f for f77 f90 +text/x-java-source java +text/x-opml opml +text/x-pascal p pas +text/x-nfo nfo +text/x-setext etx +text/x-sfv sfv +text/x-uuencode uu +text/x-vcalendar vcs +text/x-vcard vcf +# text/xml +# text/xml-external-parsed-entity +# video/1d-interleaved-parityfec +video/3gpp 3gp +# video/3gpp-tt +video/3gpp2 3g2 +# video/bmpeg +# video/bt656 +# video/celb +# video/dv +# video/example +video/h261 h261 +video/h263 h263 +# video/h263-1998 +# video/h263-2000 +video/h264 h264 +# video/h264-rcdo +# video/h264-svc +video/jpeg jpgv +# video/jpeg2000 +video/jpm jpm jpgm +video/mj2 mj2 mjp2 +# video/mp1s +# video/mp2p +# video/mp2t +video/mp4 mp4 mp4v mpg4 +# video/mp4v-es +video/mpeg mpeg mpg mpe m1v m2v +# video/mpeg4-generic +# video/mpv +# video/nv +video/ogg ogv +# video/parityfec +# video/pointer +video/quicktime qt mov +# video/raw +# video/rtp-enc-aescm128 +# video/rtx +# video/smpte292m +# video/ulpfec +# video/vc1 +# video/vnd.cctv +video/vnd.dece.hd uvh uvvh +video/vnd.dece.mobile uvm uvvm +# video/vnd.dece.mp4 +video/vnd.dece.pd uvp uvvp +video/vnd.dece.sd uvs uvvs +video/vnd.dece.video uvv uvvv +# video/vnd.directv.mpeg +# video/vnd.directv.mpeg-tts +# video/vnd.dlna.mpeg-tts +video/vnd.dvb.file dvb +video/vnd.fvt fvt +# video/vnd.hns.video +# video/vnd.iptvforum.1dparityfec-1010 +# video/vnd.iptvforum.1dparityfec-2005 +# video/vnd.iptvforum.2dparityfec-1010 +# video/vnd.iptvforum.2dparityfec-2005 +# video/vnd.iptvforum.ttsavc +# video/vnd.iptvforum.ttsmpeg2 +# video/vnd.motorola.video +# video/vnd.motorola.videop +video/vnd.mpegurl mxu m4u +video/vnd.ms-playready.media.pyv pyv +# video/vnd.nokia.interleaved-multimedia +# video/vnd.nokia.videovoip +# video/vnd.objectvideo +# video/vnd.sealed.mpeg1 +# video/vnd.sealed.mpeg4 +# video/vnd.sealed.swf +# video/vnd.sealedmedia.softseal.mov +video/vnd.uvvu.mp4 uvu uvvu +video/vnd.vivo viv +video/webm webm +video/x-f4v f4v +video/x-fli fli +video/x-flv flv +video/x-m4v m4v +video/x-matroska mkv mk3d mks +video/x-mng mng +video/x-ms-asf asf asx +video/x-ms-vob vob +video/x-ms-wm wm +video/x-ms-wmv wmv +video/x-ms-wmx wmx +video/x-ms-wvx wvx +video/x-msvideo avi +video/x-sgi-movie movie +video/x-smv smv +x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/accepts/node_modules/mime/types/node.types b/node_modules/express/node_modules/accepts/node_modules/mime/types/node.types new file mode 100644 index 000000000..55b2cf794 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/mime/types/node.types @@ -0,0 +1,77 @@ +# What: WebVTT +# Why: To allow formats intended for marking up external text track resources. +# http://dev.w3.org/html5/webvtt/ +# Added by: niftylettuce +text/vtt vtt + +# What: Google Chrome Extension +# Why: To allow apps to (work) be served with the right content type header. +# http://codereview.chromium.org/2830017 +# Added by: niftylettuce +application/x-chrome-extension crx + +# What: HTC support +# Why: To properly render .htc files such as CSS3PIE +# Added by: niftylettuce +text/x-component htc + +# What: HTML5 application cache manifes ('.manifest' extension) +# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps +# per https://developer.mozilla.org/en/offline_resources_in_firefox +# Added by: louisremi +text/cache-manifest manifest + +# What: node binary buffer format +# Why: semi-standard extension w/in the node community +# Added by: tootallnate +application/octet-stream buffer + +# What: The "protected" MP-4 formats used by iTunes. +# Why: Required for streaming music to browsers (?) +# Added by: broofa +application/mp4 m4p +audio/mp4 m4a + +# What: Video format, Part of RFC1890 +# Why: See https://github.com/bentomas/node-mime/pull/6 +# Added by: mjrusso +video/MP2T ts + +# What: EventSource mime type +# Why: mime type of Server-Sent Events stream +# http://www.w3.org/TR/eventsource/#text-event-stream +# Added by: francois2metz +text/event-stream event-stream + +# What: Mozilla App manifest mime type +# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests +# Added by: ednapiranha +application/x-web-app-manifest+json webapp + +# What: Lua file types +# Why: Googling around shows de-facto consensus on these +# Added by: creationix (Issue #45) +text/x-lua lua +application/x-lua-bytecode luac + +# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax +# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown +# Added by: avoidwork +text/x-markdown markdown md mkd + +# What: ini files +# Why: because they're just text files +# Added by: Matthew Kastor +text/plain ini + +# What: DASH Adaptive Streaming manifest +# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video +# Added by: eelcocramer +application/dash+xml mdp + +# What: OpenType font files - http://www.microsoft.com/typography/otspec/ +# Why: Browsers usually ignore the font MIME types and sniff the content, +# but Chrome, shows a warning if OpenType fonts aren't served with +# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. +# Added by: alrra +font/opentype otf diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/.npmignore b/node_modules/express/node_modules/accepts/node_modules/negotiator/.npmignore new file mode 100644 index 000000000..a6a8d173b --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/.npmignore @@ -0,0 +1,3 @@ +examples +test +.travis.yml diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE new file mode 100644 index 000000000..42ca2e7d7 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -0,0 +1,27 @@ +Original "Negotiator" program Copyright Federico Romero +Port to JavaScript Copyright Isaac Z. Schlueter + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js new file mode 100644 index 000000000..d2312917c --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -0,0 +1,90 @@ +module.exports = preferredCharsets; +preferredCharsets.preferredCharsets = preferredCharsets; + +function parseAcceptCharset(accept) { + return accept.split(',').map(function(e) { + return parseCharset(e.trim()); + }).filter(function(e) { + return e; + }); +} + +function parseCharset(s) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q + }; +} + +function getCharsetPriority(charset, accepted) { + return (accepted.map(function(a) { + return specify(charset, a); + }).filter(Boolean).sort(function (a, b) { + if(a.s == b.s) { + return a.q > b.q ? -1 : 1; + } else { + return a.s > b.s ? -1 : 1; + } + })[0] || {s: 0, q:0}); +} + +function specify(charset, spec) { + var s = 0; + if(spec.charset === charset){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + s: s, + q: spec.q, + } +} + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + accept = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + if (provided) { + return provided.map(function(type) { + return [type, getCharsetPriority(type, accept)]; + }).filter(function(pair) { + return pair[1].q > 0; + }).sort(function(a, b) { + var pa = a[1]; + var pb = b[1]; + if(pa.q == pb.q) { + return pa.s < pb.s ? 1 : -1; + } else { + return pa.q < pb.q ? 1 : -1; + } + }).map(function(pair) { + return pair[0]; + }); + } else { + return accept.sort(function (a, b) { + // revsort + return a.q < b.q ? 1 : -1; + }).filter(function(type) { + return type.q > 0; + }).map(function(type) { + return type.charset; + }); + } +} diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js new file mode 100644 index 000000000..207291d02 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,120 @@ +module.exports = preferredEncodings; +preferredEncodings.preferredEncodings = preferredEncodings; + +function parseAcceptEncoding(accept) { + var acceptableEncodings; + + if (accept) { + acceptableEncodings = accept.split(',').map(function(e) { + return parseEncoding(e.trim()); + }); + } else { + acceptableEncodings = []; + } + + if (!acceptableEncodings.some(function(e) { + return e && specify('identity', e); + })) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + * + */ + var lowestQ = 1; + + for(var i = 0; i < acceptableEncodings.length; i++){ + var e = acceptableEncodings[i]; + if(e && e.q < lowestQ){ + lowestQ = e.q; + } + } + acceptableEncodings.push({ + encoding: 'identity', + q: lowestQ / 2, + }); + } + + return acceptableEncodings.filter(function(e) { + return e; + }); +} + +function parseEncoding(s) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q + }; +} + +function getEncodingPriority(encoding, accepted) { + return (accepted.map(function(a) { + return specify(encoding, a); + }).filter(Boolean).sort(function (a, b) { + if(a.s == b.s) { + return a.q > b.q ? -1 : 1; + } else { + return a.s > b.s ? -1 : 1; + } + })[0] || {s: 0, q: 0}); +} + +function specify(encoding, spec) { + var s = 0; + if(spec.encoding === encoding){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + s: s, + q: spec.q, + } +}; + +function preferredEncodings(accept, provided) { + accept = parseAcceptEncoding(accept || ''); + if (provided) { + return provided.map(function(type) { + return [type, getEncodingPriority(type, accept)]; + }).filter(function(pair) { + return pair[1].q > 0; + }).sort(function(a, b) { + var pa = a[1]; + var pb = b[1]; + if(pa.q == pb.q) { + return pa.s < pb.s ? 1 : -1; + } else { + return pa.q < pb.q ? 1 : -1; + } + }).map(function(pair) { + return pair[0]; + }); + } else { + return accept.sort(function (a, b) { + // revsort + return a.q < b.q ? 1 : -1; + }).filter(function(type){ + return type.q > 0; + }).map(function(type) { + return type.encoding; + }); + } +} diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js new file mode 100644 index 000000000..63036c724 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -0,0 +1,103 @@ +module.exports = preferredLanguages; +preferredLanguages.preferredLanguages = preferredLanguages; + +function parseAcceptLanguage(accept) { + return accept.split(',').map(function(e) { + return parseLanguage(e.trim()); + }).filter(function(e) { + return e; + }); +} + +function parseLanguage(s) { + var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + full: full + }; +} + +function getLanguagePriority(language, accepted) { + return (accepted.map(function(a){ + return specify(language, a); + }).filter(Boolean).sort(function (a, b) { + if(a.s == b.s) { + return a.q > b.q ? -1 : 1; + } else { + return a.s > b.s ? -1 : 1; + } + })[0] || {s: 0, q: 0}); +} + +function specify(language, spec) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full === p.full){ + s |= 4; + } else if (spec.prefix === p.full) { + s |= 2; + } else if (spec.full === p.prefix) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + s: s, + q: spec.q, + } +}; + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + accept = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + if (provided) { + + var ret = provided.map(function(type) { + return [type, getLanguagePriority(type, accept)]; + }).filter(function(pair) { + return pair[1].q > 0; + }).sort(function(a, b) { + var pa = a[1]; + var pb = b[1]; + if(pa.q == pb.q) { + return pa.s < pb.s ? 1 : -1; + } else { + return pa.q < pb.q ? 1 : -1; + } + }).map(function(pair) { + return pair[0]; + }); + return ret; + + } else { + return accept.sort(function (a, b) { + // revsort + return a.q < b.q ? 1 : -1; + }).filter(function(type) { + return type.q > 0; + }).map(function(type) { + return type.full; + }); + } +} diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 000000000..f4dc1caf2 --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,125 @@ +module.exports = preferredMediaTypes; +preferredMediaTypes.preferredMediaTypes = preferredMediaTypes; + +function parseAccept(accept) { + return accept.split(',').map(function(e) { + return parseMediaType(e.trim()); + }).filter(function(e) { + return e; + }); +}; + +function parseMediaType(s) { + var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/); + if (!match) return null; + + var type = match[1], + subtype = match[2], + full = "" + type + "/" + subtype, + params = {}, + q = 1; + + if (match[3]) { + params = match[3].split(';').map(function(s) { + return s.trim().split('='); + }).reduce(function (set, p) { + set[p[0]] = p[1]; + return set + }, params); + + if (params.q != null) { + q = parseFloat(params.q); + delete params.q; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + full: full + }; +} + +function getMediaTypePriority(type, accepted) { + return (accepted.map(function(a) { + return specify(type, a); + }).filter(Boolean).sort(function (a, b) { + if(a.s == b.s) { + return a.q > b.q ? -1 : 1; + } else { + return a.s > b.s ? -1 : 1; + } + })[0] || {s: 0, q: 0}); +} + +function specify(type, spec) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type == p.type) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype == p.subtype) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || spec.params[k] == p.params[k]; + })) { + s |= 1 + } else { + return null + } + } + + return { + q: spec.q, + s: s, + } + +} + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + accept = parseAccept(accept === undefined ? '*/*' : accept || ''); + if (provided) { + return provided.map(function(type) { + return [type, getMediaTypePriority(type, accept)]; + }).filter(function(pair) { + return pair[1].q > 0; + }).sort(function(a, b) { + var pa = a[1]; + var pb = b[1]; + if(pa.q == pb.q) { + return pa.s < pb.s ? 1 : -1; + } else { + return pa.q < pb.q ? 1 : -1; + } + }).map(function(pair) { + return pair[0]; + }); + + } else { + return accept.sort(function (a, b) { + // revsort + return a.q < b.q ? 1 : -1; + }).filter(function(type) { + return type.q > 0; + }).map(function(type) { + return type.full; + }); + } +} diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js new file mode 100644 index 000000000..ba0c48b9d --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js @@ -0,0 +1,37 @@ +module.exports = Negotiator; +Negotiator.Negotiator = Negotiator; + +function Negotiator(request) { + if (!(this instanceof Negotiator)) return new Negotiator(request); + this.request = request; +} + +var set = { charset: 'accept-charset', + encoding: 'accept-encoding', + language: 'accept-language', + mediaType: 'accept' }; + + +function capitalize(string){ + return string.charAt(0).toUpperCase() + string.slice(1); +} + +Object.keys(set).forEach(function (k) { + var header = set[k], + method = require('./'+k+'.js'), + singular = k, + plural = k + 's'; + + Negotiator.prototype[plural] = function (available) { + return method(this.request.headers[header], available); + }; + + Negotiator.prototype[singular] = function(available) { + var set = this[plural](available); + if (set) return set[0]; + }; + + // Keep preferred* methods for legacy compatibility + Negotiator.prototype['preferred'+capitalize(plural)] = Negotiator.prototype[plural]; + Negotiator.prototype['preferred'+capitalize(singular)] = Negotiator.prototype[singular]; +}) diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json new file mode 100644 index 000000000..da0eb90be --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -0,0 +1,50 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "0.4.7", + "author": { + "name": "Federico Romero", + "email": "federico.romero@outboxlabs.com" + }, + "contributors": [ + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + } + ], + "repository": { + "type": "git", + "url": "git://github.com/federomero/negotiator.git" + }, + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "engine": "node >= 0.6", + "license": "MIT", + "devDependencies": { + "nodeunit": "0.8.x" + }, + "scripts": { + "test": "nodeunit test" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "main": "lib/negotiator.js", + "readme": "# Negotiator [![Build Status](https://travis-ci.org/federomero/negotiator.png)](https://travis-ci.org/federomero/negotiator)\n\nAn HTTP content negotiator for node.js written in javascript.\n\n# Accept Negotiation\n\n Negotiator = require('negotiator')\n\n availableMediaTypes = ['text/html', 'text/plain', 'application/json']\n\n // The negotiator constructor receives a request object\n negotiator = new Negotiator(request)\n\n // Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8'\n\n negotiator.mediaTypes()\n // -> ['text/html', 'image/jpeg', 'application/*']\n\n negotiator.mediaTypes(availableMediaTypes)\n // -> ['text/html', 'application/json']\n\n negotiator.mediaType(availableMediaTypes)\n // -> 'text/html'\n\nYou can check a working example at `examples/accept.js`.\n\n## Methods\n\n`mediaTypes(availableMediaTypes)`:\n\nReturns an array of preferred media types ordered by priority from a list of available media types.\n\n`mediaType(availableMediaType)`:\n\nReturns the top preferred media type from a list of available media types.\n\n# Accept-Language Negotiation\n\n Negotiator = require('negotiator')\n\n negotiator = new Negotiator(request)\n\n availableLanguages = 'en', 'es', 'fr'\n\n // Let's say Accept-Language header is 'en;q=0.8, es, pt'\n\n negotiator.languages()\n // -> ['es', 'pt', 'en']\n\n negotiator.languages(availableLanguages)\n // -> ['es', 'en']\n\n language = negotiator.language(availableLanguages)\n // -> 'es'\n\nYou can check a working example at `examples/language.js`.\n\n## Methods\n\n`languages(availableLanguages)`:\n\nReturns an array of preferred languages ordered by priority from a list of available languages.\n\n`language(availableLanguages)`:\n\nReturns the top preferred language from a list of available languages.\n\n# Accept-Charset Negotiation\n\n Negotiator = require('negotiator')\n\n availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5']\n\n negotiator = new Negotiator(request)\n\n // Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2'\n\n negotiator.charsets()\n // -> ['utf-8', 'iso-8859-1', 'utf-7']\n\n negotiator.charsets(availableCharsets)\n // -> ['utf-8', 'iso-8859-1']\n\n negotiator.charset(availableCharsets)\n // -> 'utf-8'\n\nYou can check a working example at `examples/charset.js`.\n\n## Methods\n\n`charsets(availableCharsets)`:\n\nReturns an array of preferred charsets ordered by priority from a list of available charsets.\n\n`charset(availableCharsets)`:\n\nReturns the top preferred charset from a list of available charsets.\n\n# Accept-Encoding Negotiation\n\n Negotiator = require('negotiator').Negotiator\n\n availableEncodings = ['identity', 'gzip']\n\n negotiator = new Negotiator(request)\n\n // Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5'\n\n negotiator.encodings()\n // -> ['gzip', 'identity', 'compress']\n\n negotiator.encodings(availableEncodings)\n // -> ['gzip', 'identity']\n\n negotiator.encoding(availableEncodings)\n // -> 'gzip'\n\nYou can check a working example at `examples/encoding.js`.\n\n## Methods\n\n`encodings(availableEncodings)`:\n\nReturns an array of preferred encodings ordered by priority from a list of available encodings.\n\n`encoding(availableEncodings)`:\n\nReturns the top preferred encoding from a list of available encodings.\n\n# License\n\nMIT\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/federomero/negotiator/issues" + }, + "homepage": "https://github.com/federomero/negotiator", + "dependencies": {}, + "_id": "negotiator@0.4.7", + "_from": "negotiator@~0.4.0" +} diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/readme.md b/node_modules/express/node_modules/accepts/node_modules/negotiator/readme.md new file mode 100644 index 000000000..d982a9c1f --- /dev/null +++ b/node_modules/express/node_modules/accepts/node_modules/negotiator/readme.md @@ -0,0 +1,132 @@ +# Negotiator [![Build Status](https://travis-ci.org/federomero/negotiator.png)](https://travis-ci.org/federomero/negotiator) + +An HTTP content negotiator for node.js written in javascript. + +# Accept Negotiation + + Negotiator = require('negotiator') + + availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + + // The negotiator constructor receives a request object + negotiator = new Negotiator(request) + + // Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + + negotiator.mediaTypes() + // -> ['text/html', 'image/jpeg', 'application/*'] + + negotiator.mediaTypes(availableMediaTypes) + // -> ['text/html', 'application/json'] + + negotiator.mediaType(availableMediaTypes) + // -> 'text/html' + +You can check a working example at `examples/accept.js`. + +## Methods + +`mediaTypes(availableMediaTypes)`: + +Returns an array of preferred media types ordered by priority from a list of available media types. + +`mediaType(availableMediaType)`: + +Returns the top preferred media type from a list of available media types. + +# Accept-Language Negotiation + + Negotiator = require('negotiator') + + negotiator = new Negotiator(request) + + availableLanguages = 'en', 'es', 'fr' + + // Let's say Accept-Language header is 'en;q=0.8, es, pt' + + negotiator.languages() + // -> ['es', 'pt', 'en'] + + negotiator.languages(availableLanguages) + // -> ['es', 'en'] + + language = negotiator.language(availableLanguages) + // -> 'es' + +You can check a working example at `examples/language.js`. + +## Methods + +`languages(availableLanguages)`: + +Returns an array of preferred languages ordered by priority from a list of available languages. + +`language(availableLanguages)`: + +Returns the top preferred language from a list of available languages. + +# Accept-Charset Negotiation + + Negotiator = require('negotiator') + + availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + + negotiator = new Negotiator(request) + + // Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + + negotiator.charsets() + // -> ['utf-8', 'iso-8859-1', 'utf-7'] + + negotiator.charsets(availableCharsets) + // -> ['utf-8', 'iso-8859-1'] + + negotiator.charset(availableCharsets) + // -> 'utf-8' + +You can check a working example at `examples/charset.js`. + +## Methods + +`charsets(availableCharsets)`: + +Returns an array of preferred charsets ordered by priority from a list of available charsets. + +`charset(availableCharsets)`: + +Returns the top preferred charset from a list of available charsets. + +# Accept-Encoding Negotiation + + Negotiator = require('negotiator').Negotiator + + availableEncodings = ['identity', 'gzip'] + + negotiator = new Negotiator(request) + + // Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + + negotiator.encodings() + // -> ['gzip', 'identity', 'compress'] + + negotiator.encodings(availableEncodings) + // -> ['gzip', 'identity'] + + negotiator.encoding(availableEncodings) + // -> 'gzip' + +You can check a working example at `examples/encoding.js`. + +## Methods + +`encodings(availableEncodings)`: + +Returns an array of preferred encodings ordered by priority from a list of available encodings. + +`encoding(availableEncodings)`: + +Returns the top preferred encoding from a list of available encodings. + +# License + +MIT diff --git a/node_modules/express/node_modules/accepts/package.json b/node_modules/express/node_modules/accepts/package.json new file mode 100644 index 000000000..36125f25d --- /dev/null +++ b/node_modules/express/node_modules/accepts/package.json @@ -0,0 +1,52 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/accepts.git" + }, + "bugs": { + "url": "https://github.com/expressjs/accepts/issues" + }, + "dependencies": { + "mime": "~1.2.11", + "negotiator": "~0.4.0" + }, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "make test" + }, + "homepage": "https://github.com/expressjs/accepts", + "_id": "accepts@1.0.1", + "dist": { + "shasum": "c1e06d613e6246ba874678d6d9b92389b7ce310c", + "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.0.1.tgz" + }, + "_from": "accepts@1.0.1", + "_npmVersion": "1.3.23", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "directories": {}, + "_shasum": "c1e06d613e6246ba874678d6d9b92389b7ce310c", + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.1.tgz", + "readme": "# Accepts [![Build Status](https://travis-ci.org/expressjs/accepts.png)](https://travis-ci.org/expressjs/accepts)\n\nHigher level content negotation based on [negotiator](https://github.com/federomero/negotiator). Extracted from [koa](https://github.com/koajs/koa) for general use.\n\nIn addition to negotatior, it allows:\n\n- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.\n- Allows type shorthands such as `json`.\n- Returns `false` when no types match\n- Treats non-existent headers as `*`\n\n## API\n\n### var accept = new Accepts(req)\n\n```js\nvar accepts = require('accepts')\n\nhttp.createServer(function (req, res) {\n var accept = accepts(req)\n})\n```\n\n### accept\\[property\\]\\(\\)\n\nReturns all the explicitly accepted content property as an array in descending priority.\n\n- `accept.types()`\n- `accept.encodings()`\n- `accept.charsets()`\n- `accept.languages()`\n\nThey are also aliased in singular form such as `accept.type()`. `accept.languages()` is also aliased as `accept.langs()`, etc.\n\nNote: you should almost never do this in a real app as it defeats the purpose of content negotiation.\n\nExample:\n\n```js\n// in Google Chrome\nvar encodings = accept.encodings() // -> ['sdch', 'gzip', 'deflate']\n```\n\nSince you probably don't support `sdch`, you should just supply the encodings you support:\n\n```js\nvar encoding = accept.encodings('gzip', 'deflate') // -> 'gzip', probably\n```\n\n### accept\\[property\\]\\(values, ...\\)\n\nYou can either have `values` be an array or have an argument list of values.\n\nIf the client does not accept any `values`, `false` will be returned.\nIf the client accepts any `values`, the preferred `value` will be return.\n\nFor `accept.types()`, shorthand mime types are allowed.\n\nExample:\n\n```js\n// req.headers.accept = 'application/json'\n\naccept.types('json') // -> 'json'\naccept.types('html', 'json') // -> 'json'\naccept.types('html') // -> false\n\n// req.headers.accept = ''\n// which is equivalent to `*`\n\naccept.types() // -> [], no explicit types\naccept.types('text/html', 'text/json') // -> 'text/html', since it was first\n```\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.", + "readmeFilename": "README.md" +} diff --git a/node_modules/express/node_modules/buffer-crc32/.npmignore b/node_modules/express/node_modules/buffer-crc32/.npmignore new file mode 100644 index 000000000..b512c09d4 --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/.npmignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/.travis.yml b/node_modules/express/node_modules/buffer-crc32/.travis.yml new file mode 100644 index 000000000..7a902e8c8 --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - 0.6 + - 0.8 +notifications: + email: + recipients: + - brianloveswords@gmail.com \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/README.md b/node_modules/express/node_modules/buffer-crc32/README.md new file mode 100644 index 000000000..0d9d8b835 --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/README.md @@ -0,0 +1,47 @@ +# buffer-crc32 + +[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32) + +crc32 that works with binary data and fancy character sets, outputs +buffer, signed or unsigned data and has tests. + +Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix + +# install +``` +npm install buffer-crc32 +``` + +# example +```js +var crc32 = require('buffer-crc32'); +// works with buffers +var buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]) +crc32(buf) // -> + +// has convenience methods for getting signed or unsigned ints +crc32.signed(buf) // -> -1805997238 +crc32.unsigned(buf) // -> 2488970058 + +// will cast to buffer if given a string, so you can +// directly use foreign characters safely +crc32('自動販売機') // -> + +// and works in append mode too +var partialCrc = crc32('hey'); +var partialCrc = crc32(' ', partialCrc); +var partialCrc = crc32('sup', partialCrc); +var partialCrc = crc32(' ', partialCrc); +var finalCrc = crc32('bros', partialCrc); // -> +``` + +# tests +This was tested against the output of zlib's crc32 method. You can run +the tests with`npm test` (requires tap) + +# see also +https://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also +supports buffer inputs and return unsigned ints (thanks @tjholowaychuk). + +# license +MIT/X11 diff --git a/node_modules/express/node_modules/buffer-crc32/index.js b/node_modules/express/node_modules/buffer-crc32/index.js new file mode 100644 index 000000000..e29ce3ebc --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/index.js @@ -0,0 +1,88 @@ +var Buffer = require('buffer').Buffer; + +var CRC_TABLE = [ + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, + 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, + 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, + 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, + 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, + 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, + 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, + 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, + 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, + 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, + 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, + 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, + 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, + 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, + 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, + 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, + 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, + 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, + 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, + 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, + 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, + 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, + 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, + 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, + 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, + 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, + 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, + 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, + 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, + 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, + 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, + 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, + 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, + 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, + 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, + 0x2d02ef8d +]; + +function bufferizeInt(num) { + var tmp = Buffer(4); + tmp.writeInt32BE(num, 0); + return tmp; +} + +function _crc32(buf, previous) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer(buf); + } + if (Buffer.isBuffer(previous)) { + previous = previous.readUInt32BE(0); + } + var crc = ~~previous ^ -1; + for (var n = 0; n < buf.length; n++) { + crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ -1); +} + +function crc32() { + return bufferizeInt(_crc32.apply(null, arguments)); +} +crc32.signed = function () { + return _crc32.apply(null, arguments); +}; +crc32.unsigned = function () { + return _crc32.apply(null, arguments) >>> 0; +}; + +module.exports = crc32; diff --git a/node_modules/express/node_modules/buffer-crc32/package.json b/node_modules/express/node_modules/buffer-crc32/package.json new file mode 100644 index 000000000..c57c6fde3 --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/package.json @@ -0,0 +1,57 @@ +{ + "author": { + "name": "Brian J. Brennan", + "email": "brianloveswords@gmail.com", + "url": "http://bjb.io" + }, + "name": "buffer-crc32", + "description": "A pure javascript CRC32 algorithm that plays nice with binary data", + "version": "0.2.1", + "contributors": [ + { + "name": "Vladimir Kuznetsov" + } + ], + "homepage": "https://github.com/brianloveswords/buffer-crc32", + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/buffer-crc32.git" + }, + "main": "index.js", + "scripts": { + "test": "tap tests/*.test.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "~0.2.5" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "_id": "buffer-crc32@0.2.1", + "dist": { + "shasum": "be3e5382fc02b6d6324956ac1af98aa98b08534c", + "tarball": "http://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.1.tgz" + }, + "_npmVersion": "1.1.65", + "_npmUser": { + "name": "brianloveswords", + "email": "brian@nyhacker.org" + }, + "maintainers": [ + { + "name": "brianloveswords", + "email": "brian@nyhacker.org" + } + ], + "directories": {}, + "_shasum": "be3e5382fc02b6d6324956ac1af98aa98b08534c", + "_from": "buffer-crc32@0.2.1", + "_resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.1.tgz", + "readme": "# buffer-crc32\n\n[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)\n\ncrc32 that works with binary data and fancy character sets, outputs\nbuffer, signed or unsigned data and has tests.\n\nDerived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix\n\n# install\n```\nnpm install buffer-crc32\n```\n\n# example\n```js\nvar crc32 = require('buffer-crc32');\n// works with buffers\nvar buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])\ncrc32(buf) // -> \n\n// has convenience methods for getting signed or unsigned ints\ncrc32.signed(buf) // -> -1805997238\ncrc32.unsigned(buf) // -> 2488970058\n\n// will cast to buffer if given a string, so you can\n// directly use foreign characters safely\ncrc32('自動販売機') // -> \n\n// and works in append mode too\nvar partialCrc = crc32('hey');\nvar partialCrc = crc32(' ', partialCrc);\nvar partialCrc = crc32('sup', partialCrc);\nvar partialCrc = crc32(' ', partialCrc);\nvar finalCrc = crc32('bros', partialCrc); // -> \n```\n\n# tests\nThis was tested against the output of zlib's crc32 method. You can run\nthe tests with`npm test` (requires tap)\n\n# see also\nhttps://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also\nsupports buffer inputs and return unsigned ints (thanks @tjholowaychuk).\n\n# license\nMIT/X11\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/brianloveswords/buffer-crc32/issues" + } +} diff --git a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js b/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js new file mode 100644 index 000000000..bb0f9efcc --- /dev/null +++ b/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js @@ -0,0 +1,89 @@ +var crc32 = require('..'); +var test = require('tap').test; + +test('simple crc32 is no problem', function (t) { + var input = Buffer('hey sup bros'); + var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); + t.same(crc32(input), expected); + t.end(); +}); + +test('another simple one', function (t) { + var input = Buffer('IEND'); + var expected = Buffer([0xae, 0x42, 0x60, 0x82]); + t.same(crc32(input), expected); + t.end(); +}); + +test('slightly more complex', function (t) { + var input = Buffer([0x00, 0x00, 0x00]); + var expected = Buffer([0xff, 0x41, 0xd9, 0x12]); + t.same(crc32(input), expected); + t.end(); +}); + +test('complex crc32 gets calculated like a champ', function (t) { + var input = Buffer('शीर्षक'); + var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); + t.same(crc32(input), expected); + t.end(); +}); + +test('casts to buffer if necessary', function (t) { + var input = 'शीर्षक'; + var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); + t.same(crc32(input), expected); + t.end(); +}); + +test('can do signed', function (t) { + var input = 'ham sandwich'; + var expected = -1891873021; + t.same(crc32.signed(input), expected); + t.end(); +}); + +test('can do unsigned', function (t) { + var input = 'bear sandwich'; + var expected = 3711466352; + t.same(crc32.unsigned(input), expected); + t.end(); +}); + + +test('simple crc32 in append mode', function (t) { + var input = [Buffer('hey'), Buffer(' '), Buffer('sup'), Buffer(' '), Buffer('bros')]; + var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); + for (var crc = 0, i = 0; i < input.length; i++) { + crc = crc32(input[i], crc); + } + t.same(crc, expected); + t.end(); +}); + + +test('can do signed in append mode', function (t) { + var input1 = 'ham'; + var input2 = ' '; + var input3 = 'sandwich'; + var expected = -1891873021; + + var crc = crc32.signed(input1); + crc = crc32.signed(input2, crc); + crc = crc32.signed(input3, crc); + + t.same(crc, expected); + t.end(); +}); + +test('can do unsigned in append mode', function (t) { + var input1 = 'bear san'; + var input2 = 'dwich'; + var expected = 3711466352; + + var crc = crc32.unsigned(input1); + crc = crc32.unsigned(input2, crc); + t.same(crc, expected); + t.end(); +}); + diff --git a/node_modules/express/node_modules/cookie-signature/.npmignore b/node_modules/express/node_modules/cookie-signature/.npmignore new file mode 100644 index 000000000..f1250e584 --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/express/node_modules/cookie-signature/History.md b/node_modules/express/node_modules/cookie-signature/History.md new file mode 100644 index 000000000..7aacdf0c0 --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/History.md @@ -0,0 +1,21 @@ +1.0.3 / 2014-01-28 +================== + + * fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/node_modules/cookie-signature/Makefile b/node_modules/express/node_modules/cookie-signature/Makefile new file mode 100644 index 000000000..4e9c8d36e --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/cookie-signature/Readme.md b/node_modules/express/node_modules/cookie-signature/Readme.md new file mode 100644 index 000000000..2559e841b --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/cookie-signature/index.js b/node_modules/express/node_modules/cookie-signature/index.js new file mode 100644 index 000000000..32419feae --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/index.js @@ -0,0 +1,43 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError('cookie required'); + if ('string' != typeof secret) throw new TypeError('secret required'); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError('cookie required'); + if ('string' != typeof secret) throw new TypeError('secret required'); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return exports.sign(mac, secret) == exports.sign(val, secret) ? str : false; +}; diff --git a/node_modules/express/node_modules/cookie-signature/package.json b/node_modules/express/node_modules/cookie-signature/package.json new file mode 100644 index 000000000..8e3731bb7 --- /dev/null +++ b/node_modules/express/node_modules/cookie-signature/package.json @@ -0,0 +1,50 @@ +{ + "name": "cookie-signature", + "version": "1.0.3", + "description": "Sign and unsign cookies", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "main": "index", + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature", + "_id": "cookie-signature@1.0.3", + "dist": { + "shasum": "91cd997cc51fb641595738c69cda020328f50ff9", + "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.3.tgz" + }, + "_from": "cookie-signature@1.0.3", + "_npmVersion": "1.3.15", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "91cd997cc51fb641595738c69cda020328f50ff9", + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.3.tgz", + "readme": "\n# cookie-signature\n\n Sign and unsign cookies.\n\n## Example\n\n```js\nvar cookie = require('cookie-signature');\n\nvar val = cookie.sign('hello', 'tobiiscool');\nval.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');\n\nvar val = cookie.sign('hello', 'tobiiscool');\ncookie.unsign(val, 'tobiiscool').should.equal('hello');\ncookie.unsign(val, 'luna').should.be.false;\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 LearnBoost <tj@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md" +} diff --git a/node_modules/express/node_modules/cookie/.npmignore b/node_modules/express/node_modules/cookie/.npmignore new file mode 100644 index 000000000..efab07fb1 --- /dev/null +++ b/node_modules/express/node_modules/cookie/.npmignore @@ -0,0 +1,2 @@ +test +.travis.yml diff --git a/node_modules/express/node_modules/cookie/LICENSE b/node_modules/express/node_modules/cookie/LICENSE new file mode 100644 index 000000000..249d9def9 --- /dev/null +++ b/node_modules/express/node_modules/cookie/LICENSE @@ -0,0 +1,9 @@ +// MIT License + +Copyright (C) Roman Shtylman + +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/express/node_modules/cookie/README.md b/node_modules/express/node_modules/cookie/README.md new file mode 100644 index 000000000..3170b4b87 --- /dev/null +++ b/node_modules/express/node_modules/cookie/README.md @@ -0,0 +1,44 @@ +# cookie [![Build Status](https://secure.travis-ci.org/defunctzombie/node-cookie.png?branch=master)](http://travis-ci.org/defunctzombie/node-cookie) # + +cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. + +See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. + +## how? + +``` +npm install cookie +``` + +```javascript +var cookie = require('cookie'); + +var hdr = cookie.serialize('foo', 'bar'); +// hdr = 'foo=bar'; + +var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); +// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; +``` + +## more + +The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. + +### path +> cookie path + +### expires +> absolute expiration date for the cookie (Date object) + +### maxAge +> relative max age of the cookie from when the client receives it (seconds) + +### domain +> domain for the cookie + +### secure +> true or false + +### httpOnly +> true or false + diff --git a/node_modules/express/node_modules/cookie/index.js b/node_modules/express/node_modules/cookie/index.js new file mode 100644 index 000000000..00d54a7b6 --- /dev/null +++ b/node_modules/express/node_modules/cookie/index.js @@ -0,0 +1,75 @@ + +/// Serialize the a name value pair into a cookie string suitable for +/// http headers. An optional options object specified cookie parameters +/// +/// serialize('foo', 'bar', { httpOnly: true }) +/// => "foo=bar; httpOnly" +/// +/// @param {String} name +/// @param {String} val +/// @param {Object} options +/// @return {String} +var serialize = function(name, val, opt){ + opt = opt || {}; + var enc = opt.encode || encode; + var pairs = [name + '=' + enc(val)]; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + pairs.push('Max-Age=' + maxAge); + } + + if (opt.domain) pairs.push('Domain=' + opt.domain); + if (opt.path) pairs.push('Path=' + opt.path); + if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); + if (opt.httpOnly) pairs.push('HttpOnly'); + if (opt.secure) pairs.push('Secure'); + + return pairs.join('; '); +}; + +/// Parse the given cookie header string into an object +/// The object has the various cookies as keys(names) => values +/// @param {String} str +/// @return {Object} +var parse = function(str, opt) { + opt = opt || {}; + var obj = {} + var pairs = str.split(/; */); + var dec = opt.decode || decode; + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('=') + + // skip things that don't look like key=value + if (eq_idx < 0) { + return; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + try { + obj[key] = dec(val); + } catch (e) { + obj[key] = val; + } + } + }); + + return obj; +}; + +var encode = encodeURIComponent; +var decode = decodeURIComponent; + +module.exports.serialize = serialize; +module.exports.parse = parse; diff --git a/node_modules/express/node_modules/cookie/package.json b/node_modules/express/node_modules/cookie/package.json new file mode 100644 index 000000000..35c0e189d --- /dev/null +++ b/node_modules/express/node_modules/cookie/package.json @@ -0,0 +1,55 @@ +{ + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "name": "cookie", + "description": "cookie parsing and serialization", + "version": "0.1.2", + "repository": { + "type": "git", + "url": "git://github.com/shtylman/node-cookie.git" + }, + "keywords": [ + "cookie", + "cookies" + ], + "main": "index.js", + "scripts": { + "test": "mocha" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "bugs": { + "url": "https://github.com/shtylman/node-cookie/issues" + }, + "homepage": "https://github.com/shtylman/node-cookie", + "_id": "cookie@0.1.2", + "dist": { + "shasum": "72fec3d24e48a3432073d90c12642005061004b1", + "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz" + }, + "_from": "cookie@0.1.2", + "_npmVersion": "1.4.6", + "_npmUser": { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + "maintainers": [ + { + "name": "shtylman", + "email": "shtylman@gmail.com" + } + ], + "directories": {}, + "_shasum": "72fec3d24e48a3432073d90c12642005061004b1", + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz", + "readme": "# cookie [![Build Status](https://secure.travis-ci.org/defunctzombie/node-cookie.png?branch=master)](http://travis-ci.org/defunctzombie/node-cookie) #\n\ncookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers.\n\nSee [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies.\n\n## how?\n\n```\nnpm install cookie\n```\n\n```javascript\nvar cookie = require('cookie');\n\nvar hdr = cookie.serialize('foo', 'bar');\n// hdr = 'foo=bar';\n\nvar cookies = cookie.parse('foo=bar; cat=meow; dog=ruff');\n// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' };\n```\n\n## more\n\nThe serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values.\n\n### path\n> cookie path\n\n### expires\n> absolute expiration date for the cookie (Date object)\n\n### maxAge\n> relative max age of the cookie from when the client receives it (seconds)\n\n### domain\n> domain for the cookie\n\n### secure\n> true or false\n\n### httpOnly\n> true or false\n\n", + "readmeFilename": "README.md" +} diff --git a/node_modules/express/node_modules/debug/Readme.md b/node_modules/express/node_modules/debug/Readme.md new file mode 100644 index 000000000..8981f8abe --- /dev/null +++ b/node_modules/express/node_modules/debug/Readme.md @@ -0,0 +1,114 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +``` +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + a('doing some work'); +}, 1200); +``` + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +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/express/node_modules/debug/debug.js b/node_modules/express/node_modules/debug/debug.js new file mode 100644 index 000000000..509dc0ded --- /dev/null +++ b/node_modules/express/node_modules/debug/debug.js @@ -0,0 +1,137 @@ + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + if (!debug.enabled(name)) return function(){}; + + return function(fmt){ + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (debug[name] || curr); + debug[name] = curr; + + fmt = name + + ' ' + + fmt + + ' +' + debug.humanize(ms); + + // This hackery is required for IE8 + // where `console.log` doesn't have 'apply' + window.console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); + } +} + +/** + * The currently active debug mode names. + */ + +debug.names = []; +debug.skips = []; + +/** + * Enables a debug mode by name. This can include modes + * separated by a colon and wildcards. + * + * @param {String} name + * @api public + */ + +debug.enable = function(name) { + try { + localStorage.debug = name; + } catch(e){} + + var split = (name || '').split(/[\s,]+/) + , len = split.length; + + for (var i = 0; i < len; i++) { + name = split[i].replace('*', '.*?'); + if (name[0] === '-') { + debug.skips.push(new RegExp('^' + name.substr(1) + '$')); + } + else { + debug.names.push(new RegExp('^' + name + '$')); + } + } +}; + +/** + * Disable debug output. + * + * @api public + */ + +debug.disable = function(){ + debug.enable(''); +}; + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +debug.humanize = function(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +}; + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +debug.enabled = function(name) { + for (var i = 0, len = debug.skips.length; i < len; i++) { + if (debug.skips[i].test(name)) { + return false; + } + } + for (var i = 0, len = debug.names.length; i < len; i++) { + if (debug.names[i].test(name)) { + return true; + } + } + return false; +}; + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +// persist + +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){} diff --git a/node_modules/express/node_modules/debug/lib/debug.js b/node_modules/express/node_modules/debug/lib/debug.js new file mode 100644 index 000000000..e7422e68a --- /dev/null +++ b/node_modules/express/node_modules/debug/lib/debug.js @@ -0,0 +1,158 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Enabled debuggers. + */ + +var names = [] + , skips = []; + +/** + * Colors. + */ + +var colors = [6, 2, 3, 4, 5, 1]; + +/** + * Previous debug() call. + */ + +var prev = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Is stdout a TTY? Colored output is disabled when `true`. + */ + +var isatty = tty.isatty(1); + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function color() { + return colors[prevColor++ % colors.length]; +} + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +function humanize(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +} + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + function disabled(){} + disabled.enabled = false; + + var match = skips.some(function(re){ + return re.test(name); + }); + + if (match) return disabled; + + match = names.some(function(re){ + return re.test(name); + }); + + if (!match) return disabled; + var c = color(); + + function colored(fmt) { + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (prev[name] || curr); + prev[name] = curr; + + fmt = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[3' + c + 'm\u001b[90m' + + fmt + '\u001b[3' + c + 'm' + + ' +' + humanize(ms) + '\u001b[0m'; + + console.log.apply(this, arguments); + } + + function plain(fmt) { + fmt = coerce(fmt); + + fmt = new Date().toUTCString() + + ' ' + name + ' ' + fmt; + console.log.apply(this, arguments); + } + + colored.enabled = plain.enabled = true; + + return isatty || process.env.DEBUG_COLORS + ? colored + : plain; +} + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +/** + * Enable specified `namespaces` for debugging. + */ + +debug.enable = function(namespaces) { + namespaces.split(/[\s,]+/) + .forEach(function(name){ + name = name.replace('*', '.*?'); + if (name[0] == '-') { + skips.push(new RegExp('^' + name.substr(1) + '$')); + } else { + names.push(new RegExp('^' + name + '$')); + } + }); +}; + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +debug.enable(process.env.DEBUG || ''); diff --git a/node_modules/express/node_modules/debug/package.json b/node_modules/express/node_modules/debug/package.json new file mode 100644 index 000000000..47a25fca0 --- /dev/null +++ b/node_modules/express/node_modules/debug/package.json @@ -0,0 +1,44 @@ +{ + "name": "debug", + "version": "0.8.1", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*" + }, + "main": "lib/debug.js", + "browser": "./debug.js", + "engines": { + "node": "*" + }, + "files": [ + "lib/debug.js", + "debug.js" + ], + "component": { + "scripts": { + "debug/index.js": "debug.js" + } + }, + "readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n\nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n\n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\".\n\n## Wildcards\n\n The `*` character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.\n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@0.8.1", + "_from": "debug@>= 0.7.3 < 1" +} diff --git a/node_modules/express/node_modules/escape-html/.npmignore b/node_modules/express/node_modules/escape-html/.npmignore new file mode 100644 index 000000000..48a2e246c --- /dev/null +++ b/node_modules/express/node_modules/escape-html/.npmignore @@ -0,0 +1,2 @@ +components +build diff --git a/node_modules/express/node_modules/escape-html/Makefile b/node_modules/express/node_modules/escape-html/Makefile new file mode 100644 index 000000000..3f6119d22 --- /dev/null +++ b/node_modules/express/node_modules/escape-html/Makefile @@ -0,0 +1,11 @@ + +build: components index.js + @component build + +components: + @Component install + +clean: + rm -fr build components template.js + +.PHONY: clean diff --git a/node_modules/express/node_modules/escape-html/Readme.md b/node_modules/express/node_modules/escape-html/Readme.md new file mode 100644 index 000000000..2cfcc9973 --- /dev/null +++ b/node_modules/express/node_modules/escape-html/Readme.md @@ -0,0 +1,15 @@ + +# escape-html + + Escape HTML entities + +## Example + +```js +var escape = require('escape-html'); +escape(str); +``` + +## License + + MIT \ No newline at end of file diff --git a/node_modules/express/node_modules/escape-html/component.json b/node_modules/express/node_modules/escape-html/component.json new file mode 100644 index 000000000..cb9740fd4 --- /dev/null +++ b/node_modules/express/node_modules/escape-html/component.json @@ -0,0 +1,10 @@ +{ + "name": "escape-html", + "description": "Escape HTML entities", + "version": "1.0.1", + "keywords": ["escape", "html", "utility"], + "dependencies": {}, + "scripts": [ + "index.js" + ] +} diff --git a/node_modules/express/node_modules/escape-html/index.js b/node_modules/express/node_modules/escape-html/index.js new file mode 100644 index 000000000..276521145 --- /dev/null +++ b/node_modules/express/node_modules/escape-html/index.js @@ -0,0 +1,16 @@ +/** + * Escape special characters in the given string of html. + * + * @param {String} html + * @return {String} + * @api private + */ + +module.exports = function(html) { + return String(html) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>'); +} diff --git a/node_modules/express/node_modules/escape-html/package.json b/node_modules/express/node_modules/escape-html/package.json new file mode 100644 index 000000000..ee240f053 --- /dev/null +++ b/node_modules/express/node_modules/escape-html/package.json @@ -0,0 +1,47 @@ +{ + "name": "escape-html", + "description": "Escape HTML entities", + "version": "1.0.1", + "keywords": [ + "escape", + "html", + "utility" + ], + "dependencies": {}, + "main": "index.js", + "component": { + "scripts": { + "escape-html/index.js": "index.js" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/component/escape-html.git" + }, + "readme": "\n# escape-html\n\n Escape HTML entities\n\n## Example\n\n```js\nvar escape = require('escape-html');\nescape(str);\n```\n\n## License\n\n MIT", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "homepage": "https://github.com/component/escape-html", + "_id": "escape-html@1.0.1", + "dist": { + "shasum": "181a286ead397a39a92857cfb1d43052e356bff0", + "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" + }, + "_from": "escape-html@1.0.1", + "_npmVersion": "1.3.15", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "181a286ead397a39a92857cfb1d43052e356bff0", + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" +} diff --git a/node_modules/express/node_modules/fresh/.npmignore b/node_modules/express/node_modules/fresh/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/express/node_modules/fresh/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/express/node_modules/fresh/History.md b/node_modules/express/node_modules/fresh/History.md new file mode 100644 index 000000000..12e1b3e2d --- /dev/null +++ b/node_modules/express/node_modules/fresh/History.md @@ -0,0 +1,10 @@ + +0.2.1 / 2014-01-29 +================== + + * fix: support max-age=0 for end-to-end revalidation + +0.2.0 / 2013-08-11 +================== + + * fix: return false for no-cache diff --git a/node_modules/express/node_modules/fresh/Makefile b/node_modules/express/node_modules/fresh/Makefile new file mode 100644 index 000000000..8e8640f2e --- /dev/null +++ b/node_modules/express/node_modules/fresh/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --reporter spec \ + --require should + +.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/Readme.md b/node_modules/express/node_modules/fresh/Readme.md new file mode 100644 index 000000000..61366c577 --- /dev/null +++ b/node_modules/express/node_modules/fresh/Readme.md @@ -0,0 +1,57 @@ + +# node-fresh + + HTTP response freshness testing + +## fresh(req, res) + + Check freshness of `req` and `res` headers. + + When the cache is "fresh" __true__ is returned, + otherwise __false__ is returned to indicate that + the cache is now stale. + +## Example: + +```js +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'luna' }; +fresh(req, res); +// => false + +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'tobi' }; +fresh(req, res); +// => true +``` + +## Installation + +``` +$ npm install fresh +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/index.js b/node_modules/express/node_modules/fresh/index.js new file mode 100644 index 000000000..9c3f47d1e --- /dev/null +++ b/node_modules/express/node_modules/fresh/index.js @@ -0,0 +1,53 @@ + +/** + * Expose `fresh()`. + */ + +module.exports = fresh; + +/** + * Check freshness of `req` and `res` headers. + * + * When the cache is "fresh" __true__ is returned, + * otherwise __false__ is returned to indicate that + * the cache is now stale. + * + * @param {Object} req + * @param {Object} res + * @return {Boolean} + * @api public + */ + +function fresh(req, res) { + // defaults + var etagMatches = true; + var notModified = true; + + // fields + var modifiedSince = req['if-modified-since']; + var noneMatch = req['if-none-match']; + var lastModified = res['last-modified']; + var etag = res['etag']; + var cc = req['cache-control']; + + // unconditional request + if (!modifiedSince && !noneMatch) return false; + + // check for no-cache cache request directive + if (cc && cc.indexOf('no-cache') !== -1) return false; + + // parse if-none-match + if (noneMatch) noneMatch = noneMatch.split(/ *, */); + + // if-none-match + if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; + + // if-modified-since + if (modifiedSince) { + modifiedSince = new Date(modifiedSince); + lastModified = new Date(lastModified); + notModified = lastModified <= modifiedSince; + } + + return !! (etagMatches && notModified); +} \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/package.json b/node_modules/express/node_modules/fresh/package.json new file mode 100644 index 000000000..8c92ff33c --- /dev/null +++ b/node_modules/express/node_modules/fresh/package.json @@ -0,0 +1,52 @@ +{ + "name": "fresh", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "HTTP response freshness testing", + "version": "0.2.2", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-fresh.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/visionmedia/node-fresh/blob/master/Readme.md#license" + } + ], + "bugs": { + "url": "https://github.com/visionmedia/node-fresh/issues" + }, + "homepage": "https://github.com/visionmedia/node-fresh", + "_id": "fresh@0.2.2", + "dist": { + "shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz" + }, + "_from": "fresh@0.2.2", + "_npmVersion": "1.3.15", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz", + "readme": "\n# node-fresh\n\n HTTP response freshness testing\n\n## fresh(req, res)\n\n Check freshness of `req` and `res` headers.\n\n When the cache is \"fresh\" __true__ is returned,\n otherwise __false__ is returned to indicate that\n the cache is now stale.\n\n## Example:\n\n```js\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'luna' };\nfresh(req, res);\n// => false\n\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'tobi' };\nfresh(req, res);\n// => true\n```\n\n## Installation\n\n```\n$ npm install fresh\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md" +} diff --git a/node_modules/express/node_modules/merge-descriptors/.npmignore b/node_modules/express/node_modules/merge-descriptors/.npmignore new file mode 100644 index 000000000..f62e6050c --- /dev/null +++ b/node_modules/express/node_modules/merge-descriptors/.npmignore @@ -0,0 +1,59 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db + +# Node.js # +########### +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log + +# Components # +############## + +/build +/components +/vendors \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/README.md b/node_modules/express/node_modules/merge-descriptors/README.md new file mode 100644 index 000000000..50cf50c03 --- /dev/null +++ b/node_modules/express/node_modules/merge-descriptors/README.md @@ -0,0 +1,49 @@ +# Merge Descriptors [![Build Status](https://travis-ci.org/component/merge-descriptors.png)](https://travis-ci.org/component/merge-descriptors) + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +Overwrites `destination`'s descriptors with `source`'s. + +## License + +The MIT License (MIT) + +Copyright (c) 2013 Jonathan Ong me@jongleberry.com + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/component.json b/node_modules/express/node_modules/merge-descriptors/component.json new file mode 100644 index 000000000..7653906b4 --- /dev/null +++ b/node_modules/express/node_modules/merge-descriptors/component.json @@ -0,0 +1,10 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "0.0.2", + "scripts": [ + "index.js" + ], + "repo": "component/merge-descriptors", + "license": "MIT" +} \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/index.js b/node_modules/express/node_modules/merge-descriptors/index.js new file mode 100644 index 000000000..e4e23793c --- /dev/null +++ b/node_modules/express/node_modules/merge-descriptors/index.js @@ -0,0 +1,8 @@ +module.exports = function (dest, src) { + Object.getOwnPropertyNames(src).forEach(function (name) { + var descriptor = Object.getOwnPropertyDescriptor(src, name) + Object.defineProperty(dest, name, descriptor) + }) + + return dest +} \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/package.json b/node_modules/express/node_modules/merge-descriptors/package.json new file mode 100644 index 000000000..df00f17fd --- /dev/null +++ b/node_modules/express/node_modules/merge-descriptors/package.json @@ -0,0 +1,44 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "0.0.2", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/component/merge-descriptors.git" + }, + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "scripts": { + "test": "make test;" + }, + "homepage": "https://github.com/component/merge-descriptors", + "_id": "merge-descriptors@0.0.2", + "dist": { + "shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", + "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz" + }, + "_from": "merge-descriptors@0.0.2", + "_npmVersion": "1.3.17", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "directories": {}, + "_shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", + "readme": "# Merge Descriptors [![Build Status](https://travis-ci.org/component/merge-descriptors.png)](https://travis-ci.org/component/merge-descriptors)\n\nMerge objects using descriptors.\n\n```js\nvar thing = {\n get name() {\n return 'jon'\n }\n}\n\nvar animal = {\n\n}\n\nmerge(animal, thing)\n\nanimal.name === 'jon'\n```\n\n## API\n\n### merge(destination, source)\n\nOverwrites `destination`'s descriptors with `source`'s.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.", + "readmeFilename": "README.md" +} diff --git a/node_modules/express/node_modules/methods/History.md b/node_modules/express/node_modules/methods/History.md new file mode 100644 index 000000000..1d0e229fd --- /dev/null +++ b/node_modules/express/node_modules/methods/History.md @@ -0,0 +1,5 @@ + +0.1.0 / 2013-10-28 +================== + + * add http.METHODS support diff --git a/node_modules/express/node_modules/methods/Readme.md b/node_modules/express/node_modules/methods/Readme.md new file mode 100644 index 000000000..ac0658e21 --- /dev/null +++ b/node_modules/express/node_modules/methods/Readme.md @@ -0,0 +1,4 @@ + +# Methods + + HTTP verbs that node core's parser supports. diff --git a/node_modules/express/node_modules/methods/index.js b/node_modules/express/node_modules/methods/index.js new file mode 100644 index 000000000..95b93f5fb --- /dev/null +++ b/node_modules/express/node_modules/methods/index.js @@ -0,0 +1,37 @@ + +var http = require('http'); + +if (http.METHODS) { + module.exports = http.METHODS.map(function(method){ + return method.toLowerCase(); + }); + + return; +} + +module.exports = [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search' +]; diff --git a/node_modules/express/node_modules/methods/package.json b/node_modules/express/node_modules/methods/package.json new file mode 100644 index 000000000..aab451885 --- /dev/null +++ b/node_modules/express/node_modules/methods/package.json @@ -0,0 +1,29 @@ +{ + "name": "methods", + "version": "0.1.0", + "description": "HTTP methods that node supports", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "http", + "methods" + ], + "author": { + "name": "TJ Holowaychuk" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-methods.git" + }, + "readme": "\n# Methods\n\n HTTP verbs that node core's parser supports.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/visionmedia/node-methods/issues" + }, + "homepage": "https://github.com/visionmedia/node-methods", + "_id": "methods@0.1.0", + "_from": "methods@0.1.0" +} diff --git a/node_modules/express/node_modules/parseurl/.npmignore b/node_modules/express/node_modules/parseurl/.npmignore new file mode 100644 index 000000000..b906d96aa --- /dev/null +++ b/node_modules/express/node_modules/parseurl/.npmignore @@ -0,0 +1,59 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store* +# Icon? +ehthumbs.db +Thumbs.db + +# Node.js # +########### +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log + +# Components # +############## + +/build +/components +/public \ No newline at end of file diff --git a/node_modules/express/node_modules/parseurl/README.md b/node_modules/express/node_modules/parseurl/README.md new file mode 100644 index 000000000..6d043c994 --- /dev/null +++ b/node_modules/express/node_modules/parseurl/README.md @@ -0,0 +1,34 @@ +# parseurl + +Parse a URL with memoization. + +## API + +### var pathname = parseurl(req) + +`pathname` can then be passed to a router or something. + +## LICENSE + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/parseurl/index.js b/node_modules/express/node_modules/parseurl/index.js new file mode 100644 index 000000000..582c7dee6 --- /dev/null +++ b/node_modules/express/node_modules/parseurl/index.js @@ -0,0 +1,26 @@ + +var parse = require('url').parse; + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api private + */ + +module.exports = function parseUrl(req){ + var parsed = req._parsedUrl; + if (parsed && parsed.href == req.url) { + return parsed; + } else { + parsed = parse(req.url); + + if (parsed.auth && !parsed.protocol && ~parsed.href.indexOf('//')) { + // This parses pathnames, and a strange pathname like //r@e should work + parsed = parse(req.url.replace(/@/g, '%40')); + } + + return req._parsedUrl = parsed; + } +}; diff --git a/node_modules/express/node_modules/parseurl/package.json b/node_modules/express/node_modules/parseurl/package.json new file mode 100644 index 000000000..dad3a3f11 --- /dev/null +++ b/node_modules/express/node_modules/parseurl/package.json @@ -0,0 +1,42 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "https://github.com/expressjs/parseurl.git" + }, + "bugs": { + "url": "https://github.com/expressjs/parseurl/issues", + "email": "me@jongleberry.com" + }, + "license": "MIT", + "homepage": "https://github.com/expressjs/parseurl", + "_id": "parseurl@1.0.1", + "dist": { + "shasum": "2e57dce6efdd37c3518701030944c22bf388b7b4", + "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz" + }, + "_from": "parseurl@1.0.1", + "_npmVersion": "1.4.4", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "directories": {}, + "_shasum": "2e57dce6efdd37c3518701030944c22bf388b7b4", + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", + "readme": "# parseurl\n\nParse a URL with memoization.\n\n## API\n\n### var pathname = parseurl(req)\n\n`pathname` can then be passed to a router or something.\n\n## LICENSE\n\n(The MIT License)\n\nCopyright (c) 2014 Jonathan Ong \n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "README.md" +} diff --git a/node_modules/express/node_modules/path-to-regexp/.npmignore b/node_modules/express/node_modules/path-to-regexp/.npmignore new file mode 100644 index 000000000..ba2a97b57 --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/.npmignore @@ -0,0 +1,2 @@ +node_modules +coverage diff --git a/node_modules/express/node_modules/path-to-regexp/History.md b/node_modules/express/node_modules/path-to-regexp/History.md new file mode 100644 index 000000000..68aedb6a7 --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/History.md @@ -0,0 +1,11 @@ + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/node_modules/express/node_modules/path-to-regexp/Readme.md b/node_modules/express/node_modules/path-to-regexp/Readme.md new file mode 100644 index 000000000..9199e3876 --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,33 @@ + +# Path-to-RegExp + + Turn an Express-style path string such as `/user/:name` into a regular expression. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT \ No newline at end of file diff --git a/node_modules/express/node_modules/path-to-regexp/component.json b/node_modules/express/node_modules/path-to-regexp/component.json new file mode 100644 index 000000000..90f836c7b --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/component.json @@ -0,0 +1,15 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.0", + "keywords": [ + "express", + "regexp", + "route", + "routing" + ], + "scripts": [ + "index.js" + ], + "license": "MIT" +} diff --git a/node_modules/express/node_modules/path-to-regexp/index.js b/node_modules/express/node_modules/path-to-regexp/index.js new file mode 100644 index 000000000..11c32bfab --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/index.js @@ -0,0 +1,56 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + var sensitive = options.sensitive; + var strict = options.strict; + var end = options.end !== false; + keys = keys || []; + + if (path instanceof RegExp) return path; + if (path instanceof Array) path = '(' + path.join('|') + ')'; + + path = path + .concat(strict ? '' : '/?') + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ name: key, optional: !!optional }); + + return '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + }) + .replace(/\*/g, '(.*)'); + + return new RegExp('^' + path + (end ? '$' : '(?=\/|$)'), sensitive ? '' : 'i'); +}; diff --git a/node_modules/express/node_modules/path-to-regexp/package.json b/node_modules/express/node_modules/path-to-regexp/package.json new file mode 100644 index 000000000..0a536e14f --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/package.json @@ -0,0 +1,129 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.2", + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + }, + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "homepage": "https://github.com/component/path-to-regexp", + "_id": "path-to-regexp@0.1.2", + "dist": { + "shasum": "9b2b151f9cc3018c9eea50ca95729e05781712b4", + "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz" + }, + "_from": "path-to-regexp@0.1.2", + "_npmVersion": "1.4.4", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + { + "name": "retrofox", + "email": "rdsuarez@gmail.com" + }, + { + "name": "coreh", + "email": "thecoreh@gmail.com" + }, + { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + }, + { + "name": "kelonye", + "email": "kelonyemitchel@gmail.com" + }, + { + "name": "mattmueller", + "email": "mattmuelle@gmail.com" + }, + { + "name": "yields", + "email": "yields@icloud.com" + }, + { + "name": "anthonyshort", + "email": "antshort@gmail.com" + }, + { + "name": "ianstormtaylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "cristiandouce", + "email": "cristian@gravityonmars.com" + }, + { + "name": "swatinem", + "email": "arpad.borsos@googlemail.com" + }, + { + "name": "stagas", + "email": "gstagas@gmail.com" + }, + { + "name": "amasad", + "email": "amjad.masad@gmail.com" + }, + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "calvinfo", + "email": "calvin@calv.info" + }, + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + } + ], + "directories": {}, + "_shasum": "9b2b151f9cc3018c9eea50ca95729e05781712b4", + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz" +} diff --git a/node_modules/express/node_modules/path-to-regexp/test.js b/node_modules/express/node_modules/path-to-regexp/test.js new file mode 100644 index 000000000..bdce042da --- /dev/null +++ b/node_modules/express/node_modules/path-to-regexp/test.js @@ -0,0 +1,510 @@ +var pathToRegExp = require('./'); +var assert = require('assert'); + +describe('path-to-regexp', function () { + describe('strings', function () { + it('should match simple paths', function () { + var params = []; + var m = pathToRegExp('/test', params).exec('/test'); + + assert.equal(params.length, 0); + + assert.equal(m.length, 1); + assert.equal(m[0], '/test'); + }); + + it('should match express format params', function () { + var params = []; + var m = pathToRegExp('/:test', params).exec('/pathname'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/pathname'); + assert.equal(m[1], 'pathname'); + }); + + it('should do strict matches', function () { + var params = []; + var re = pathToRegExp('/:test', params, { strict: true }); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/route'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/route'); + assert.equal(m[1], 'route'); + + m = re.exec('/route/'); + + assert.ok(!m); + }); + + it('should allow optional express format params', function () { + var params = []; + var re = pathToRegExp('/:test?', params); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, true); + + m = re.exec('/route'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/route'); + assert.equal(m[1], 'route'); + + m = re.exec('/'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/'); + assert.equal(m[1], undefined); + }); + + it('should allow express format param regexps', function () { + var params = []; + var m = pathToRegExp('/:page(\\d+)', params).exec('/56'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'page'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/56'); + assert.equal(m[1], '56'); + }); + + it('should match without a prefixed slash', function () { + var params = []; + var m = pathToRegExp(':test', params).exec('string'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], 'string'); + assert.equal(m[1], 'string'); + }); + + it('should not match format parts', function () { + var params = []; + var m = pathToRegExp('/:test.json', params).exec('/route.json'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/route.json'); + assert.equal(m[1], 'route'); + }); + + it('should match format parts', function () { + var params = []; + var re = pathToRegExp('/:test.:format', params); + var m; + + assert.equal(params.length, 2); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + assert.equal(params[1].name, 'format'); + assert.equal(params[1].optional, false); + + m = re.exec('/route.json'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/route.json'); + assert.equal(m[1], 'route'); + assert.equal(m[2], 'json'); + + m = re.exec('/route'); + + assert.ok(!m); + }); + + it('should match route parts with a trailing format', function () { + var params = []; + var m = pathToRegExp('/:test.json', params).exec('/route.json'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/route.json'); + assert.equal(m[1], 'route'); + }); + + it('should match optional trailing routes', function () { + var params = []; + var m = pathToRegExp('/test*', params).exec('/test/route'); + + assert.equal(params.length, 0); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test/route'); + assert.equal(m[1], '/route'); + }); + + it('should match optional trailing routes after a param', function () { + var params = []; + var re = pathToRegExp('/:test*', params); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/test/route'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/test/route'); + assert.equal(m[1], 'test'); + assert.equal(m[2], '/route'); + + m = re.exec('/testing'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/testing'); + assert.equal(m[1], 'testing'); + assert.equal(m[2], ''); + }); + + it('should match optional trailing routes before a format', function () { + var params = []; + var re = pathToRegExp('/test*.json', params); + var m; + + assert.equal(params.length, 0); + + m = re.exec('/test.json'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test.json'); + assert.equal(m[1], ''); + + m = re.exec('/testing.json'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/testing.json'); + assert.equal(m[1], 'ing'); + + m = re.exec('/test/route.json'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test/route.json'); + assert.equal(m[1], '/route'); + }); + + it('should match optional trailing routes after a param and before a format', function () { + var params = []; + var re = pathToRegExp('/:test*.json', params); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/testing.json'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/testing.json'); + assert.equal(m[1], 'testing'); + assert.equal(m[2], ''); + + m = re.exec('/test/route.json'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/test/route.json'); + assert.equal(m[1], 'test'); + assert.equal(m[2], '/route'); + + m = re.exec('.json'); + + assert.ok(!m); + }); + + it('should match optional trailing routes between a normal param and a format param', function () { + var params = []; + var re = pathToRegExp('/:test*.:format', params); + var m; + + assert.equal(params.length, 2); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + assert.equal(params[1].name, 'format'); + assert.equal(params[1].optional, false); + + m = re.exec('/testing.json'); + + assert.equal(m.length, 4); + assert.equal(m[0], '/testing.json'); + assert.equal(m[1], 'testing'); + assert.equal(m[2], ''); + assert.equal(m[3], 'json'); + + m = re.exec('/test/route.json'); + + assert.equal(m.length, 4); + assert.equal(m[0], '/test/route.json'); + assert.equal(m[1], 'test'); + assert.equal(m[2], '/route'); + assert.equal(m[3], 'json'); + + m = re.exec('/test'); + + assert.ok(!m); + + m = re.exec('.json'); + + assert.ok(!m); + }); + + it('should match optional trailing routes after a param and before an optional format param', function () { + var params = []; + var re = pathToRegExp('/:test*.:format?', params); + var m; + + assert.equal(params.length, 2); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + assert.equal(params[1].name, 'format'); + assert.equal(params[1].optional, true); + + m = re.exec('/testing.json'); + + assert.equal(m.length, 4); + assert.equal(m[0], '/testing.json'); + assert.equal(m[1], 'testing'); + assert.equal(m[2], ''); + assert.equal(m[3], 'json'); + + m = re.exec('/test/route.json'); + + assert.equal(m.length, 4); + assert.equal(m[0], '/test/route.json'); + assert.equal(m[1], 'test'); + assert.equal(m[2], '/route'); + assert.equal(m[3], 'json'); + + m = re.exec('/test'); + + assert.equal(m.length, 4); + assert.equal(m[0], '/test'); + assert.equal(m[1], 'test'); + assert.equal(m[2], ''); + assert.equal(m[3], undefined); + + m = re.exec('.json'); + + assert.ok(!m); + }); + + it('should match optional trailing routes inside optional express param', function () { + var params = []; + var re = pathToRegExp('/:test*?', params); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, true); + + m = re.exec('/test/route'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/test/route'); + assert.equal(m[1], 'test'); + assert.equal(m[2], '/route'); + + m = re.exec('/test'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/test'); + assert.equal(m[1], 'test'); + assert.equal(m[2], ''); + + m = re.exec('/'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/'); + assert.equal(m[1], undefined); + assert.equal(m[2], undefined); + }); + + it('should do case insensitive matches', function () { + var m = pathToRegExp('/test').exec('/TEST'); + + assert.equal(m[0], '/TEST'); + }); + + it('should do case sensitive matches', function () { + var re = pathToRegExp('/test', null, { sensitive: true }); + var m; + + m = re.exec('/test'); + + assert.equal(m.length, 1); + assert.equal(m[0], '/test'); + + m = re.exec('/TEST'); + + assert.ok(!m); + }); + + it('should do non-ending matches', function () { + var params = []; + var m = pathToRegExp('/:test', params, { end: false }).exec('/test/route'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test'); + assert.equal(m[1], 'test'); + }); + + it('should match trailing slashes in non-ending non-strict mode', function () { + var params = []; + var re = pathToRegExp('/:test', params, { end: false }); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/test/'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test/'); + assert.equal(m[1], 'test'); + }); + + it('should not match trailing slashes in non-ending strict mode', function () { + var params = []; + var re = pathToRegExp('/:test', params, { end: false, strict: true }); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/test/'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test'); + assert.equal(m[1], 'test'); + }); + + it('should match text after an express param', function () { + var params = []; + var re = pathToRegExp('/(:test)route', params); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + m = re.exec('/route'); + + assert.ok(!m); + + m = re.exec('/testroute'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/testroute'); + assert.equal(m[1], 'test'); + + m = re.exec('testroute'); + + assert.ok(!m); + }); + + it('should match text after an optional express param', function () { + var params = []; + var re = pathToRegExp('/(:test?)route', params); + var m; + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, true); + + m = re.exec('/route'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/route'); + assert.equal(m[1], undefined); + + m = re.exec('/testroute'); + + assert.equal(m.length, 2); + assert.equal(m[0], '/testroute'); + assert.equal(m[1], 'test'); + + m = re.exec('route'); + + assert.ok(!m); + }); + + it('should match optional formats', function () { + var params = []; + var re = pathToRegExp('/:test.:format?', params); + var m; + + assert.equal(params.length, 2); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + assert.equal(params[1].name, 'format'); + assert.equal(params[1].optional, true); + + m = re.exec('/route'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/route'); + assert.equal(m[1], 'route'); + assert.equal(m[2], undefined); + + m = re.exec('/route.json'); + + assert.equal(m.length, 3); + assert.equal(m[0], '/route.json'); + assert.equal(m[1], 'route'); + assert.equal(m[2], 'json'); + }); + + it('should match full paths with format by default', function () { + var params = []; + var m = pathToRegExp('/:test', params).exec('/test.json'); + + assert.equal(params.length, 1); + assert.equal(params[0].name, 'test'); + assert.equal(params[0].optional, false); + + assert.equal(m.length, 2); + assert.equal(m[0], '/test.json'); + assert.equal(m[1], 'test.json'); + }); + }); + + describe('regexps', function () { + it('should return the regexp', function () { + assert.deepEqual(pathToRegExp(/.*/), /.*/); + }); + }); + + describe('arrays', function () { + it('should join arrays parts', function () { + var re = pathToRegExp(['/test', '/route']); + + assert.ok(re.exec('/test')); + assert.ok(re.exec('/route')); + assert.ok(!re.exec('/else')); + }); + }); +}); diff --git a/node_modules/express/node_modules/qs/.gitmodules b/node_modules/express/node_modules/qs/.gitmodules new file mode 100644 index 000000000..49e31dac7 --- /dev/null +++ b/node_modules/express/node_modules/qs/.gitmodules @@ -0,0 +1,6 @@ +[submodule "support/expresso"] + path = support/expresso + url = git://github.com/visionmedia/expresso.git +[submodule "support/should"] + path = support/should + url = git://github.com/visionmedia/should.js.git diff --git a/node_modules/express/node_modules/qs/.npmignore b/node_modules/express/node_modules/qs/.npmignore new file mode 100644 index 000000000..e85ce2afa --- /dev/null +++ b/node_modules/express/node_modules/qs/.npmignore @@ -0,0 +1,7 @@ +test +.travis.yml +benchmark.js +component.json +examples.js +History.md +Makefile diff --git a/node_modules/express/node_modules/qs/Readme.md b/node_modules/express/node_modules/qs/Readme.md new file mode 100644 index 000000000..27e54a4af --- /dev/null +++ b/node_modules/express/node_modules/qs/Readme.md @@ -0,0 +1,58 @@ +# node-querystring + + query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others. + +## Installation + + $ npm install qs + +## Examples + +```js +var qs = require('qs'); + +qs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com'); +// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } } + +qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}) +// => user[name]=Tobi&user[email]=tobi%40learnboost.com +``` + +## Testing + +Install dev dependencies: + + $ npm install -d + +and execute: + + $ make test + +browser: + + $ open test/browser/index.html + +## License + +(The MIT License) + +Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/index.js b/node_modules/express/node_modules/qs/index.js new file mode 100644 index 000000000..b05938acc --- /dev/null +++ b/node_modules/express/node_modules/qs/index.js @@ -0,0 +1,366 @@ +/** + * Object#toString() ref for stringify(). + */ + +var toString = Object.prototype.toString; + +/** + * Object#hasOwnProperty ref + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Array#indexOf shim. + */ + +var indexOf = typeof Array.prototype.indexOf === 'function' + ? function(arr, el) { return arr.indexOf(el); } + : function(arr, el) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] === el) return i; + } + return -1; + }; + +/** + * Array.isArray shim. + */ + +var isArray = Array.isArray || function(arr) { + return toString.call(arr) == '[object Array]'; +}; + +/** + * Object.keys shim. + */ + +var objectKeys = Object.keys || function(obj) { + var ret = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + ret.push(key); + } + } + return ret; +}; + +/** + * Array#forEach shim. + */ + +var forEach = typeof Array.prototype.forEach === 'function' + ? function(arr, fn) { return arr.forEach(fn); } + : function(arr, fn) { + for (var i = 0; i < arr.length; i++) fn(arr[i]); + }; + +/** + * Array#reduce shim. + */ + +var reduce = function(arr, fn, initial) { + if (typeof arr.reduce === 'function') return arr.reduce(fn, initial); + var res = initial; + for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]); + return res; +}; + +/** + * Cache non-integer test regexp. + */ + +var isint = /^[0-9]+$/; + +function promote(parent, key) { + if (parent[key].length == 0) return parent[key] = {} + var t = {}; + for (var i in parent[key]) { + if (hasOwnProperty.call(parent[key], i)) { + t[i] = parent[key][i]; + } + } + parent[key] = t; + return t; +} + +function parse(parts, parent, key, val) { + var part = parts.shift(); + + // illegal + if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; + + // end + if (!part) { + if (isArray(parent[key])) { + parent[key].push(val); + } else if ('object' == typeof parent[key]) { + parent[key] = val; + } else if ('undefined' == typeof parent[key]) { + parent[key] = val; + } else { + parent[key] = [parent[key], val]; + } + // array + } else { + var obj = parent[key] = parent[key] || []; + if (']' == part) { + if (isArray(obj)) { + if ('' != val) obj.push(val); + } else if ('object' == typeof obj) { + obj[objectKeys(obj).length] = val; + } else { + obj = parent[key] = [parent[key], val]; + } + // prop + } else if (~indexOf(part, ']')) { + part = part.substr(0, part.length - 1); + if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); + parse(parts, obj, part, val); + // key + } else { + if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); + parse(parts, obj, part, val); + } + } +} + +/** + * Merge parent key/val pair. + */ + +function merge(parent, key, val){ + if (~indexOf(key, ']')) { + var parts = key.split('[') + , len = parts.length + , last = len - 1; + parse(parts, parent, 'base', val); + // optimize + } else { + if (!isint.test(key) && isArray(parent.base)) { + var t = {}; + for (var k in parent.base) t[k] = parent.base[k]; + parent.base = t; + } + set(parent.base, key, val); + } + + return parent; +} + +/** + * Compact sparse arrays. + */ + +function compact(obj) { + if ('object' != typeof obj) return obj; + + if (isArray(obj)) { + var ret = []; + + for (var i in obj) { + if (hasOwnProperty.call(obj, i)) { + ret.push(obj[i]); + } + } + + return ret; + } + + for (var key in obj) { + obj[key] = compact(obj[key]); + } + + return obj; +} + +/** + * Parse the given obj. + */ + +function parseObject(obj){ + var ret = { base: {} }; + + forEach(objectKeys(obj), function(name){ + merge(ret, name, obj[name]); + }); + + return compact(ret.base); +} + +/** + * Parse the given str. + */ + +function parseString(str){ + var ret = reduce(String(str).split('&'), function(ret, pair){ + var eql = indexOf(pair, '=') + , brace = lastBraceInKey(pair) + , key = pair.substr(0, brace || eql) + , val = pair.substr(brace || eql, pair.length) + , val = val.substr(indexOf(val, '=') + 1, val.length); + + // ?foo + if ('' == key) key = pair, val = ''; + if ('' == key) return ret; + + return merge(ret, decode(key), decode(val)); + }, { base: {} }).base; + + return compact(ret); +} + +/** + * Parse the given query `str` or `obj`, returning an object. + * + * @param {String} str | {Object} obj + * @return {Object} + * @api public + */ + +exports.parse = function(str){ + if (null == str || '' == str) return {}; + return 'object' == typeof str + ? parseObject(str) + : parseString(str); +}; + +/** + * Turn the given `obj` into a query string + * + * @param {Object} obj + * @return {String} + * @api public + */ + +var stringify = exports.stringify = function(obj, prefix) { + if (isArray(obj)) { + return stringifyArray(obj, prefix); + } else if ('[object Object]' == toString.call(obj)) { + return stringifyObject(obj, prefix); + } else if ('string' == typeof obj) { + return stringifyString(obj, prefix); + } else { + return prefix + '=' + encodeURIComponent(String(obj)); + } +}; + +/** + * Stringify the given `str`. + * + * @param {String} str + * @param {String} prefix + * @return {String} + * @api private + */ + +function stringifyString(str, prefix) { + if (!prefix) throw new TypeError('stringify expects an object'); + return prefix + '=' + encodeURIComponent(str); +} + +/** + * Stringify the given `arr`. + * + * @param {Array} arr + * @param {String} prefix + * @return {String} + * @api private + */ + +function stringifyArray(arr, prefix) { + var ret = []; + if (!prefix) throw new TypeError('stringify expects an object'); + for (var i = 0; i < arr.length; i++) { + ret.push(stringify(arr[i], prefix + '[' + i + ']')); + } + return ret.join('&'); +} + +/** + * Stringify the given `obj`. + * + * @param {Object} obj + * @param {String} prefix + * @return {String} + * @api private + */ + +function stringifyObject(obj, prefix) { + var ret = [] + , keys = objectKeys(obj) + , key; + + for (var i = 0, len = keys.length; i < len; ++i) { + key = keys[i]; + if ('' == key) continue; + if (null == obj[key]) { + ret.push(encodeURIComponent(key) + '='); + } else { + ret.push(stringify(obj[key], prefix + ? prefix + '[' + encodeURIComponent(key) + ']' + : encodeURIComponent(key))); + } + } + + return ret.join('&'); +} + +/** + * Set `obj`'s `key` to `val` respecting + * the weird and wonderful syntax of a qs, + * where "foo=bar&foo=baz" becomes an array. + * + * @param {Object} obj + * @param {String} key + * @param {String} val + * @api private + */ + +function set(obj, key, val) { + var v = obj[key]; + if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; + if (undefined === v) { + obj[key] = val; + } else if (isArray(v)) { + v.push(val); + } else { + obj[key] = [v, val]; + } +} + +/** + * Locate last brace in `str` within the key. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function lastBraceInKey(str) { + var len = str.length + , brace + , c; + for (var i = 0; i < len; ++i) { + c = str[i]; + if (']' == c) brace = false; + if ('[' == c) brace = true; + if ('=' == c && !brace) return i; + } +} + +/** + * Decode `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +function decode(str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (err) { + return str; + } +} diff --git a/node_modules/express/node_modules/qs/package.json b/node_modules/express/node_modules/qs/package.json new file mode 100644 index 000000000..3ccbbcfb8 --- /dev/null +++ b/node_modules/express/node_modules/qs/package.json @@ -0,0 +1,38 @@ +{ + "name": "qs", + "description": "querystring parser", + "version": "0.6.6", + "keywords": [ + "query string", + "parser", + "component" + ], + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-querystring.git" + }, + "devDependencies": { + "mocha": "*", + "expect.js": "*" + }, + "scripts": { + "test": "make test" + }, + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "main": "index", + "engines": { + "node": "*" + }, + "readme": "# node-querystring\n\n query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others.\n\n## Installation\n\n $ npm install qs\n\n## Examples\n\n```js\nvar qs = require('qs');\n\nqs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com');\n// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } }\n\nqs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }})\n// => user[name]=Tobi&user[email]=tobi%40learnboost.com\n```\n\n## Testing\n\nInstall dev dependencies:\n\n $ npm install -d\n\nand execute:\n\n $ make test\n\nbrowser:\n\n $ open test/browser/index.html\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/visionmedia/node-querystring/issues" + }, + "homepage": "https://github.com/visionmedia/node-querystring", + "_id": "qs@0.6.6", + "_from": "qs@0.6.6" +} diff --git a/node_modules/express/node_modules/range-parser/.npmignore b/node_modules/express/node_modules/range-parser/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/express/node_modules/range-parser/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/express/node_modules/range-parser/History.md b/node_modules/express/node_modules/range-parser/History.md new file mode 100644 index 000000000..b35ba515c --- /dev/null +++ b/node_modules/express/node_modules/range-parser/History.md @@ -0,0 +1,21 @@ + +1.0.0 / 2013-12-11 +================== + + * add repository to package.json + * add MIT license + +0.0.4 / 2012-06-17 +================== + + * changed: ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * add `.type` diff --git a/node_modules/express/node_modules/range-parser/Makefile b/node_modules/express/node_modules/range-parser/Makefile new file mode 100644 index 000000000..8e8640f2e --- /dev/null +++ b/node_modules/express/node_modules/range-parser/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --reporter spec \ + --require should + +.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/Readme.md b/node_modules/express/node_modules/range-parser/Readme.md new file mode 100644 index 000000000..cb30a5ac0 --- /dev/null +++ b/node_modules/express/node_modules/range-parser/Readme.md @@ -0,0 +1,53 @@ + +# node-range-parser + + Range header field parser. + +## Example: + +```js +assert(-1 == parse(200, 'bytes=500-20')); +assert(-2 == parse(200, 'bytes=malformed')); +parse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }])); +parse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }])); +parse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }])); +parse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }])); +parse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }])); +parse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }])); +parse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }])); +parse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }])); +parse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }])); +parse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }])); +parse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }])); +``` + +## Installation + +``` +$ npm install range-parser +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/index.js b/node_modules/express/node_modules/range-parser/index.js new file mode 100644 index 000000000..9b0f7a8ec --- /dev/null +++ b/node_modules/express/node_modules/range-parser/index.js @@ -0,0 +1,49 @@ + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @api public + */ + +module.exports = function(size, str){ + var valid = true; + var i = str.indexOf('='); + + if (-1 == i) return -2; + + var arr = str.slice(i + 1).split(',').map(function(range){ + var range = range.split('-') + , start = parseInt(range[0], 10) + , end = parseInt(range[1], 10); + + // -nnn + if (isNaN(start)) { + start = size - end; + end = size - 1; + // nnn- + } else if (isNaN(end)) { + end = size - 1; + } + + // limit last-byte-pos to current length + if (end > size - 1) end = size - 1; + + // invalid + if (isNaN(start) + || isNaN(end) + || start > end + || start < 0) valid = false; + + return { + start: start, + end: end + }; + }); + + arr.type = str.slice(0, i); + + return valid ? arr : -1; +}; \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/package.json b/node_modules/express/node_modules/range-parser/package.json new file mode 100644 index 000000000..1b1c0dc16 --- /dev/null +++ b/node_modules/express/node_modules/range-parser/package.json @@ -0,0 +1,52 @@ +{ + "name": "range-parser", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "Range header field string parser", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-range-parser.git" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/visionmedia/node-range-parser#license" + } + ], + "bugs": { + "url": "https://github.com/visionmedia/node-range-parser/issues" + }, + "_id": "range-parser@1.0.0", + "dist": { + "shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz" + }, + "_from": "range-parser@1.0.0", + "_npmVersion": "1.2.30", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz", + "readme": "\n# node-range-parser\n\n Range header field parser.\n\n## Example:\n\n```js\nassert(-1 == parse(200, 'bytes=500-20'));\nassert(-2 == parse(200, 'bytes=malformed'));\nparse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));\nparse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));\nparse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));\nparse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));\nparse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));\nparse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));\nparse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));\nparse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));\nparse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));\n```\n\n## Installation\n\n```\n$ npm install range-parser\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md", + "homepage": "https://github.com/visionmedia/node-range-parser" +} diff --git a/node_modules/express/node_modules/send/.npmignore b/node_modules/express/node_modules/send/.npmignore new file mode 100644 index 000000000..670588af5 --- /dev/null +++ b/node_modules/express/node_modules/send/.npmignore @@ -0,0 +1,3 @@ +test +examples +*.sock diff --git a/node_modules/express/node_modules/send/History.md b/node_modules/express/node_modules/send/History.md new file mode 100644 index 000000000..5de73da99 --- /dev/null +++ b/node_modules/express/node_modules/send/History.md @@ -0,0 +1,61 @@ + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/node_modules/send/Readme.md b/node_modules/express/node_modules/send/Readme.md new file mode 100644 index 000000000..7fbd77965 --- /dev/null +++ b/node_modules/express/node_modules/send/Readme.md @@ -0,0 +1,156 @@ +# send + + Send is Connect's `static()` extracted for generalized use, a streaming static file + server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework. + +## Installation + + $ npm install send + +## Examples + + Small: + +```js +var http = require('http'); +var send = require('send'); + +var app = http.createServer(function(req, res){ + send(req, req.url).pipe(res); +}).listen(3000); +``` + + Serving from a root directory with custom error-handling: + +```js +var http = require('http'); +var send = require('send'); +var url = require('url'); + +var app = http.createServer(function(req, res){ + // your custom error-handling logic: + function error(err) { + res.statusCode = err.status || 500; + res.end(err.message); + } + + // your custom directory handling logic: + function redirect() { + res.statusCode = 301; + res.setHeader('Location', req.url + '/'); + res.end('Redirecting to ' + req.url + '/'); + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, url.parse(req.url).pathname, {root: '/www/example.com/public'}) + .on('error', error) + .on('directory', redirect) + .pipe(res); +}).listen(3000); +``` + +## API + +### Options + +#### etag + + Enable or disable etag generation, defaults to true. + +#### hidden + + Enable or disable transfer of hidden files, defaults to false. + +#### index + + By default send supports "index.html" files, to disable this + set `false` or to supply a new index pass a string or an array + in preferred order. + +#### maxage + + Provide a max-age in milliseconds for http caching, defaults to 0. + +#### root + + Serve files relative to `path`. + +### Events + + - `error` an error occurred `(err)` + - `directory` a directory was requested + - `file` a file was requested `(path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +### .etag(bool) + + Enable or disable etag generation, defaults to true. + +### .root(dir) + + Serve files relative to `path`. Aliased as `.from(dir)`. + +### .index(paths) + + By default send supports "index.html" files, to disable this + invoke `.index(false)` or to supply a new index pass a string + or an array in preferred order. + +### .maxage(ms) + + Provide a max-age in milliseconds for http caching, defaults to 0. + +### .hidden(bool) + + Enable or disable transfer of hidden files, defaults to false. + +## Error-handling + + By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc. + +## Caching + + It does _not_ perform internal caching, you should use a reverse proxy cache such + as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;). + +## Debugging + + To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ make test +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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/express/node_modules/send/index.js b/node_modules/express/node_modules/send/index.js new file mode 100644 index 000000000..f17158d85 --- /dev/null +++ b/node_modules/express/node_modules/send/index.js @@ -0,0 +1,2 @@ + +module.exports = require('./lib/send'); \ No newline at end of file diff --git a/node_modules/express/node_modules/send/lib/send.js b/node_modules/express/node_modules/send/lib/send.js new file mode 100644 index 000000000..b2cfbaa14 --- /dev/null +++ b/node_modules/express/node_modules/send/lib/send.js @@ -0,0 +1,584 @@ + +/** + * Module dependencies. + */ + +var debug = require('debug')('send') + , parseRange = require('range-parser') + , Stream = require('stream') + , mime = require('mime') + , fresh = require('fresh') + , path = require('path') + , http = require('http') + , fs = require('fs') + , basename = path.basename + , normalize = path.normalize + , join = path.join + , utils = require('./utils'); + +var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/; + +/** + * Expose `send`. + */ + +exports = module.exports = send; + +/** + * Expose mime module. + */ + +exports.mime = mime; + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {Request} req + * @param {String} path + * @param {Object} options + * @return {SendStream} + * @api public + */ + +function send(req, path, options) { + return new SendStream(req, path, options); +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * Events: + * + * - `error` an error occurred + * - `stream` file streaming has started + * - `end` streaming has completed + * - `directory` a directory was requested + * + * @param {Request} req + * @param {String} path + * @param {Object} options + * @api private + */ + +function SendStream(req, path, options) { + var self = this; + options = options || {}; + this.req = req; + this.path = path; + this.options = options; + this.etag(('etag' in options) ? options.etag : true); + this.maxage(options.maxage); + this.hidden(options.hidden); + this.index(('index' in options) ? options.index : 'index.html'); + if (options.root || options.from) this.root(options.root || options.from); +} + +/** + * Inherits from `Stream.prototype`. + */ + +SendStream.prototype.__proto__ = Stream.prototype; + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = function(val){ + val = Boolean(val); + debug('etag %s', val); + this._etag = val; + return this; +}; + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = function(val){ + val = Boolean(val); + debug('hidden %s', val); + this._hidden = val; + return this; +}; + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = function index(paths){ + var index = !paths ? [] : Array.isArray(paths) ? paths : [paths]; + debug('index %j', index); + this._index = index; + return this; +}; + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = +SendStream.prototype.from = function(path){ + path = String(path); + this._root = normalize(path); + return this; +}; + +/** + * Set max-age to `ms`. + * + * @param {Number} ms + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = function(ms){ + ms = Number(ms); + if (isNaN(ms)) ms = 0; + if (Infinity == ms) ms = 60 * 60 * 24 * 365 * 1000; + debug('max-age %d', ms); + this._maxage = ms; + return this; +}; + +/** + * Emit error with `status`. + * + * @param {Number} status + * @api private + */ + +SendStream.prototype.error = function(status, err){ + var res = this.res; + var msg = http.STATUS_CODES[status]; + err = err || new Error(msg); + err.status = status; + if (this.listeners('error').length) return this.emit('error', err); + res.statusCode = err.status; + res.end(msg); +}; + +/** + * Check if the pathname is potentially malicious. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isMalicious = function(){ + return !this._root && ~this.path.indexOf('..') && upPathRegexp.test(this.path); +}; + +/** + * Check if the pathname ends with "/". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasTrailingSlash = function(){ + return '/' == this.path[this.path.length - 1]; +}; + +/** + * Check if the basename leads with ".". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasLeadingDot = function(){ + return '.' == basename(this.path)[0]; +}; + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function(){ + return this.req.headers['if-none-match'] + || this.req.headers['if-modified-since']; +}; + +/** + * Strip content-* header fields. + * + * @api private + */ + +SendStream.prototype.removeContentHeaderFields = function(){ + var res = this.res; + Object.keys(res._headers).forEach(function(field){ + if (0 == field.indexOf('content')) { + res.removeHeader(field); + } + }); +}; + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function(){ + var res = this.res; + debug('not modified'); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); +}; + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent(){ + var err = new Error('Can\'t set headers after they are sent.'); + debug('headers already sent'); + this.error(500, err); +}; + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function(){ + var res = this.res; + return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; +}; + +/** + * Handle stat() error. + * + * @param {Error} err + * @api private + */ + +SendStream.prototype.onStatError = function(err){ + var notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR']; + if (~notfound.indexOf(err.code)) return this.error(404, err); + this.error(500, err); +}; + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function(){ + return fresh(this.req.headers, this.res._headers); +}; + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh(){ + var ifRange = this.req.headers['if-range']; + + if (!ifRange) return true; + + return ~ifRange.indexOf('"') + ? ~ifRange.indexOf(this.res._headers['etag']) + : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange); +}; + +/** + * Redirect to `path`. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.redirect = function(path){ + if (this.listeners('directory').length) return this.emit('directory'); + if (this.hasTrailingSlash()) return this.error(403); + var res = this.res; + path += '/'; + res.statusCode = 301; + res.setHeader('Location', path); + res.end('Redirecting to ' + utils.escape(path)); +}; + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function(res){ + var self = this + , args = arguments + , path = this.path + , root = this._root; + + // references + this.res = res; + + // invalid request uri + path = utils.decode(path); + if (-1 == path) return this.error(400); + + // null byte(s) + if (~path.indexOf('\0')) return this.error(400); + + // join / normalize from optional root dir + if (root) path = normalize(join(this._root, path)); + + // ".." is malicious without "root" + if (this.isMalicious()) return this.error(403); + + // malicious path + if (root && 0 != path.indexOf(root)) return this.error(403); + + // hidden file support + if (!this._hidden && this.hasLeadingDot()) return this.error(404); + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path); + return res; + } + + debug('stat "%s"', path); + fs.stat(path, function(err, stat){ + if (err) return self.onStatError(err); + if (stat.isDirectory()) return self.redirect(self.path); + self.emit('file', path, stat); + self.send(path, stat); + }); + + return res; +}; + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function(path, stat){ + var options = this.options; + var len = stat.size; + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + + if (res._header) { + // impossible to send now + return this.headersAlreadySent(); + } + + // set header fields + this.setHeader(path, stat); + + // set content-type + this.type(path); + + // conditional GET support + if (this.isConditionalGET() + && this.isCachable() + && this.isFresh()) { + return this.notModified(); + } + + // adjust len to start/end options + len = Math.max(0, len - offset); + if (options.end !== undefined) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + + // Range support + if (ranges) { + ranges = parseRange(len, ranges); + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale'); + ranges = -2; + } + + // unsatisfiable + if (-1 == ranges) { + debug('range unsatisfiable'); + res.setHeader('Content-Range', 'bytes */' + stat.size); + return this.error(416); + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (-2 != ranges && ranges.length === 1) { + debug('range %j', ranges); + + options.start = offset + ranges[0].start; + options.end = offset + ranges[0].end; + + // Content-Range + res.statusCode = 206; + res.setHeader('Content-Range', 'bytes ' + + ranges[0].start + + '-' + + ranges[0].end + + '/' + + len); + len = options.end - options.start + 1; + } + } + + // content-length + res.setHeader('Content-Length', len); + + // HEAD support + if ('HEAD' == req.method) return res.end(); + + this.stream(path, options); +}; + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex(path){ + var i = -1; + var self = this; + + function next(err){ + if (i++ >= self._index.length) { + if (err) return self.onStatError(err); + return self.redirect(self.path); + } + + var p = path + self._index[i]; + + debug('stat "%s"', p); + fs.stat(p, function(err, stat){ + if (err) return next(err); + if (stat.isDirectory()) return self.redirect(self.path); + self.emit('file', p, stat); + self.send(p, stat); + }); + } + + if (!this.hasTrailingSlash()) path += '/'; + + next(); +}; + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function(path, options){ + // TODO: this is all lame, refactor meeee + var self = this; + var res = this.res; + var req = this.req; + + // pipe + var stream = fs.createReadStream(path, options); + this.emit('stream', stream); + stream.pipe(res); + + // socket closed, done with the fd + req.on('close', stream.destroy.bind(stream)); + + // error handling code-smell + stream.on('error', function(err){ + // no hope in responding + if (res._header) { + console.error(err.stack); + req.destroy(); + return; + } + + // 500 + err.status = 500; + self.emit('error', err); + }); + + // end + stream.on('end', function(){ + self.emit('end'); + }); +}; + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function(path){ + var res = this.res; + if (res.getHeader('Content-Type')) return; + var type = mime.lookup(path); + var charset = mime.charsets.lookup(type); + debug('content-type %s', type); + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); +}; + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader(path, stat){ + var res = this.res; + if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); + if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString()); + if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (this._maxage / 1000)); + if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString()); + + if (this._etag && !res.getHeader('ETag')) { + var etag = utils.etag(path, stat); + debug('etag %s', etag); + res.setHeader('ETag', etag); + } +}; diff --git a/node_modules/express/node_modules/send/lib/utils.js b/node_modules/express/node_modules/send/lib/utils.js new file mode 100644 index 000000000..1b32fe3ad --- /dev/null +++ b/node_modules/express/node_modules/send/lib/utils.js @@ -0,0 +1,54 @@ + +/** + * Module dependencies. + */ + +var crc32 = require('buffer-crc32').unsigned; + +/** + * Return a weak ETag from the given `path` and `stat`. + * + * @param {String} path + * @param {Object} stat + * @return {String} + * @api private + */ + +exports.etag = function etag(path, stat) { + var tag = String(stat.mtime.getTime()) + ':' + String(stat.size) + ':' + path; + return 'W/"' + crc32(tag) + '"'; +}; + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +exports.decode = function(path){ + try { + return decodeURIComponent(path); + } catch (err) { + return -1; + } +}; + +/** + * Escape the given string of `html`. + * + * @param {String} html + * @return {String} + * @api private + */ + +exports.escape = function(html){ + return String(html) + .replace(/&(?!\w+;)/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +}; \ No newline at end of file diff --git a/node_modules/express/node_modules/send/node_modules/debug/Readme.md b/node_modules/express/node_modules/send/node_modules/debug/Readme.md new file mode 100644 index 000000000..8981f8abe --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/debug/Readme.md @@ -0,0 +1,114 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +``` +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + a('doing some work'); +}, 1200); +``` + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +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/express/node_modules/send/node_modules/debug/debug.js b/node_modules/express/node_modules/send/node_modules/debug/debug.js new file mode 100644 index 000000000..509dc0ded --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/debug/debug.js @@ -0,0 +1,137 @@ + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + if (!debug.enabled(name)) return function(){}; + + return function(fmt){ + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (debug[name] || curr); + debug[name] = curr; + + fmt = name + + ' ' + + fmt + + ' +' + debug.humanize(ms); + + // This hackery is required for IE8 + // where `console.log` doesn't have 'apply' + window.console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); + } +} + +/** + * The currently active debug mode names. + */ + +debug.names = []; +debug.skips = []; + +/** + * Enables a debug mode by name. This can include modes + * separated by a colon and wildcards. + * + * @param {String} name + * @api public + */ + +debug.enable = function(name) { + try { + localStorage.debug = name; + } catch(e){} + + var split = (name || '').split(/[\s,]+/) + , len = split.length; + + for (var i = 0; i < len; i++) { + name = split[i].replace('*', '.*?'); + if (name[0] === '-') { + debug.skips.push(new RegExp('^' + name.substr(1) + '$')); + } + else { + debug.names.push(new RegExp('^' + name + '$')); + } + } +}; + +/** + * Disable debug output. + * + * @api public + */ + +debug.disable = function(){ + debug.enable(''); +}; + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +debug.humanize = function(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +}; + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +debug.enabled = function(name) { + for (var i = 0, len = debug.skips.length; i < len; i++) { + if (debug.skips[i].test(name)) { + return false; + } + } + for (var i = 0, len = debug.names.length; i < len; i++) { + if (debug.names[i].test(name)) { + return true; + } + } + return false; +}; + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +// persist + +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){} diff --git a/node_modules/express/node_modules/send/node_modules/debug/lib/debug.js b/node_modules/express/node_modules/send/node_modules/debug/lib/debug.js new file mode 100644 index 000000000..e7422e68a --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/debug/lib/debug.js @@ -0,0 +1,158 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Enabled debuggers. + */ + +var names = [] + , skips = []; + +/** + * Colors. + */ + +var colors = [6, 2, 3, 4, 5, 1]; + +/** + * Previous debug() call. + */ + +var prev = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Is stdout a TTY? Colored output is disabled when `true`. + */ + +var isatty = tty.isatty(1); + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function color() { + return colors[prevColor++ % colors.length]; +} + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +function humanize(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +} + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + function disabled(){} + disabled.enabled = false; + + var match = skips.some(function(re){ + return re.test(name); + }); + + if (match) return disabled; + + match = names.some(function(re){ + return re.test(name); + }); + + if (!match) return disabled; + var c = color(); + + function colored(fmt) { + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (prev[name] || curr); + prev[name] = curr; + + fmt = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[3' + c + 'm\u001b[90m' + + fmt + '\u001b[3' + c + 'm' + + ' +' + humanize(ms) + '\u001b[0m'; + + console.log.apply(this, arguments); + } + + function plain(fmt) { + fmt = coerce(fmt); + + fmt = new Date().toUTCString() + + ' ' + name + ' ' + fmt; + console.log.apply(this, arguments); + } + + colored.enabled = plain.enabled = true; + + return isatty || process.env.DEBUG_COLORS + ? colored + : plain; +} + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +/** + * Enable specified `namespaces` for debugging. + */ + +debug.enable = function(namespaces) { + namespaces.split(/[\s,]+/) + .forEach(function(name){ + name = name.replace('*', '.*?'); + if (name[0] == '-') { + skips.push(new RegExp('^' + name.substr(1) + '$')); + } else { + names.push(new RegExp('^' + name + '$')); + } + }); +}; + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +debug.enable(process.env.DEBUG || ''); diff --git a/node_modules/express/node_modules/send/node_modules/debug/package.json b/node_modules/express/node_modules/send/node_modules/debug/package.json new file mode 100644 index 000000000..f7c6b58bf --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/debug/package.json @@ -0,0 +1,39 @@ +{ + "name": "debug", + "version": "0.8.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*" + }, + "main": "lib/debug.js", + "browser": "./debug.js", + "engines": { + "node": "*" + }, + "files": [ + "lib/debug.js", + "debug.js" + ], + "readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n\nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n\n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\".\n\n## Wildcards\n\n The `*` character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.\n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@0.8.0", + "_from": "debug@0.8.0" +} diff --git a/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/node_modules/express/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 000000000..451fc4550 --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/express/node_modules/send/node_modules/mime/README.md b/node_modules/express/node_modules/send/node_modules/mime/README.md new file mode 100644 index 000000000..6ca19bd1e --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,66 @@ +# mime + +Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + + var mime = require('mime'); + + mime.lookup('/path/to/file.txt'); // => 'text/plain' + mime.lookup('file.txt'); // => 'text/plain' + mime.lookup('.TXT'); // => 'text/plain' + mime.lookup('htm'); // => 'text/html' + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + + mime.extension('text/html'); // => 'html' + mime.extension('application/octet-stream'); // => 'bin' + +### mime.charsets.lookup() + +Map mime-type to charset + + mime.charsets.lookup('text/plain'); // => 'UTF-8' + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). + +### mime.define() + +Add custom mime/extension mappings + + mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... + }); + + mime.lookup('x-sft'); // => 'text/x-some-format' + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + + mime.extension('text/x-some-format'); // => 'x-sf' + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + + mime.load('./my_project.types'); + +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/send/node_modules/mime/mime.js b/node_modules/express/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 000000000..48be0c5e4 --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,114 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Load local copy of +// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +mime.load(path.join(__dirname, 'types/mime.types')); + +// Load additional types from node.js community +mime.load(path.join(__dirname, 'types/node.types')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/express/node_modules/send/node_modules/mime/package.json b/node_modules/express/node_modules/send/node_modules/mime/package.json new file mode 100644 index 000000000..259822b78 --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,58 @@ +{ + "author": { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "dependencies": {}, + "description": "A comprehensive library for mime-type mapping", + "devDependencies": {}, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.2.11", + "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.default_type\nSets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "_id": "mime@1.2.11", + "dist": { + "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + }, + "_from": "mime@~1.2.11", + "_npmVersion": "1.3.6", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "directories": {}, + "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "homepage": "https://github.com/broofa/node-mime" +} diff --git a/node_modules/express/node_modules/send/node_modules/mime/test.js b/node_modules/express/node_modules/send/node_modules/mime/test.js new file mode 100644 index 000000000..2cda1c7ad --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/test.js @@ -0,0 +1,84 @@ +/** + * Usage: node test.js + */ + +var mime = require('./mime'); +var assert = require('assert'); +var path = require('path'); + +function eq(a, b) { + console.log('Test: ' + a + ' === ' + b); + assert.strictEqual.apply(null, arguments); +} + +console.log(Object.keys(mime.extensions).length + ' types'); +console.log(Object.keys(mime.types).length + ' extensions\n'); + +// +// Test mime lookups +// + +eq('text/plain', mime.lookup('text.txt')); // normal file +eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase +eq('text/plain', mime.lookup('dir/text.txt')); // dir + file +eq('text/plain', mime.lookup('.text.txt')); // hidden file +eq('text/plain', mime.lookup('.txt')); // nameless +eq('text/plain', mime.lookup('txt')); // extension-only +eq('text/plain', mime.lookup('/txt')); // extension-less () +eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less +eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized +eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +eq('txt', mime.extension(mime.types.text)); +eq('html', mime.extension(mime.types.htm)); +eq('bin', mime.extension('application/octet-stream')); +eq('bin', mime.extension('application/octet-stream ')); +eq('html', mime.extension(' text/html; charset=UTF-8')); +eq('html', mime.extension('text/html; charset=UTF-8 ')); +eq('html', mime.extension('text/html; charset=UTF-8')); +eq('html', mime.extension('text/html ; charset=UTF-8')); +eq('html', mime.extension('text/html;charset=UTF-8')); +eq('html', mime.extension('text/Html;charset=UTF-8')); +eq(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +eq('application/font-woff', mime.lookup('file.woff')); +eq('application/octet-stream', mime.lookup('file.buffer')); +eq('audio/mp4', mime.lookup('file.m4a')); +eq('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +eq('UTF-8', mime.charsets.lookup('text/plain')); +eq(undefined, mime.charsets.lookup(mime.types.js)); +eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +// +// Test for overlaps between mime.types and node.types +// + +var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); +apacheTypes.load(path.join(__dirname, 'types/mime.types')); +nodeTypes.load(path.join(__dirname, 'types/node.types')); + +var keys = [].concat(Object.keys(apacheTypes.types)) + .concat(Object.keys(nodeTypes.types)); +keys.sort(); +for (var i = 1; i < keys.length; i++) { + if (keys[i] == keys[i-1]) { + console.warn('Warning: ' + + 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + + ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); + } +} + +console.log('\nOK'); diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/mime.types b/node_modules/express/node_modules/send/node_modules/mime/types/mime.types new file mode 100644 index 000000000..da8cd6918 --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/types/mime.types @@ -0,0 +1,1588 @@ +# This file maps Internet media types to unique file extension(s). +# Although created for httpd, this file is used by many software systems +# and has been placed in the public domain for unlimited redisribution. +# +# The table below contains both registered and (common) unregistered types. +# A type that has no unique extension can be ignored -- they are listed +# here to guide configurations toward known types and to make it easier to +# identify "new" types. File extensions are also commonly used to indicate +# content languages and encodings, so choose them carefully. +# +# Internet media types should be registered as described in RFC 4288. +# The registry is at . +# +# MIME type (lowercased) Extensions +# ============================================ ========== +# application/1d-interleaved-parityfec +# application/3gpp-ims+xml +# application/activemessage +application/andrew-inset ez +# application/applefile +application/applixware aw +application/atom+xml atom +application/atomcat+xml atomcat +# application/atomicmail +application/atomsvc+xml atomsvc +# application/auth-policy+xml +# application/batch-smtp +# application/beep+xml +# application/calendar+xml +# application/cals-1840 +# application/ccmp+xml +application/ccxml+xml ccxml +application/cdmi-capability cdmia +application/cdmi-container cdmic +application/cdmi-domain cdmid +application/cdmi-object cdmio +application/cdmi-queue cdmiq +# application/cea-2018+xml +# application/cellml+xml +# application/cfw +# application/cnrp+xml +# application/commonground +# application/conference-info+xml +# application/cpl+xml +# application/csta+xml +# application/cstadata+xml +application/cu-seeme cu +# application/cybercash +application/davmount+xml davmount +# application/dca-rft +# application/dec-dx +# application/dialog-info+xml +# application/dicom +# application/dns +application/docbook+xml dbk +# application/dskpp+xml +application/dssc+der dssc +application/dssc+xml xdssc +# application/dvcs +application/ecmascript ecma +# application/edi-consent +# application/edi-x12 +# application/edifact +application/emma+xml emma +# application/epp+xml +application/epub+zip epub +# application/eshop +# application/example +application/exi exi +# application/fastinfoset +# application/fastsoap +# application/fits +application/font-tdpfr pfr +# application/framework-attributes+xml +application/gml+xml gml +application/gpx+xml gpx +application/gxf gxf +# application/h224 +# application/held+xml +# application/http +application/hyperstudio stk +# application/ibe-key-request+xml +# application/ibe-pkg-reply+xml +# application/ibe-pp-data +# application/iges +# application/im-iscomposing+xml +# application/index +# application/index.cmd +# application/index.obj +# application/index.response +# application/index.vnd +application/inkml+xml ink inkml +# application/iotp +application/ipfix ipfix +# application/ipp +# application/isup +application/java-archive jar +application/java-serialized-object ser +application/java-vm class +application/javascript js +application/json json +application/jsonml+json jsonml +# application/kpml-request+xml +# application/kpml-response+xml +application/lost+xml lostxml +application/mac-binhex40 hqx +application/mac-compactpro cpt +# application/macwriteii +application/mads+xml mads +application/marc mrc +application/marcxml+xml mrcx +application/mathematica ma nb mb +# application/mathml-content+xml +# application/mathml-presentation+xml +application/mathml+xml mathml +# application/mbms-associated-procedure-description+xml +# application/mbms-deregister+xml +# application/mbms-envelope+xml +# application/mbms-msk+xml +# application/mbms-msk-response+xml +# application/mbms-protection-description+xml +# application/mbms-reception-report+xml +# application/mbms-register+xml +# application/mbms-register-response+xml +# application/mbms-user-service-description+xml +application/mbox mbox +# application/media_control+xml +application/mediaservercontrol+xml mscml +application/metalink+xml metalink +application/metalink4+xml meta4 +application/mets+xml mets +# application/mikey +application/mods+xml mods +# application/moss-keys +# application/moss-signature +# application/mosskey-data +# application/mosskey-request +application/mp21 m21 mp21 +application/mp4 mp4s +# application/mpeg4-generic +# application/mpeg4-iod +# application/mpeg4-iod-xmt +# application/msc-ivr+xml +# application/msc-mixer+xml +application/msword doc dot +application/mxf mxf +# application/nasdata +# application/news-checkgroups +# application/news-groupinfo +# application/news-transmission +# application/nss +# application/ocsp-request +# application/ocsp-response +application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy +application/oda oda +application/oebps-package+xml opf +application/ogg ogx +application/omdoc+xml omdoc +application/onenote onetoc onetoc2 onetmp onepkg +application/oxps oxps +# application/parityfec +application/patch-ops-error+xml xer +application/pdf pdf +application/pgp-encrypted pgp +# application/pgp-keys +application/pgp-signature asc sig +application/pics-rules prf +# application/pidf+xml +# application/pidf-diff+xml +application/pkcs10 p10 +application/pkcs7-mime p7m p7c +application/pkcs7-signature p7s +application/pkcs8 p8 +application/pkix-attr-cert ac +application/pkix-cert cer +application/pkix-crl crl +application/pkix-pkipath pkipath +application/pkixcmp pki +application/pls+xml pls +# application/poc-settings+xml +application/postscript ai eps ps +# application/prs.alvestrand.titrax-sheet +application/prs.cww cww +# application/prs.nprend +# application/prs.plucker +# application/prs.rdf-xml-crypt +# application/prs.xsf+xml +application/pskc+xml pskcxml +# application/qsig +application/rdf+xml rdf +application/reginfo+xml rif +application/relax-ng-compact-syntax rnc +# application/remote-printing +application/resource-lists+xml rl +application/resource-lists-diff+xml rld +# application/riscos +# application/rlmi+xml +application/rls-services+xml rs +application/rpki-ghostbusters gbr +application/rpki-manifest mft +application/rpki-roa roa +# application/rpki-updown +application/rsd+xml rsd +application/rss+xml rss +application/rtf rtf +# application/rtx +# application/samlassertion+xml +# application/samlmetadata+xml +application/sbml+xml sbml +application/scvp-cv-request scq +application/scvp-cv-response scs +application/scvp-vp-request spq +application/scvp-vp-response spp +application/sdp sdp +# application/set-payment +application/set-payment-initiation setpay +# application/set-registration +application/set-registration-initiation setreg +# application/sgml +# application/sgml-open-catalog +application/shf+xml shf +# application/sieve +# application/simple-filter+xml +# application/simple-message-summary +# application/simplesymbolcontainer +# application/slate +# application/smil +application/smil+xml smi smil +# application/soap+fastinfoset +# application/soap+xml +application/sparql-query rq +application/sparql-results+xml srx +# application/spirits-event+xml +application/srgs gram +application/srgs+xml grxml +application/sru+xml sru +application/ssdl+xml ssdl +application/ssml+xml ssml +# application/tamp-apex-update +# application/tamp-apex-update-confirm +# application/tamp-community-update +# application/tamp-community-update-confirm +# application/tamp-error +# application/tamp-sequence-adjust +# application/tamp-sequence-adjust-confirm +# application/tamp-status-query +# application/tamp-status-response +# application/tamp-update +# application/tamp-update-confirm +application/tei+xml tei teicorpus +application/thraud+xml tfi +# application/timestamp-query +# application/timestamp-reply +application/timestamped-data tsd +# application/tve-trigger +# application/ulpfec +# application/vcard+xml +# application/vemmi +# application/vividence.scriptfile +# application/vnd.3gpp.bsf+xml +application/vnd.3gpp.pic-bw-large plb +application/vnd.3gpp.pic-bw-small psb +application/vnd.3gpp.pic-bw-var pvb +# application/vnd.3gpp.sms +# application/vnd.3gpp2.bcmcsinfo+xml +# application/vnd.3gpp2.sms +application/vnd.3gpp2.tcap tcap +application/vnd.3m.post-it-notes pwn +application/vnd.accpac.simply.aso aso +application/vnd.accpac.simply.imp imp +application/vnd.acucobol acu +application/vnd.acucorp atc acutc +application/vnd.adobe.air-application-installer-package+zip air +application/vnd.adobe.formscentral.fcdt fcdt +application/vnd.adobe.fxp fxp fxpl +# application/vnd.adobe.partial-upload +application/vnd.adobe.xdp+xml xdp +application/vnd.adobe.xfdf xfdf +# application/vnd.aether.imp +# application/vnd.ah-barcode +application/vnd.ahead.space ahead +application/vnd.airzip.filesecure.azf azf +application/vnd.airzip.filesecure.azs azs +application/vnd.amazon.ebook azw +application/vnd.americandynamics.acc acc +application/vnd.amiga.ami ami +# application/vnd.amundsen.maze+xml +application/vnd.android.package-archive apk +application/vnd.anser-web-certificate-issue-initiation cii +application/vnd.anser-web-funds-transfer-initiation fti +application/vnd.antix.game-component atx +application/vnd.apple.installer+xml mpkg +application/vnd.apple.mpegurl m3u8 +# application/vnd.arastra.swi +application/vnd.aristanetworks.swi swi +application/vnd.astraea-software.iota iota +application/vnd.audiograph aep +# application/vnd.autopackage +# application/vnd.avistar+xml +application/vnd.blueice.multipass mpm +# application/vnd.bluetooth.ep.oob +application/vnd.bmi bmi +application/vnd.businessobjects rep +# application/vnd.cab-jscript +# application/vnd.canon-cpdl +# application/vnd.canon-lips +# application/vnd.cendio.thinlinc.clientconf +application/vnd.chemdraw+xml cdxml +application/vnd.chipnuts.karaoke-mmd mmd +application/vnd.cinderella cdy +# application/vnd.cirpack.isdn-ext +application/vnd.claymore cla +application/vnd.cloanto.rp9 rp9 +application/vnd.clonk.c4group c4g c4d c4f c4p c4u +application/vnd.cluetrust.cartomobile-config c11amc +application/vnd.cluetrust.cartomobile-config-pkg c11amz +# application/vnd.collection+json +# application/vnd.commerce-battelle +application/vnd.commonspace csp +application/vnd.contact.cmsg cdbcmsg +application/vnd.cosmocaller cmc +application/vnd.crick.clicker clkx +application/vnd.crick.clicker.keyboard clkk +application/vnd.crick.clicker.palette clkp +application/vnd.crick.clicker.template clkt +application/vnd.crick.clicker.wordbank clkw +application/vnd.criticaltools.wbs+xml wbs +application/vnd.ctc-posml pml +# application/vnd.ctct.ws+xml +# application/vnd.cups-pdf +# application/vnd.cups-postscript +application/vnd.cups-ppd ppd +# application/vnd.cups-raster +# application/vnd.cups-raw +# application/vnd.curl +application/vnd.curl.car car +application/vnd.curl.pcurl pcurl +# application/vnd.cybank +application/vnd.dart dart +application/vnd.data-vision.rdz rdz +application/vnd.dece.data uvf uvvf uvd uvvd +application/vnd.dece.ttml+xml uvt uvvt +application/vnd.dece.unspecified uvx uvvx +application/vnd.dece.zip uvz uvvz +application/vnd.denovo.fcselayout-link fe_launch +# application/vnd.dir-bi.plate-dl-nosuffix +application/vnd.dna dna +application/vnd.dolby.mlp mlp +# application/vnd.dolby.mobile.1 +# application/vnd.dolby.mobile.2 +application/vnd.dpgraph dpg +application/vnd.dreamfactory dfac +application/vnd.ds-keypoint kpxx +application/vnd.dvb.ait ait +# application/vnd.dvb.dvbj +# application/vnd.dvb.esgcontainer +# application/vnd.dvb.ipdcdftnotifaccess +# application/vnd.dvb.ipdcesgaccess +# application/vnd.dvb.ipdcesgaccess2 +# application/vnd.dvb.ipdcesgpdd +# application/vnd.dvb.ipdcroaming +# application/vnd.dvb.iptv.alfec-base +# application/vnd.dvb.iptv.alfec-enhancement +# application/vnd.dvb.notif-aggregate-root+xml +# application/vnd.dvb.notif-container+xml +# application/vnd.dvb.notif-generic+xml +# application/vnd.dvb.notif-ia-msglist+xml +# application/vnd.dvb.notif-ia-registration-request+xml +# application/vnd.dvb.notif-ia-registration-response+xml +# application/vnd.dvb.notif-init+xml +# application/vnd.dvb.pfr +application/vnd.dvb.service svc +# application/vnd.dxr +application/vnd.dynageo geo +# application/vnd.easykaraoke.cdgdownload +# application/vnd.ecdis-update +application/vnd.ecowin.chart mag +# application/vnd.ecowin.filerequest +# application/vnd.ecowin.fileupdate +# application/vnd.ecowin.series +# application/vnd.ecowin.seriesrequest +# application/vnd.ecowin.seriesupdate +# application/vnd.emclient.accessrequest+xml +application/vnd.enliven nml +# application/vnd.eprints.data+xml +application/vnd.epson.esf esf +application/vnd.epson.msf msf +application/vnd.epson.quickanime qam +application/vnd.epson.salt slt +application/vnd.epson.ssf ssf +# application/vnd.ericsson.quickcall +application/vnd.eszigno3+xml es3 et3 +# application/vnd.etsi.aoc+xml +# application/vnd.etsi.cug+xml +# application/vnd.etsi.iptvcommand+xml +# application/vnd.etsi.iptvdiscovery+xml +# application/vnd.etsi.iptvprofile+xml +# application/vnd.etsi.iptvsad-bc+xml +# application/vnd.etsi.iptvsad-cod+xml +# application/vnd.etsi.iptvsad-npvr+xml +# application/vnd.etsi.iptvservice+xml +# application/vnd.etsi.iptvsync+xml +# application/vnd.etsi.iptvueprofile+xml +# application/vnd.etsi.mcid+xml +# application/vnd.etsi.overload-control-policy-dataset+xml +# application/vnd.etsi.sci+xml +# application/vnd.etsi.simservs+xml +# application/vnd.etsi.tsl+xml +# application/vnd.etsi.tsl.der +# application/vnd.eudora.data +application/vnd.ezpix-album ez2 +application/vnd.ezpix-package ez3 +# application/vnd.f-secure.mobile +application/vnd.fdf fdf +application/vnd.fdsn.mseed mseed +application/vnd.fdsn.seed seed dataless +# application/vnd.ffsns +# application/vnd.fints +application/vnd.flographit gph +application/vnd.fluxtime.clip ftc +# application/vnd.font-fontforge-sfd +application/vnd.framemaker fm frame maker book +application/vnd.frogans.fnc fnc +application/vnd.frogans.ltf ltf +application/vnd.fsc.weblaunch fsc +application/vnd.fujitsu.oasys oas +application/vnd.fujitsu.oasys2 oa2 +application/vnd.fujitsu.oasys3 oa3 +application/vnd.fujitsu.oasysgp fg5 +application/vnd.fujitsu.oasysprs bh2 +# application/vnd.fujixerox.art-ex +# application/vnd.fujixerox.art4 +# application/vnd.fujixerox.hbpl +application/vnd.fujixerox.ddd ddd +application/vnd.fujixerox.docuworks xdw +application/vnd.fujixerox.docuworks.binder xbd +# application/vnd.fut-misnet +application/vnd.fuzzysheet fzs +application/vnd.genomatix.tuxedo txd +# application/vnd.geocube+xml +application/vnd.geogebra.file ggb +application/vnd.geogebra.tool ggt +application/vnd.geometry-explorer gex gre +application/vnd.geonext gxt +application/vnd.geoplan g2w +application/vnd.geospace g3w +# application/vnd.globalplatform.card-content-mgt +# application/vnd.globalplatform.card-content-mgt-response +application/vnd.gmx gmx +application/vnd.google-earth.kml+xml kml +application/vnd.google-earth.kmz kmz +application/vnd.grafeq gqf gqs +# application/vnd.gridmp +application/vnd.groove-account gac +application/vnd.groove-help ghf +application/vnd.groove-identity-message gim +application/vnd.groove-injector grv +application/vnd.groove-tool-message gtm +application/vnd.groove-tool-template tpl +application/vnd.groove-vcard vcg +# application/vnd.hal+json +application/vnd.hal+xml hal +application/vnd.handheld-entertainment+xml zmm +application/vnd.hbci hbci +# application/vnd.hcl-bireports +application/vnd.hhe.lesson-player les +application/vnd.hp-hpgl hpgl +application/vnd.hp-hpid hpid +application/vnd.hp-hps hps +application/vnd.hp-jlyt jlt +application/vnd.hp-pcl pcl +application/vnd.hp-pclxl pclxl +# application/vnd.httphone +application/vnd.hydrostatix.sof-data sfd-hdstx +# application/vnd.hzn-3d-crossword +# application/vnd.ibm.afplinedata +# application/vnd.ibm.electronic-media +application/vnd.ibm.minipay mpy +application/vnd.ibm.modcap afp listafp list3820 +application/vnd.ibm.rights-management irm +application/vnd.ibm.secure-container sc +application/vnd.iccprofile icc icm +application/vnd.igloader igl +application/vnd.immervision-ivp ivp +application/vnd.immervision-ivu ivu +# application/vnd.informedcontrol.rms+xml +# application/vnd.informix-visionary +# application/vnd.infotech.project +# application/vnd.infotech.project+xml +# application/vnd.innopath.wamp.notification +application/vnd.insors.igm igm +application/vnd.intercon.formnet xpw xpx +application/vnd.intergeo i2g +# application/vnd.intertrust.digibox +# application/vnd.intertrust.nncp +application/vnd.intu.qbo qbo +application/vnd.intu.qfx qfx +# application/vnd.iptc.g2.conceptitem+xml +# application/vnd.iptc.g2.knowledgeitem+xml +# application/vnd.iptc.g2.newsitem+xml +# application/vnd.iptc.g2.newsmessage+xml +# application/vnd.iptc.g2.packageitem+xml +# application/vnd.iptc.g2.planningitem+xml +application/vnd.ipunplugged.rcprofile rcprofile +application/vnd.irepository.package+xml irp +application/vnd.is-xpr xpr +application/vnd.isac.fcs fcs +application/vnd.jam jam +# application/vnd.japannet-directory-service +# application/vnd.japannet-jpnstore-wakeup +# application/vnd.japannet-payment-wakeup +# application/vnd.japannet-registration +# application/vnd.japannet-registration-wakeup +# application/vnd.japannet-setstore-wakeup +# application/vnd.japannet-verification +# application/vnd.japannet-verification-wakeup +application/vnd.jcp.javame.midlet-rms rms +application/vnd.jisp jisp +application/vnd.joost.joda-archive joda +application/vnd.kahootz ktz ktr +application/vnd.kde.karbon karbon +application/vnd.kde.kchart chrt +application/vnd.kde.kformula kfo +application/vnd.kde.kivio flw +application/vnd.kde.kontour kon +application/vnd.kde.kpresenter kpr kpt +application/vnd.kde.kspread ksp +application/vnd.kde.kword kwd kwt +application/vnd.kenameaapp htke +application/vnd.kidspiration kia +application/vnd.kinar kne knp +application/vnd.koan skp skd skt skm +application/vnd.kodak-descriptor sse +application/vnd.las.las+xml lasxml +# application/vnd.liberty-request+xml +application/vnd.llamagraphics.life-balance.desktop lbd +application/vnd.llamagraphics.life-balance.exchange+xml lbe +application/vnd.lotus-1-2-3 123 +application/vnd.lotus-approach apr +application/vnd.lotus-freelance pre +application/vnd.lotus-notes nsf +application/vnd.lotus-organizer org +application/vnd.lotus-screencam scm +application/vnd.lotus-wordpro lwp +application/vnd.macports.portpkg portpkg +# application/vnd.marlin.drm.actiontoken+xml +# application/vnd.marlin.drm.conftoken+xml +# application/vnd.marlin.drm.license+xml +# application/vnd.marlin.drm.mdcf +application/vnd.mcd mcd +application/vnd.medcalcdata mc1 +application/vnd.mediastation.cdkey cdkey +# application/vnd.meridian-slingshot +application/vnd.mfer mwf +application/vnd.mfmp mfm +application/vnd.micrografx.flo flo +application/vnd.micrografx.igx igx +application/vnd.mif mif +# application/vnd.minisoft-hp3000-save +# application/vnd.mitsubishi.misty-guard.trustweb +application/vnd.mobius.daf daf +application/vnd.mobius.dis dis +application/vnd.mobius.mbk mbk +application/vnd.mobius.mqy mqy +application/vnd.mobius.msl msl +application/vnd.mobius.plc plc +application/vnd.mobius.txf txf +application/vnd.mophun.application mpn +application/vnd.mophun.certificate mpc +# application/vnd.motorola.flexsuite +# application/vnd.motorola.flexsuite.adsi +# application/vnd.motorola.flexsuite.fis +# application/vnd.motorola.flexsuite.gotap +# application/vnd.motorola.flexsuite.kmr +# application/vnd.motorola.flexsuite.ttc +# application/vnd.motorola.flexsuite.wem +# application/vnd.motorola.iprm +application/vnd.mozilla.xul+xml xul +application/vnd.ms-artgalry cil +# application/vnd.ms-asf +application/vnd.ms-cab-compressed cab +# application/vnd.ms-color.iccprofile +application/vnd.ms-excel xls xlm xla xlc xlt xlw +application/vnd.ms-excel.addin.macroenabled.12 xlam +application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb +application/vnd.ms-excel.sheet.macroenabled.12 xlsm +application/vnd.ms-excel.template.macroenabled.12 xltm +application/vnd.ms-fontobject eot +application/vnd.ms-htmlhelp chm +application/vnd.ms-ims ims +application/vnd.ms-lrm lrm +# application/vnd.ms-office.activex+xml +application/vnd.ms-officetheme thmx +# application/vnd.ms-opentype +# application/vnd.ms-package.obfuscated-opentype +application/vnd.ms-pki.seccat cat +application/vnd.ms-pki.stl stl +# application/vnd.ms-playready.initiator+xml +application/vnd.ms-powerpoint ppt pps pot +application/vnd.ms-powerpoint.addin.macroenabled.12 ppam +application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm +application/vnd.ms-powerpoint.slide.macroenabled.12 sldm +application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm +application/vnd.ms-powerpoint.template.macroenabled.12 potm +# application/vnd.ms-printing.printticket+xml +application/vnd.ms-project mpp mpt +# application/vnd.ms-tnef +# application/vnd.ms-wmdrm.lic-chlg-req +# application/vnd.ms-wmdrm.lic-resp +# application/vnd.ms-wmdrm.meter-chlg-req +# application/vnd.ms-wmdrm.meter-resp +application/vnd.ms-word.document.macroenabled.12 docm +application/vnd.ms-word.template.macroenabled.12 dotm +application/vnd.ms-works wps wks wcm wdb +application/vnd.ms-wpl wpl +application/vnd.ms-xpsdocument xps +application/vnd.mseq mseq +# application/vnd.msign +# application/vnd.multiad.creator +# application/vnd.multiad.creator.cif +# application/vnd.music-niff +application/vnd.musician mus +application/vnd.muvee.style msty +application/vnd.mynfc taglet +# application/vnd.ncd.control +# application/vnd.ncd.reference +# application/vnd.nervana +# application/vnd.netfpx +application/vnd.neurolanguage.nlu nlu +application/vnd.nitf ntf nitf +application/vnd.noblenet-directory nnd +application/vnd.noblenet-sealer nns +application/vnd.noblenet-web nnw +# application/vnd.nokia.catalogs +# application/vnd.nokia.conml+wbxml +# application/vnd.nokia.conml+xml +# application/vnd.nokia.isds-radio-presets +# application/vnd.nokia.iptv.config+xml +# application/vnd.nokia.landmark+wbxml +# application/vnd.nokia.landmark+xml +# application/vnd.nokia.landmarkcollection+xml +# application/vnd.nokia.n-gage.ac+xml +application/vnd.nokia.n-gage.data ngdat +application/vnd.nokia.n-gage.symbian.install n-gage +# application/vnd.nokia.ncd +# application/vnd.nokia.pcd+wbxml +# application/vnd.nokia.pcd+xml +application/vnd.nokia.radio-preset rpst +application/vnd.nokia.radio-presets rpss +application/vnd.novadigm.edm edm +application/vnd.novadigm.edx edx +application/vnd.novadigm.ext ext +# application/vnd.ntt-local.file-transfer +# application/vnd.ntt-local.sip-ta_remote +# application/vnd.ntt-local.sip-ta_tcp_stream +application/vnd.oasis.opendocument.chart odc +application/vnd.oasis.opendocument.chart-template otc +application/vnd.oasis.opendocument.database odb +application/vnd.oasis.opendocument.formula odf +application/vnd.oasis.opendocument.formula-template odft +application/vnd.oasis.opendocument.graphics odg +application/vnd.oasis.opendocument.graphics-template otg +application/vnd.oasis.opendocument.image odi +application/vnd.oasis.opendocument.image-template oti +application/vnd.oasis.opendocument.presentation odp +application/vnd.oasis.opendocument.presentation-template otp +application/vnd.oasis.opendocument.spreadsheet ods +application/vnd.oasis.opendocument.spreadsheet-template ots +application/vnd.oasis.opendocument.text odt +application/vnd.oasis.opendocument.text-master odm +application/vnd.oasis.opendocument.text-template ott +application/vnd.oasis.opendocument.text-web oth +# application/vnd.obn +# application/vnd.oftn.l10n+json +# application/vnd.oipf.contentaccessdownload+xml +# application/vnd.oipf.contentaccessstreaming+xml +# application/vnd.oipf.cspg-hexbinary +# application/vnd.oipf.dae.svg+xml +# application/vnd.oipf.dae.xhtml+xml +# application/vnd.oipf.mippvcontrolmessage+xml +# application/vnd.oipf.pae.gem +# application/vnd.oipf.spdiscovery+xml +# application/vnd.oipf.spdlist+xml +# application/vnd.oipf.ueprofile+xml +# application/vnd.oipf.userprofile+xml +application/vnd.olpc-sugar xo +# application/vnd.oma-scws-config +# application/vnd.oma-scws-http-request +# application/vnd.oma-scws-http-response +# application/vnd.oma.bcast.associated-procedure-parameter+xml +# application/vnd.oma.bcast.drm-trigger+xml +# application/vnd.oma.bcast.imd+xml +# application/vnd.oma.bcast.ltkm +# application/vnd.oma.bcast.notification+xml +# application/vnd.oma.bcast.provisioningtrigger +# application/vnd.oma.bcast.sgboot +# application/vnd.oma.bcast.sgdd+xml +# application/vnd.oma.bcast.sgdu +# application/vnd.oma.bcast.simple-symbol-container +# application/vnd.oma.bcast.smartcard-trigger+xml +# application/vnd.oma.bcast.sprov+xml +# application/vnd.oma.bcast.stkm +# application/vnd.oma.cab-address-book+xml +# application/vnd.oma.cab-feature-handler+xml +# application/vnd.oma.cab-pcc+xml +# application/vnd.oma.cab-user-prefs+xml +# application/vnd.oma.dcd +# application/vnd.oma.dcdc +application/vnd.oma.dd2+xml dd2 +# application/vnd.oma.drm.risd+xml +# application/vnd.oma.group-usage-list+xml +# application/vnd.oma.pal+xml +# application/vnd.oma.poc.detailed-progress-report+xml +# application/vnd.oma.poc.final-report+xml +# application/vnd.oma.poc.groups+xml +# application/vnd.oma.poc.invocation-descriptor+xml +# application/vnd.oma.poc.optimized-progress-report+xml +# application/vnd.oma.push +# application/vnd.oma.scidm.messages+xml +# application/vnd.oma.xcap-directory+xml +# application/vnd.omads-email+xml +# application/vnd.omads-file+xml +# application/vnd.omads-folder+xml +# application/vnd.omaloc-supl-init +application/vnd.openofficeorg.extension oxt +# application/vnd.openxmlformats-officedocument.custom-properties+xml +# application/vnd.openxmlformats-officedocument.customxmlproperties+xml +# application/vnd.openxmlformats-officedocument.drawing+xml +# application/vnd.openxmlformats-officedocument.drawingml.chart+xml +# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml +# application/vnd.openxmlformats-officedocument.extended-properties+xml +# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml +# application/vnd.openxmlformats-officedocument.presentationml.comments+xml +# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml +application/vnd.openxmlformats-officedocument.presentationml.presentation pptx +# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml +application/vnd.openxmlformats-officedocument.presentationml.slide sldx +# application/vnd.openxmlformats-officedocument.presentationml.slide+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml +application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx +# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml +# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml +# application/vnd.openxmlformats-officedocument.presentationml.tags+xml +application/vnd.openxmlformats-officedocument.presentationml.template potx +# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx +# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml +# application/vnd.openxmlformats-officedocument.theme+xml +# application/vnd.openxmlformats-officedocument.themeoverride+xml +# application/vnd.openxmlformats-officedocument.vmldrawing +# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.document docx +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx +# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml +# application/vnd.openxmlformats-package.core-properties+xml +# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml +# application/vnd.openxmlformats-package.relationships+xml +# application/vnd.quobject-quoxdocument +# application/vnd.osa.netdeploy +application/vnd.osgeo.mapguide.package mgp +# application/vnd.osgi.bundle +application/vnd.osgi.dp dp +application/vnd.osgi.subsystem esa +# application/vnd.otps.ct-kip+xml +application/vnd.palm pdb pqa oprc +# application/vnd.paos.xml +application/vnd.pawaafile paw +application/vnd.pg.format str +application/vnd.pg.osasli ei6 +# application/vnd.piaccess.application-licence +application/vnd.picsel efif +application/vnd.pmi.widget wg +# application/vnd.poc.group-advertisement+xml +application/vnd.pocketlearn plf +application/vnd.powerbuilder6 pbd +# application/vnd.powerbuilder6-s +# application/vnd.powerbuilder7 +# application/vnd.powerbuilder7-s +# application/vnd.powerbuilder75 +# application/vnd.powerbuilder75-s +# application/vnd.preminet +application/vnd.previewsystems.box box +application/vnd.proteus.magazine mgz +application/vnd.publishare-delta-tree qps +application/vnd.pvi.ptid1 ptid +# application/vnd.pwg-multiplexed +# application/vnd.pwg-xhtml-print+xml +# application/vnd.qualcomm.brew-app-res +application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb +# application/vnd.radisys.moml+xml +# application/vnd.radisys.msml+xml +# application/vnd.radisys.msml-audit+xml +# application/vnd.radisys.msml-audit-conf+xml +# application/vnd.radisys.msml-audit-conn+xml +# application/vnd.radisys.msml-audit-dialog+xml +# application/vnd.radisys.msml-audit-stream+xml +# application/vnd.radisys.msml-conf+xml +# application/vnd.radisys.msml-dialog+xml +# application/vnd.radisys.msml-dialog-base+xml +# application/vnd.radisys.msml-dialog-fax-detect+xml +# application/vnd.radisys.msml-dialog-fax-sendrecv+xml +# application/vnd.radisys.msml-dialog-group+xml +# application/vnd.radisys.msml-dialog-speech+xml +# application/vnd.radisys.msml-dialog-transform+xml +# application/vnd.rainstor.data +# application/vnd.rapid +application/vnd.realvnc.bed bed +application/vnd.recordare.musicxml mxl +application/vnd.recordare.musicxml+xml musicxml +# application/vnd.renlearn.rlprint +application/vnd.rig.cryptonote cryptonote +application/vnd.rim.cod cod +application/vnd.rn-realmedia rm +application/vnd.rn-realmedia-vbr rmvb +application/vnd.route66.link66+xml link66 +# application/vnd.rs-274x +# application/vnd.ruckus.download +# application/vnd.s3sms +application/vnd.sailingtracker.track st +# application/vnd.sbm.cid +# application/vnd.sbm.mid2 +# application/vnd.scribus +# application/vnd.sealed.3df +# application/vnd.sealed.csf +# application/vnd.sealed.doc +# application/vnd.sealed.eml +# application/vnd.sealed.mht +# application/vnd.sealed.net +# application/vnd.sealed.ppt +# application/vnd.sealed.tiff +# application/vnd.sealed.xls +# application/vnd.sealedmedia.softseal.html +# application/vnd.sealedmedia.softseal.pdf +application/vnd.seemail see +application/vnd.sema sema +application/vnd.semd semd +application/vnd.semf semf +application/vnd.shana.informed.formdata ifm +application/vnd.shana.informed.formtemplate itp +application/vnd.shana.informed.interchange iif +application/vnd.shana.informed.package ipk +application/vnd.simtech-mindmapper twd twds +application/vnd.smaf mmf +# application/vnd.smart.notebook +application/vnd.smart.teacher teacher +# application/vnd.software602.filler.form+xml +# application/vnd.software602.filler.form-xml-zip +application/vnd.solent.sdkm+xml sdkm sdkd +application/vnd.spotfire.dxp dxp +application/vnd.spotfire.sfs sfs +# application/vnd.sss-cod +# application/vnd.sss-dtf +# application/vnd.sss-ntf +application/vnd.stardivision.calc sdc +application/vnd.stardivision.draw sda +application/vnd.stardivision.impress sdd +application/vnd.stardivision.math smf +application/vnd.stardivision.writer sdw vor +application/vnd.stardivision.writer-global sgl +application/vnd.stepmania.package smzip +application/vnd.stepmania.stepchart sm +# application/vnd.street-stream +application/vnd.sun.xml.calc sxc +application/vnd.sun.xml.calc.template stc +application/vnd.sun.xml.draw sxd +application/vnd.sun.xml.draw.template std +application/vnd.sun.xml.impress sxi +application/vnd.sun.xml.impress.template sti +application/vnd.sun.xml.math sxm +application/vnd.sun.xml.writer sxw +application/vnd.sun.xml.writer.global sxg +application/vnd.sun.xml.writer.template stw +# application/vnd.sun.wadl+xml +application/vnd.sus-calendar sus susp +application/vnd.svd svd +# application/vnd.swiftview-ics +application/vnd.symbian.install sis sisx +application/vnd.syncml+xml xsm +application/vnd.syncml.dm+wbxml bdm +application/vnd.syncml.dm+xml xdm +# application/vnd.syncml.dm.notification +# application/vnd.syncml.ds.notification +application/vnd.tao.intent-module-archive tao +application/vnd.tcpdump.pcap pcap cap dmp +application/vnd.tmobile-livetv tmo +application/vnd.trid.tpt tpt +application/vnd.triscape.mxs mxs +application/vnd.trueapp tra +# application/vnd.truedoc +# application/vnd.ubisoft.webplayer +application/vnd.ufdl ufd ufdl +application/vnd.uiq.theme utz +application/vnd.umajin umj +application/vnd.unity unityweb +application/vnd.uoml+xml uoml +# application/vnd.uplanet.alert +# application/vnd.uplanet.alert-wbxml +# application/vnd.uplanet.bearer-choice +# application/vnd.uplanet.bearer-choice-wbxml +# application/vnd.uplanet.cacheop +# application/vnd.uplanet.cacheop-wbxml +# application/vnd.uplanet.channel +# application/vnd.uplanet.channel-wbxml +# application/vnd.uplanet.list +# application/vnd.uplanet.list-wbxml +# application/vnd.uplanet.listcmd +# application/vnd.uplanet.listcmd-wbxml +# application/vnd.uplanet.signal +application/vnd.vcx vcx +# application/vnd.vd-study +# application/vnd.vectorworks +# application/vnd.verimatrix.vcas +# application/vnd.vidsoft.vidconference +application/vnd.visio vsd vst vss vsw +application/vnd.visionary vis +# application/vnd.vividence.scriptfile +application/vnd.vsf vsf +# application/vnd.wap.sic +# application/vnd.wap.slc +application/vnd.wap.wbxml wbxml +application/vnd.wap.wmlc wmlc +application/vnd.wap.wmlscriptc wmlsc +application/vnd.webturbo wtb +# application/vnd.wfa.wsc +# application/vnd.wmc +# application/vnd.wmf.bootstrap +# application/vnd.wolfram.mathematica +# application/vnd.wolfram.mathematica.package +application/vnd.wolfram.player nbp +application/vnd.wordperfect wpd +application/vnd.wqd wqd +# application/vnd.wrq-hp3000-labelled +application/vnd.wt.stf stf +# application/vnd.wv.csp+wbxml +# application/vnd.wv.csp+xml +# application/vnd.wv.ssp+xml +application/vnd.xara xar +application/vnd.xfdl xfdl +# application/vnd.xfdl.webform +# application/vnd.xmi+xml +# application/vnd.xmpie.cpkg +# application/vnd.xmpie.dpkg +# application/vnd.xmpie.plan +# application/vnd.xmpie.ppkg +# application/vnd.xmpie.xlim +application/vnd.yamaha.hv-dic hvd +application/vnd.yamaha.hv-script hvs +application/vnd.yamaha.hv-voice hvp +application/vnd.yamaha.openscoreformat osf +application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg +# application/vnd.yamaha.remote-setup +application/vnd.yamaha.smaf-audio saf +application/vnd.yamaha.smaf-phrase spf +# application/vnd.yamaha.through-ngn +# application/vnd.yamaha.tunnel-udpencap +application/vnd.yellowriver-custom-menu cmp +application/vnd.zul zir zirz +application/vnd.zzazz.deck+xml zaz +application/voicexml+xml vxml +# application/vq-rtcpxr +# application/watcherinfo+xml +# application/whoispp-query +# application/whoispp-response +application/widget wgt +application/winhlp hlp +# application/wita +# application/wordperfect5.1 +application/wsdl+xml wsdl +application/wspolicy+xml wspolicy +application/x-7z-compressed 7z +application/x-abiword abw +application/x-ace-compressed ace +# application/x-amf +application/x-apple-diskimage dmg +application/x-authorware-bin aab x32 u32 vox +application/x-authorware-map aam +application/x-authorware-seg aas +application/x-bcpio bcpio +application/x-bittorrent torrent +application/x-blorb blb blorb +application/x-bzip bz +application/x-bzip2 bz2 boz +application/x-cbr cbr cba cbt cbz cb7 +application/x-cdlink vcd +application/x-cfs-compressed cfs +application/x-chat chat +application/x-chess-pgn pgn +application/x-conference nsc +# application/x-compress +application/x-cpio cpio +application/x-csh csh +application/x-debian-package deb udeb +application/x-dgc-compressed dgc +application/x-director dir dcr dxr cst cct cxt w3d fgd swa +application/x-doom wad +application/x-dtbncx+xml ncx +application/x-dtbook+xml dtb +application/x-dtbresource+xml res +application/x-dvi dvi +application/x-envoy evy +application/x-eva eva +application/x-font-bdf bdf +# application/x-font-dos +# application/x-font-framemaker +application/x-font-ghostscript gsf +# application/x-font-libgrx +application/x-font-linux-psf psf +application/x-font-otf otf +application/x-font-pcf pcf +application/x-font-snf snf +# application/x-font-speedo +# application/x-font-sunos-news +application/x-font-ttf ttf ttc +application/x-font-type1 pfa pfb pfm afm +application/font-woff woff +# application/x-font-vfont +application/x-freearc arc +application/x-futuresplash spl +application/x-gca-compressed gca +application/x-glulx ulx +application/x-gnumeric gnumeric +application/x-gramps-xml gramps +application/x-gtar gtar +# application/x-gzip +application/x-hdf hdf +application/x-install-instructions install +application/x-iso9660-image iso +application/x-java-jnlp-file jnlp +application/x-latex latex +application/x-lzh-compressed lzh lha +application/x-mie mie +application/x-mobipocket-ebook prc mobi +application/x-ms-application application +application/x-ms-shortcut lnk +application/x-ms-wmd wmd +application/x-ms-wmz wmz +application/x-ms-xbap xbap +application/x-msaccess mdb +application/x-msbinder obd +application/x-mscardfile crd +application/x-msclip clp +application/x-msdownload exe dll com bat msi +application/x-msmediaview mvb m13 m14 +application/x-msmetafile wmf wmz emf emz +application/x-msmoney mny +application/x-mspublisher pub +application/x-msschedule scd +application/x-msterminal trm +application/x-mswrite wri +application/x-netcdf nc cdf +application/x-nzb nzb +application/x-pkcs12 p12 pfx +application/x-pkcs7-certificates p7b spc +application/x-pkcs7-certreqresp p7r +application/x-rar-compressed rar +application/x-research-info-systems ris +application/x-sh sh +application/x-shar shar +application/x-shockwave-flash swf +application/x-silverlight-app xap +application/x-sql sql +application/x-stuffit sit +application/x-stuffitx sitx +application/x-subrip srt +application/x-sv4cpio sv4cpio +application/x-sv4crc sv4crc +application/x-t3vm-image t3 +application/x-tads gam +application/x-tar tar +application/x-tcl tcl +application/x-tex tex +application/x-tex-tfm tfm +application/x-texinfo texinfo texi +application/x-tgif obj +application/x-ustar ustar +application/x-wais-source src +application/x-x509-ca-cert der crt +application/x-xfig fig +application/x-xliff+xml xlf +application/x-xpinstall xpi +application/x-xz xz +application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 +# application/x400-bp +application/xaml+xml xaml +# application/xcap-att+xml +# application/xcap-caps+xml +application/xcap-diff+xml xdf +# application/xcap-el+xml +# application/xcap-error+xml +# application/xcap-ns+xml +# application/xcon-conference-info-diff+xml +# application/xcon-conference-info+xml +application/xenc+xml xenc +application/xhtml+xml xhtml xht +# application/xhtml-voice+xml +application/xml xml xsl +application/xml-dtd dtd +# application/xml-external-parsed-entity +# application/xmpp+xml +application/xop+xml xop +application/xproc+xml xpl +application/xslt+xml xslt +application/xspf+xml xspf +application/xv+xml mxml xhvml xvml xvm +application/yang yang +application/yin+xml yin +application/zip zip +# audio/1d-interleaved-parityfec +# audio/32kadpcm +# audio/3gpp +# audio/3gpp2 +# audio/ac3 +audio/adpcm adp +# audio/amr +# audio/amr-wb +# audio/amr-wb+ +# audio/asc +# audio/atrac-advanced-lossless +# audio/atrac-x +# audio/atrac3 +audio/basic au snd +# audio/bv16 +# audio/bv32 +# audio/clearmode +# audio/cn +# audio/dat12 +# audio/dls +# audio/dsr-es201108 +# audio/dsr-es202050 +# audio/dsr-es202211 +# audio/dsr-es202212 +# audio/dv +# audio/dvi4 +# audio/eac3 +# audio/evrc +# audio/evrc-qcp +# audio/evrc0 +# audio/evrc1 +# audio/evrcb +# audio/evrcb0 +# audio/evrcb1 +# audio/evrcwb +# audio/evrcwb0 +# audio/evrcwb1 +# audio/example +# audio/fwdred +# audio/g719 +# audio/g722 +# audio/g7221 +# audio/g723 +# audio/g726-16 +# audio/g726-24 +# audio/g726-32 +# audio/g726-40 +# audio/g728 +# audio/g729 +# audio/g7291 +# audio/g729d +# audio/g729e +# audio/gsm +# audio/gsm-efr +# audio/gsm-hr-08 +# audio/ilbc +# audio/ip-mr_v2.5 +# audio/isac +# audio/l16 +# audio/l20 +# audio/l24 +# audio/l8 +# audio/lpc +audio/midi mid midi kar rmi +# audio/mobile-xmf +audio/mp4 mp4a +# audio/mp4a-latm +# audio/mpa +# audio/mpa-robust +audio/mpeg mpga mp2 mp2a mp3 m2a m3a +# audio/mpeg4-generic +# audio/musepack +audio/ogg oga ogg spx +# audio/opus +# audio/parityfec +# audio/pcma +# audio/pcma-wb +# audio/pcmu-wb +# audio/pcmu +# audio/prs.sid +# audio/qcelp +# audio/red +# audio/rtp-enc-aescm128 +# audio/rtp-midi +# audio/rtx +audio/s3m s3m +audio/silk sil +# audio/smv +# audio/smv0 +# audio/smv-qcp +# audio/sp-midi +# audio/speex +# audio/t140c +# audio/t38 +# audio/telephone-event +# audio/tone +# audio/uemclip +# audio/ulpfec +# audio/vdvi +# audio/vmr-wb +# audio/vnd.3gpp.iufp +# audio/vnd.4sb +# audio/vnd.audiokoz +# audio/vnd.celp +# audio/vnd.cisco.nse +# audio/vnd.cmles.radio-events +# audio/vnd.cns.anp1 +# audio/vnd.cns.inf1 +audio/vnd.dece.audio uva uvva +audio/vnd.digital-winds eol +# audio/vnd.dlna.adts +# audio/vnd.dolby.heaac.1 +# audio/vnd.dolby.heaac.2 +# audio/vnd.dolby.mlp +# audio/vnd.dolby.mps +# audio/vnd.dolby.pl2 +# audio/vnd.dolby.pl2x +# audio/vnd.dolby.pl2z +# audio/vnd.dolby.pulse.1 +audio/vnd.dra dra +audio/vnd.dts dts +audio/vnd.dts.hd dtshd +# audio/vnd.dvb.file +# audio/vnd.everad.plj +# audio/vnd.hns.audio +audio/vnd.lucent.voice lvp +audio/vnd.ms-playready.media.pya pya +# audio/vnd.nokia.mobile-xmf +# audio/vnd.nortel.vbk +audio/vnd.nuera.ecelp4800 ecelp4800 +audio/vnd.nuera.ecelp7470 ecelp7470 +audio/vnd.nuera.ecelp9600 ecelp9600 +# audio/vnd.octel.sbc +# audio/vnd.qcelp +# audio/vnd.rhetorex.32kadpcm +audio/vnd.rip rip +# audio/vnd.sealedmedia.softseal.mpeg +# audio/vnd.vmx.cvsd +# audio/vorbis +# audio/vorbis-config +audio/webm weba +audio/x-aac aac +audio/x-aiff aif aiff aifc +audio/x-caf caf +audio/x-flac flac +audio/x-matroska mka +audio/x-mpegurl m3u +audio/x-ms-wax wax +audio/x-ms-wma wma +audio/x-pn-realaudio ram ra +audio/x-pn-realaudio-plugin rmp +# audio/x-tta +audio/x-wav wav +audio/xm xm +chemical/x-cdx cdx +chemical/x-cif cif +chemical/x-cmdf cmdf +chemical/x-cml cml +chemical/x-csml csml +# chemical/x-pdb +chemical/x-xyz xyz +image/bmp bmp +image/cgm cgm +# image/example +# image/fits +image/g3fax g3 +image/gif gif +image/ief ief +# image/jp2 +image/jpeg jpeg jpg jpe +# image/jpm +# image/jpx +image/ktx ktx +# image/naplps +image/png png +image/prs.btif btif +# image/prs.pti +image/sgi sgi +image/svg+xml svg svgz +# image/t38 +image/tiff tiff tif +# image/tiff-fx +image/vnd.adobe.photoshop psd +# image/vnd.cns.inf2 +image/vnd.dece.graphic uvi uvvi uvg uvvg +image/vnd.dvb.subtitle sub +image/vnd.djvu djvu djv +image/vnd.dwg dwg +image/vnd.dxf dxf +image/vnd.fastbidsheet fbs +image/vnd.fpx fpx +image/vnd.fst fst +image/vnd.fujixerox.edmics-mmr mmr +image/vnd.fujixerox.edmics-rlc rlc +# image/vnd.globalgraphics.pgb +# image/vnd.microsoft.icon +# image/vnd.mix +image/vnd.ms-modi mdi +image/vnd.ms-photo wdp +image/vnd.net-fpx npx +# image/vnd.radiance +# image/vnd.sealed.png +# image/vnd.sealedmedia.softseal.gif +# image/vnd.sealedmedia.softseal.jpg +# image/vnd.svf +image/vnd.wap.wbmp wbmp +image/vnd.xiff xif +image/webp webp +image/x-3ds 3ds +image/x-cmu-raster ras +image/x-cmx cmx +image/x-freehand fh fhc fh4 fh5 fh7 +image/x-icon ico +image/x-mrsid-image sid +image/x-pcx pcx +image/x-pict pic pct +image/x-portable-anymap pnm +image/x-portable-bitmap pbm +image/x-portable-graymap pgm +image/x-portable-pixmap ppm +image/x-rgb rgb +image/x-tga tga +image/x-xbitmap xbm +image/x-xpixmap xpm +image/x-xwindowdump xwd +# message/cpim +# message/delivery-status +# message/disposition-notification +# message/example +# message/external-body +# message/feedback-report +# message/global +# message/global-delivery-status +# message/global-disposition-notification +# message/global-headers +# message/http +# message/imdn+xml +# message/news +# message/partial +message/rfc822 eml mime +# message/s-http +# message/sip +# message/sipfrag +# message/tracking-status +# message/vnd.si.simp +# model/example +model/iges igs iges +model/mesh msh mesh silo +model/vnd.collada+xml dae +model/vnd.dwf dwf +# model/vnd.flatland.3dml +model/vnd.gdl gdl +# model/vnd.gs-gdl +# model/vnd.gs.gdl +model/vnd.gtw gtw +# model/vnd.moml+xml +model/vnd.mts mts +# model/vnd.parasolid.transmit.binary +# model/vnd.parasolid.transmit.text +model/vnd.vtu vtu +model/vrml wrl vrml +model/x3d+binary x3db x3dbz +model/x3d+vrml x3dv x3dvz +model/x3d+xml x3d x3dz +# multipart/alternative +# multipart/appledouble +# multipart/byteranges +# multipart/digest +# multipart/encrypted +# multipart/example +# multipart/form-data +# multipart/header-set +# multipart/mixed +# multipart/parallel +# multipart/related +# multipart/report +# multipart/signed +# multipart/voice-message +# text/1d-interleaved-parityfec +text/cache-manifest appcache +text/calendar ics ifb +text/css css +text/csv csv +# text/directory +# text/dns +# text/ecmascript +# text/enriched +# text/example +# text/fwdred +text/html html htm +# text/javascript +text/n3 n3 +# text/parityfec +text/plain txt text conf def list log in +# text/prs.fallenstein.rst +text/prs.lines.tag dsc +# text/vnd.radisys.msml-basic-layout +# text/red +# text/rfc822-headers +text/richtext rtx +# text/rtf +# text/rtp-enc-aescm128 +# text/rtx +text/sgml sgml sgm +# text/t140 +text/tab-separated-values tsv +text/troff t tr roff man me ms +text/turtle ttl +# text/ulpfec +text/uri-list uri uris urls +text/vcard vcard +# text/vnd.abc +text/vnd.curl curl +text/vnd.curl.dcurl dcurl +text/vnd.curl.scurl scurl +text/vnd.curl.mcurl mcurl +# text/vnd.dmclientscript +text/vnd.dvb.subtitle sub +# text/vnd.esmertec.theme-descriptor +text/vnd.fly fly +text/vnd.fmi.flexstor flx +text/vnd.graphviz gv +text/vnd.in3d.3dml 3dml +text/vnd.in3d.spot spot +# text/vnd.iptc.newsml +# text/vnd.iptc.nitf +# text/vnd.latex-z +# text/vnd.motorola.reflex +# text/vnd.ms-mediapackage +# text/vnd.net2phone.commcenter.command +# text/vnd.si.uricatalogue +text/vnd.sun.j2me.app-descriptor jad +# text/vnd.trolltech.linguist +# text/vnd.wap.si +# text/vnd.wap.sl +text/vnd.wap.wml wml +text/vnd.wap.wmlscript wmls +text/x-asm s asm +text/x-c c cc cxx cpp h hh dic +text/x-fortran f for f77 f90 +text/x-java-source java +text/x-opml opml +text/x-pascal p pas +text/x-nfo nfo +text/x-setext etx +text/x-sfv sfv +text/x-uuencode uu +text/x-vcalendar vcs +text/x-vcard vcf +# text/xml +# text/xml-external-parsed-entity +# video/1d-interleaved-parityfec +video/3gpp 3gp +# video/3gpp-tt +video/3gpp2 3g2 +# video/bmpeg +# video/bt656 +# video/celb +# video/dv +# video/example +video/h261 h261 +video/h263 h263 +# video/h263-1998 +# video/h263-2000 +video/h264 h264 +# video/h264-rcdo +# video/h264-svc +video/jpeg jpgv +# video/jpeg2000 +video/jpm jpm jpgm +video/mj2 mj2 mjp2 +# video/mp1s +# video/mp2p +# video/mp2t +video/mp4 mp4 mp4v mpg4 +# video/mp4v-es +video/mpeg mpeg mpg mpe m1v m2v +# video/mpeg4-generic +# video/mpv +# video/nv +video/ogg ogv +# video/parityfec +# video/pointer +video/quicktime qt mov +# video/raw +# video/rtp-enc-aescm128 +# video/rtx +# video/smpte292m +# video/ulpfec +# video/vc1 +# video/vnd.cctv +video/vnd.dece.hd uvh uvvh +video/vnd.dece.mobile uvm uvvm +# video/vnd.dece.mp4 +video/vnd.dece.pd uvp uvvp +video/vnd.dece.sd uvs uvvs +video/vnd.dece.video uvv uvvv +# video/vnd.directv.mpeg +# video/vnd.directv.mpeg-tts +# video/vnd.dlna.mpeg-tts +video/vnd.dvb.file dvb +video/vnd.fvt fvt +# video/vnd.hns.video +# video/vnd.iptvforum.1dparityfec-1010 +# video/vnd.iptvforum.1dparityfec-2005 +# video/vnd.iptvforum.2dparityfec-1010 +# video/vnd.iptvforum.2dparityfec-2005 +# video/vnd.iptvforum.ttsavc +# video/vnd.iptvforum.ttsmpeg2 +# video/vnd.motorola.video +# video/vnd.motorola.videop +video/vnd.mpegurl mxu m4u +video/vnd.ms-playready.media.pyv pyv +# video/vnd.nokia.interleaved-multimedia +# video/vnd.nokia.videovoip +# video/vnd.objectvideo +# video/vnd.sealed.mpeg1 +# video/vnd.sealed.mpeg4 +# video/vnd.sealed.swf +# video/vnd.sealedmedia.softseal.mov +video/vnd.uvvu.mp4 uvu uvvu +video/vnd.vivo viv +video/webm webm +video/x-f4v f4v +video/x-fli fli +video/x-flv flv +video/x-m4v m4v +video/x-matroska mkv mk3d mks +video/x-mng mng +video/x-ms-asf asf asx +video/x-ms-vob vob +video/x-ms-wm wm +video/x-ms-wmv wmv +video/x-ms-wmx wmx +video/x-ms-wvx wvx +video/x-msvideo avi +video/x-sgi-movie movie +video/x-smv smv +x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/node.types b/node_modules/express/node_modules/send/node_modules/mime/types/node.types new file mode 100644 index 000000000..55b2cf794 --- /dev/null +++ b/node_modules/express/node_modules/send/node_modules/mime/types/node.types @@ -0,0 +1,77 @@ +# What: WebVTT +# Why: To allow formats intended for marking up external text track resources. +# http://dev.w3.org/html5/webvtt/ +# Added by: niftylettuce +text/vtt vtt + +# What: Google Chrome Extension +# Why: To allow apps to (work) be served with the right content type header. +# http://codereview.chromium.org/2830017 +# Added by: niftylettuce +application/x-chrome-extension crx + +# What: HTC support +# Why: To properly render .htc files such as CSS3PIE +# Added by: niftylettuce +text/x-component htc + +# What: HTML5 application cache manifes ('.manifest' extension) +# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps +# per https://developer.mozilla.org/en/offline_resources_in_firefox +# Added by: louisremi +text/cache-manifest manifest + +# What: node binary buffer format +# Why: semi-standard extension w/in the node community +# Added by: tootallnate +application/octet-stream buffer + +# What: The "protected" MP-4 formats used by iTunes. +# Why: Required for streaming music to browsers (?) +# Added by: broofa +application/mp4 m4p +audio/mp4 m4a + +# What: Video format, Part of RFC1890 +# Why: See https://github.com/bentomas/node-mime/pull/6 +# Added by: mjrusso +video/MP2T ts + +# What: EventSource mime type +# Why: mime type of Server-Sent Events stream +# http://www.w3.org/TR/eventsource/#text-event-stream +# Added by: francois2metz +text/event-stream event-stream + +# What: Mozilla App manifest mime type +# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests +# Added by: ednapiranha +application/x-web-app-manifest+json webapp + +# What: Lua file types +# Why: Googling around shows de-facto consensus on these +# Added by: creationix (Issue #45) +text/x-lua lua +application/x-lua-bytecode luac + +# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax +# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown +# Added by: avoidwork +text/x-markdown markdown md mkd + +# What: ini files +# Why: because they're just text files +# Added by: Matthew Kastor +text/plain ini + +# What: DASH Adaptive Streaming manifest +# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video +# Added by: eelcocramer +application/dash+xml mdp + +# What: OpenType font files - http://www.microsoft.com/typography/otspec/ +# Why: Browsers usually ignore the font MIME types and sniff the content, +# but Chrome, shows a warning if OpenType fonts aren't served with +# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. +# Added by: alrra +font/opentype otf diff --git a/node_modules/express/node_modules/send/package.json b/node_modules/express/node_modules/send/package.json new file mode 100644 index 000000000..779e2df16 --- /dev/null +++ b/node_modules/express/node_modules/send/package.json @@ -0,0 +1,65 @@ +{ + "name": "send", + "version": "0.3.0", + "description": "Better streaming static file server with Range and conditional-GET support", + "keywords": [ + "static", + "file", + "server" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": { + "buffer-crc32": "0.2.1", + "debug": "0.8.0", + "fresh": "~0.2.1", + "mime": "1.2.11", + "range-parser": "~1.0.0" + }, + "devDependencies": { + "mocha": "*", + "should": "*", + "supertest": "0.10.0", + "connect": "2.x" + }, + "scripts": { + "test": "mocha --require should --reporter spec --bail" + }, + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/send.git" + }, + "main": "index", + "bugs": { + "url": "https://github.com/visionmedia/send/issues" + }, + "homepage": "https://github.com/visionmedia/send", + "_id": "send@0.3.0", + "dist": { + "shasum": "9718324634806fc75bc4f8f5e51f57d9d66606e7", + "tarball": "http://registry.npmjs.org/send/-/send-0.3.0.tgz" + }, + "_from": "send@0.3.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "directories": {}, + "_shasum": "9718324634806fc75bc4f8f5e51f57d9d66606e7", + "_resolved": "https://registry.npmjs.org/send/-/send-0.3.0.tgz", + "readme": "# send\n\n Send is Connect's `static()` extracted for generalized use, a streaming static file\n server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework.\n\n## Installation\n\n $ npm install send\n\n## Examples\n\n Small:\n\n```js\nvar http = require('http');\nvar send = require('send');\n\nvar app = http.createServer(function(req, res){\n send(req, req.url).pipe(res);\n}).listen(3000);\n```\n\n Serving from a root directory with custom error-handling:\n\n```js\nvar http = require('http');\nvar send = require('send');\nvar url = require('url');\n\nvar app = http.createServer(function(req, res){\n // your custom error-handling logic:\n function error(err) {\n res.statusCode = err.status || 500;\n res.end(err.message);\n }\n\n // your custom directory handling logic:\n function redirect() {\n res.statusCode = 301;\n res.setHeader('Location', req.url + '/');\n res.end('Redirecting to ' + req.url + '/');\n }\n\n // transfer arbitrary files from within\n // /www/example.com/public/*\n send(req, url.parse(req.url).pathname, {root: '/www/example.com/public'})\n .on('error', error)\n .on('directory', redirect)\n .pipe(res);\n}).listen(3000);\n```\n\n## API\n\n### Options\n\n#### etag\n\n Enable or disable etag generation, defaults to true.\n\n#### hidden\n\n Enable or disable transfer of hidden files, defaults to false.\n\n#### index\n\n By default send supports \"index.html\" files, to disable this\n set `false` or to supply a new index pass a string or an array\n in preferred order.\n\n#### maxage\n\n Provide a max-age in milliseconds for http caching, defaults to 0.\n\n#### root\n\n Serve files relative to `path`.\n\n### Events\n\n - `error` an error occurred `(err)`\n - `directory` a directory was requested\n - `file` a file was requested `(path, stat)`\n - `stream` file streaming has started `(stream)`\n - `end` streaming has completed\n\n### .etag(bool)\n\n Enable or disable etag generation, defaults to true.\n\n### .root(dir)\n\n Serve files relative to `path`. Aliased as `.from(dir)`.\n\n### .index(paths)\n\n By default send supports \"index.html\" files, to disable this\n invoke `.index(false)` or to supply a new index pass a string\n or an array in preferred order.\n\n### .maxage(ms)\n\n Provide a max-age in milliseconds for http caching, defaults to 0.\n\n### .hidden(bool)\n\n Enable or disable transfer of hidden files, defaults to false.\n\n## Error-handling\n\n By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc.\n\n## Caching\n\n It does _not_ perform internal caching, you should use a reverse proxy cache such\n as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;).\n\n## Debugging\n\n To enable `debug()` instrumentation output export __DEBUG__:\n\n```\n$ DEBUG=send node app\n```\n\n## Running tests\n\n```\n$ npm install\n$ make test\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "Readme.md" +} diff --git a/node_modules/express/node_modules/serve-static/.npmignore b/node_modules/express/node_modules/serve-static/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/express/node_modules/serve-static/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/express/node_modules/serve-static/.travis.yml b/node_modules/express/node_modules/serve-static/.travis.yml new file mode 100644 index 000000000..99cdc7439 --- /dev/null +++ b/node_modules/express/node_modules/serve-static/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" diff --git a/node_modules/express/node_modules/serve-static/History.md b/node_modules/express/node_modules/serve-static/History.md new file mode 100644 index 000000000..442e1d3ed --- /dev/null +++ b/node_modules/express/node_modules/serve-static/History.md @@ -0,0 +1,31 @@ +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/node_modules/express/node_modules/serve-static/LICENSE b/node_modules/express/node_modules/serve-static/LICENSE new file mode 100644 index 000000000..b7bc0852e --- /dev/null +++ b/node_modules/express/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014 Douglas Christopher Wilson + +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/express/node_modules/serve-static/Readme.md b/node_modules/express/node_modules/serve-static/Readme.md new file mode 100644 index 000000000..af1caaaca --- /dev/null +++ b/node_modules/express/node_modules/serve-static/Readme.md @@ -0,0 +1,41 @@ +# Serve Static + +Previously `connect.static()`. + +[![Build Status](https://travis-ci.org/expressjs/serve-static.svg?branch=master)](https://travis-ci.org/expressjs/serve-static) + +Usage: + +```js +var connect = require('connect'); +var serveStatic = require('serve-static'); + +var app = connect(); + +app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})); +app.listen(); +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/express/node_modules/serve-static/index.js b/node_modules/express/node_modules/serve-static/index.js new file mode 100644 index 000000000..d0043fb7a --- /dev/null +++ b/node_modules/express/node_modules/serve-static/index.js @@ -0,0 +1,139 @@ +/*! + * Connect - static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var parseurl = require('parseurl'); +var resolve = require('path').resolve; +var send = require('send'); +var url = require('url'); + +/** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * var serveStatic = require('serve-static'); + * + * connect() + * .use(serveStatic(__dirname + '/public')) + * + * connect() + * .use(serveStatic(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * - `index` Default file name, defaults to 'index.html' + * + * Further options are forwarded on to `send`. + * + * @param {String} root + * @param {Object} options + * @return {Function} + * @api public + */ + +exports = module.exports = function(root, options){ + options = extend({}, options); + + // root required + if (!root) throw new TypeError('root path required'); + + // resolve root to absolute + root = resolve(root); + + // default redirect + var redirect = false !== options.redirect; + + // setup options for send + options.maxage = options.maxage || options.maxAge || 0; + options.root = root; + + return function staticMiddleware(req, res, next) { + if ('GET' != req.method && 'HEAD' != req.method) return next(); + var opts = extend({}, options); + var originalUrl = url.parse(req.originalUrl || req.url); + var path = parseurl(req).pathname; + + if (path == '/' && originalUrl.pathname[originalUrl.pathname.length - 1] != '/') { + return directory(); + } + + function directory() { + if (!redirect) return next(); + var target; + originalUrl.pathname += '/'; + target = url.format(originalUrl); + res.statusCode = 303; + res.setHeader('Location', target); + res.end('Redirecting to ' + escape(target)); + } + + function error(err) { + if (404 == err.status) return next(); + next(err); + } + + send(req, path, opts) + .on('error', error) + .on('directory', directory) + .pipe(res); + }; +}; + +/** + * Expose mime module. + * + * If you wish to extend the mime table use this + * reference to the "mime" module in the npm registry. + */ + +exports.mime = send.mime; + +/** + * Escape the given string of `html`. + * + * @param {String} html + * @return {String} + * @api private + */ + +function escape(html) { + return String(html) + .replace(/&(?!\w+;)/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +}; + +/** + * Shallow clone a single object. + * + * @param {Object} obj + * @param {Object} source + * @return {Object} + * @api private + */ + +function extend(obj, source) { + if (!source) return obj; + + for (var prop in source) { + obj[prop] = source[prop]; + } + + return obj; +}; diff --git a/node_modules/express/node_modules/serve-static/package.json b/node_modules/express/node_modules/serve-static/package.json new file mode 100644 index 000000000..e200ce2a1 --- /dev/null +++ b/node_modules/express/node_modules/serve-static/package.json @@ -0,0 +1,72 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/serve-static.git" + }, + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "dependencies": { + "parseurl": "1.0.1", + "send": "0.3.0" + }, + "devDependencies": { + "connect": "~2.14.1", + "mocha": "~1.18.2", + "should": "~3.3.0", + "supertest": "~0.11.0" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --require should" + }, + "homepage": "https://github.com/expressjs/serve-static", + "_id": "serve-static@1.1.0", + "dist": { + "shasum": "454dfa05bb3ddd4e701a8915b83a278aa91c5643", + "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.1.0.tgz" + }, + "_from": "serve-static@1.1.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + } + ], + "directories": {}, + "_shasum": "454dfa05bb3ddd4e701a8915b83a278aa91c5643", + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.1.0.tgz", + "readme": "# Serve Static\n\nPreviously `connect.static()`.\n\n[![Build Status](https://travis-ci.org/expressjs/serve-static.svg?branch=master)](https://travis-ci.org/expressjs/serve-static)\n\nUsage:\n\n```js\nvar connect = require('connect');\nvar serveStatic = require('serve-static');\n\nvar app = connect();\n\napp.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}));\napp.listen();\n```\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Douglas Christopher Wilson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", + "readmeFilename": "Readme.md" +} diff --git a/node_modules/express/node_modules/type-is/.npmignore b/node_modules/express/node_modules/type-is/.npmignore new file mode 100644 index 000000000..602eb8e1b --- /dev/null +++ b/node_modules/express/node_modules/type-is/.npmignore @@ -0,0 +1 @@ +test.js \ No newline at end of file diff --git a/node_modules/express/node_modules/type-is/.travis.yml b/node_modules/express/node_modules/type-is/.travis.yml new file mode 100644 index 000000000..3e3646a12 --- /dev/null +++ b/node_modules/express/node_modules/type-is/.travis.yml @@ -0,0 +1,4 @@ +node_js: +- "0.10" +- "0.11" +language: node_js \ No newline at end of file diff --git a/node_modules/express/node_modules/type-is/HISTORY.md b/node_modules/express/node_modules/type-is/HISTORY.md new file mode 100644 index 000000000..d20fe7789 --- /dev/null +++ b/node_modules/express/node_modules/type-is/HISTORY.md @@ -0,0 +1,16 @@ + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/express/node_modules/type-is/README.md b/node_modules/express/node_modules/type-is/README.md new file mode 100644 index 000000000..4e2971f0d --- /dev/null +++ b/node_modules/express/node_modules/type-is/README.md @@ -0,0 +1,87 @@ +# Type Is [![Build Status](https://travis-ci.org/expressjs/type-is.png)](https://travis-ci.org/expressjs/type-is) + +Infer the content type of a request. +Extracted from [koa](https://github.com/koajs/koa) for general use. + +Here's an example body parser: + +```js +var is = require('type-is'); +var parse = require('body'); +var busboy = require('busboy'); + +function bodyParser(req, res, next) { + var hasRequestBody = 'content-type' in req.headers + || 'transfer-encoding' in req.headers; + if (!hasRequestBody) return next(); + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + break + case 'json': + // parse json body + break + case 'multipart': + // parse multipart body + break + default: + // 415 error code + } +} +``` + +## API + +### var type = is(request, types) + +```js +var is = require('type-is') + +http.createServer(function (req, res) { + is(req, ['text/*']) +}) +``` + +`request` is the node HTTP request. `types` is an array of types. Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/json` or `application/*`. The full mime type will be returned if matched + +`false` will be returned if no type matches. + +Examples: + +```js +// req.headers.content-type = 'application/json' +is(req, ['json']) // -> 'json' +is(req, ['html', 'json']) // -> 'json' +is(req, ['application/*']) // -> 'application/json' +is(req, ['application/json']) // -> 'application/json' +is(req, ['html']) // -> false +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2013 Jonathan Ong me@jongleberry.com + +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/express/node_modules/type-is/index.js b/node_modules/express/node_modules/type-is/index.js new file mode 100644 index 000000000..af7022c38 --- /dev/null +++ b/node_modules/express/node_modules/type-is/index.js @@ -0,0 +1,148 @@ + +var mime = require('mime'); + +var slice = [].slice; + +module.exports = typeofrequest; +typeofrequest.is = typeis; +typeofrequest.hasBody = hasbody; +typeofrequest.normalize = normalize; +typeofrequest.match = mimeMatch; + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @return String + */ + +function typeis(value, types) { + if (!value) return false; + if (types && !Array.isArray(types)) types = slice.call(arguments, 1); + + // remove stuff like charsets + var index = value.indexOf(';') + value = ~index ? value.slice(0, index) : value + + // no types, return the content type + if (!types || !types.length) return value; + + var type; + for (var i = 0; i < types.length; i++) + if (mimeMatch(normalize(type = types[i]), value)) + return ~type.indexOf('*') ? value : type; + + // no matches + return false; +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @api public + */ + +function hasbody(req) { + var headers = req.headers; + if ('transfer-encoding' in headers) return true; + var length = headers['content-length']; + if (!length) return false; + // no idea when this would happen, but `isNaN(null) === false` + if (isNaN(length)) return false; + return !!parseInt(length, 10); +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @api public + */ + +function typeofrequest(req, types) { + if (!hasbody(req)) return null; + if (types && !Array.isArray(types)) types = slice.call(arguments, 1); + return typeis(req.headers['content-type'], types); +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @api private + */ + +function normalize(type) { + switch (type) { + case 'urlencoded': return 'application/x-www-form-urlencoded'; + case 'multipart': + type = 'multipart/*'; + break; + } + + return ~type.indexOf('/') ? type : mime.lookup(type); +} + +/** + * Check if `exected` mime type + * matches `actual` mime type with + * wildcard support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @api private + */ + +function mimeMatch(expected, actual) { + if (expected === actual) return true; + + if (!~expected.indexOf('*')) return false; + + actual = actual.split('/'); + expected = expected.split('/'); + + if ('*' === expected[0] && expected[1] === actual[1]) return true; + if ('*' === expected[1] && expected[0] === actual[0]) return true; + return false; +} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/LICENSE b/node_modules/express/node_modules/type-is/node_modules/mime/LICENSE new file mode 100644 index 000000000..451fc4550 --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/express/node_modules/type-is/node_modules/mime/README.md b/node_modules/express/node_modules/type-is/node_modules/mime/README.md new file mode 100644 index 000000000..6ca19bd1e --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/README.md @@ -0,0 +1,66 @@ +# mime + +Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + + var mime = require('mime'); + + mime.lookup('/path/to/file.txt'); // => 'text/plain' + mime.lookup('file.txt'); // => 'text/plain' + mime.lookup('.TXT'); // => 'text/plain' + mime.lookup('htm'); // => 'text/html' + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + + mime.extension('text/html'); // => 'html' + mime.extension('application/octet-stream'); // => 'bin' + +### mime.charsets.lookup() + +Map mime-type to charset + + mime.charsets.lookup('text/plain'); // => 'UTF-8' + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). + +### mime.define() + +Add custom mime/extension mappings + + mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... + }); + + mime.lookup('x-sft'); // => 'text/x-some-format' + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + + mime.extension('text/x-some-format'); // => 'x-sf' + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + + mime.load('./my_project.types'); + +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/mime.js b/node_modules/express/node_modules/type-is/node_modules/mime/mime.js new file mode 100644 index 000000000..48be0c5e4 --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/mime.js @@ -0,0 +1,114 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Load local copy of +// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +mime.load(path.join(__dirname, 'types/mime.types')); + +// Load additional types from node.js community +mime.load(path.join(__dirname, 'types/node.types')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/package.json b/node_modules/express/node_modules/type-is/node_modules/mime/package.json new file mode 100644 index 000000000..259822b78 --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/package.json @@ -0,0 +1,58 @@ +{ + "author": { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "dependencies": {}, + "description": "A comprehensive library for mime-type mapping", + "devDependencies": {}, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.2.11", + "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.default_type\nSets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "_id": "mime@1.2.11", + "dist": { + "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + }, + "_from": "mime@~1.2.11", + "_npmVersion": "1.3.6", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "directories": {}, + "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "homepage": "https://github.com/broofa/node-mime" +} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/test.js b/node_modules/express/node_modules/type-is/node_modules/mime/test.js new file mode 100644 index 000000000..2cda1c7ad --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/test.js @@ -0,0 +1,84 @@ +/** + * Usage: node test.js + */ + +var mime = require('./mime'); +var assert = require('assert'); +var path = require('path'); + +function eq(a, b) { + console.log('Test: ' + a + ' === ' + b); + assert.strictEqual.apply(null, arguments); +} + +console.log(Object.keys(mime.extensions).length + ' types'); +console.log(Object.keys(mime.types).length + ' extensions\n'); + +// +// Test mime lookups +// + +eq('text/plain', mime.lookup('text.txt')); // normal file +eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase +eq('text/plain', mime.lookup('dir/text.txt')); // dir + file +eq('text/plain', mime.lookup('.text.txt')); // hidden file +eq('text/plain', mime.lookup('.txt')); // nameless +eq('text/plain', mime.lookup('txt')); // extension-only +eq('text/plain', mime.lookup('/txt')); // extension-less () +eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less +eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized +eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +eq('txt', mime.extension(mime.types.text)); +eq('html', mime.extension(mime.types.htm)); +eq('bin', mime.extension('application/octet-stream')); +eq('bin', mime.extension('application/octet-stream ')); +eq('html', mime.extension(' text/html; charset=UTF-8')); +eq('html', mime.extension('text/html; charset=UTF-8 ')); +eq('html', mime.extension('text/html; charset=UTF-8')); +eq('html', mime.extension('text/html ; charset=UTF-8')); +eq('html', mime.extension('text/html;charset=UTF-8')); +eq('html', mime.extension('text/Html;charset=UTF-8')); +eq(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +eq('application/font-woff', mime.lookup('file.woff')); +eq('application/octet-stream', mime.lookup('file.buffer')); +eq('audio/mp4', mime.lookup('file.m4a')); +eq('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +eq('UTF-8', mime.charsets.lookup('text/plain')); +eq(undefined, mime.charsets.lookup(mime.types.js)); +eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +// +// Test for overlaps between mime.types and node.types +// + +var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); +apacheTypes.load(path.join(__dirname, 'types/mime.types')); +nodeTypes.load(path.join(__dirname, 'types/node.types')); + +var keys = [].concat(Object.keys(apacheTypes.types)) + .concat(Object.keys(nodeTypes.types)); +keys.sort(); +for (var i = 1; i < keys.length; i++) { + if (keys[i] == keys[i-1]) { + console.warn('Warning: ' + + 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + + ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); + } +} + +console.log('\nOK'); diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/types/mime.types b/node_modules/express/node_modules/type-is/node_modules/mime/types/mime.types new file mode 100644 index 000000000..da8cd6918 --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/types/mime.types @@ -0,0 +1,1588 @@ +# This file maps Internet media types to unique file extension(s). +# Although created for httpd, this file is used by many software systems +# and has been placed in the public domain for unlimited redisribution. +# +# The table below contains both registered and (common) unregistered types. +# A type that has no unique extension can be ignored -- they are listed +# here to guide configurations toward known types and to make it easier to +# identify "new" types. File extensions are also commonly used to indicate +# content languages and encodings, so choose them carefully. +# +# Internet media types should be registered as described in RFC 4288. +# The registry is at . +# +# MIME type (lowercased) Extensions +# ============================================ ========== +# application/1d-interleaved-parityfec +# application/3gpp-ims+xml +# application/activemessage +application/andrew-inset ez +# application/applefile +application/applixware aw +application/atom+xml atom +application/atomcat+xml atomcat +# application/atomicmail +application/atomsvc+xml atomsvc +# application/auth-policy+xml +# application/batch-smtp +# application/beep+xml +# application/calendar+xml +# application/cals-1840 +# application/ccmp+xml +application/ccxml+xml ccxml +application/cdmi-capability cdmia +application/cdmi-container cdmic +application/cdmi-domain cdmid +application/cdmi-object cdmio +application/cdmi-queue cdmiq +# application/cea-2018+xml +# application/cellml+xml +# application/cfw +# application/cnrp+xml +# application/commonground +# application/conference-info+xml +# application/cpl+xml +# application/csta+xml +# application/cstadata+xml +application/cu-seeme cu +# application/cybercash +application/davmount+xml davmount +# application/dca-rft +# application/dec-dx +# application/dialog-info+xml +# application/dicom +# application/dns +application/docbook+xml dbk +# application/dskpp+xml +application/dssc+der dssc +application/dssc+xml xdssc +# application/dvcs +application/ecmascript ecma +# application/edi-consent +# application/edi-x12 +# application/edifact +application/emma+xml emma +# application/epp+xml +application/epub+zip epub +# application/eshop +# application/example +application/exi exi +# application/fastinfoset +# application/fastsoap +# application/fits +application/font-tdpfr pfr +# application/framework-attributes+xml +application/gml+xml gml +application/gpx+xml gpx +application/gxf gxf +# application/h224 +# application/held+xml +# application/http +application/hyperstudio stk +# application/ibe-key-request+xml +# application/ibe-pkg-reply+xml +# application/ibe-pp-data +# application/iges +# application/im-iscomposing+xml +# application/index +# application/index.cmd +# application/index.obj +# application/index.response +# application/index.vnd +application/inkml+xml ink inkml +# application/iotp +application/ipfix ipfix +# application/ipp +# application/isup +application/java-archive jar +application/java-serialized-object ser +application/java-vm class +application/javascript js +application/json json +application/jsonml+json jsonml +# application/kpml-request+xml +# application/kpml-response+xml +application/lost+xml lostxml +application/mac-binhex40 hqx +application/mac-compactpro cpt +# application/macwriteii +application/mads+xml mads +application/marc mrc +application/marcxml+xml mrcx +application/mathematica ma nb mb +# application/mathml-content+xml +# application/mathml-presentation+xml +application/mathml+xml mathml +# application/mbms-associated-procedure-description+xml +# application/mbms-deregister+xml +# application/mbms-envelope+xml +# application/mbms-msk+xml +# application/mbms-msk-response+xml +# application/mbms-protection-description+xml +# application/mbms-reception-report+xml +# application/mbms-register+xml +# application/mbms-register-response+xml +# application/mbms-user-service-description+xml +application/mbox mbox +# application/media_control+xml +application/mediaservercontrol+xml mscml +application/metalink+xml metalink +application/metalink4+xml meta4 +application/mets+xml mets +# application/mikey +application/mods+xml mods +# application/moss-keys +# application/moss-signature +# application/mosskey-data +# application/mosskey-request +application/mp21 m21 mp21 +application/mp4 mp4s +# application/mpeg4-generic +# application/mpeg4-iod +# application/mpeg4-iod-xmt +# application/msc-ivr+xml +# application/msc-mixer+xml +application/msword doc dot +application/mxf mxf +# application/nasdata +# application/news-checkgroups +# application/news-groupinfo +# application/news-transmission +# application/nss +# application/ocsp-request +# application/ocsp-response +application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy +application/oda oda +application/oebps-package+xml opf +application/ogg ogx +application/omdoc+xml omdoc +application/onenote onetoc onetoc2 onetmp onepkg +application/oxps oxps +# application/parityfec +application/patch-ops-error+xml xer +application/pdf pdf +application/pgp-encrypted pgp +# application/pgp-keys +application/pgp-signature asc sig +application/pics-rules prf +# application/pidf+xml +# application/pidf-diff+xml +application/pkcs10 p10 +application/pkcs7-mime p7m p7c +application/pkcs7-signature p7s +application/pkcs8 p8 +application/pkix-attr-cert ac +application/pkix-cert cer +application/pkix-crl crl +application/pkix-pkipath pkipath +application/pkixcmp pki +application/pls+xml pls +# application/poc-settings+xml +application/postscript ai eps ps +# application/prs.alvestrand.titrax-sheet +application/prs.cww cww +# application/prs.nprend +# application/prs.plucker +# application/prs.rdf-xml-crypt +# application/prs.xsf+xml +application/pskc+xml pskcxml +# application/qsig +application/rdf+xml rdf +application/reginfo+xml rif +application/relax-ng-compact-syntax rnc +# application/remote-printing +application/resource-lists+xml rl +application/resource-lists-diff+xml rld +# application/riscos +# application/rlmi+xml +application/rls-services+xml rs +application/rpki-ghostbusters gbr +application/rpki-manifest mft +application/rpki-roa roa +# application/rpki-updown +application/rsd+xml rsd +application/rss+xml rss +application/rtf rtf +# application/rtx +# application/samlassertion+xml +# application/samlmetadata+xml +application/sbml+xml sbml +application/scvp-cv-request scq +application/scvp-cv-response scs +application/scvp-vp-request spq +application/scvp-vp-response spp +application/sdp sdp +# application/set-payment +application/set-payment-initiation setpay +# application/set-registration +application/set-registration-initiation setreg +# application/sgml +# application/sgml-open-catalog +application/shf+xml shf +# application/sieve +# application/simple-filter+xml +# application/simple-message-summary +# application/simplesymbolcontainer +# application/slate +# application/smil +application/smil+xml smi smil +# application/soap+fastinfoset +# application/soap+xml +application/sparql-query rq +application/sparql-results+xml srx +# application/spirits-event+xml +application/srgs gram +application/srgs+xml grxml +application/sru+xml sru +application/ssdl+xml ssdl +application/ssml+xml ssml +# application/tamp-apex-update +# application/tamp-apex-update-confirm +# application/tamp-community-update +# application/tamp-community-update-confirm +# application/tamp-error +# application/tamp-sequence-adjust +# application/tamp-sequence-adjust-confirm +# application/tamp-status-query +# application/tamp-status-response +# application/tamp-update +# application/tamp-update-confirm +application/tei+xml tei teicorpus +application/thraud+xml tfi +# application/timestamp-query +# application/timestamp-reply +application/timestamped-data tsd +# application/tve-trigger +# application/ulpfec +# application/vcard+xml +# application/vemmi +# application/vividence.scriptfile +# application/vnd.3gpp.bsf+xml +application/vnd.3gpp.pic-bw-large plb +application/vnd.3gpp.pic-bw-small psb +application/vnd.3gpp.pic-bw-var pvb +# application/vnd.3gpp.sms +# application/vnd.3gpp2.bcmcsinfo+xml +# application/vnd.3gpp2.sms +application/vnd.3gpp2.tcap tcap +application/vnd.3m.post-it-notes pwn +application/vnd.accpac.simply.aso aso +application/vnd.accpac.simply.imp imp +application/vnd.acucobol acu +application/vnd.acucorp atc acutc +application/vnd.adobe.air-application-installer-package+zip air +application/vnd.adobe.formscentral.fcdt fcdt +application/vnd.adobe.fxp fxp fxpl +# application/vnd.adobe.partial-upload +application/vnd.adobe.xdp+xml xdp +application/vnd.adobe.xfdf xfdf +# application/vnd.aether.imp +# application/vnd.ah-barcode +application/vnd.ahead.space ahead +application/vnd.airzip.filesecure.azf azf +application/vnd.airzip.filesecure.azs azs +application/vnd.amazon.ebook azw +application/vnd.americandynamics.acc acc +application/vnd.amiga.ami ami +# application/vnd.amundsen.maze+xml +application/vnd.android.package-archive apk +application/vnd.anser-web-certificate-issue-initiation cii +application/vnd.anser-web-funds-transfer-initiation fti +application/vnd.antix.game-component atx +application/vnd.apple.installer+xml mpkg +application/vnd.apple.mpegurl m3u8 +# application/vnd.arastra.swi +application/vnd.aristanetworks.swi swi +application/vnd.astraea-software.iota iota +application/vnd.audiograph aep +# application/vnd.autopackage +# application/vnd.avistar+xml +application/vnd.blueice.multipass mpm +# application/vnd.bluetooth.ep.oob +application/vnd.bmi bmi +application/vnd.businessobjects rep +# application/vnd.cab-jscript +# application/vnd.canon-cpdl +# application/vnd.canon-lips +# application/vnd.cendio.thinlinc.clientconf +application/vnd.chemdraw+xml cdxml +application/vnd.chipnuts.karaoke-mmd mmd +application/vnd.cinderella cdy +# application/vnd.cirpack.isdn-ext +application/vnd.claymore cla +application/vnd.cloanto.rp9 rp9 +application/vnd.clonk.c4group c4g c4d c4f c4p c4u +application/vnd.cluetrust.cartomobile-config c11amc +application/vnd.cluetrust.cartomobile-config-pkg c11amz +# application/vnd.collection+json +# application/vnd.commerce-battelle +application/vnd.commonspace csp +application/vnd.contact.cmsg cdbcmsg +application/vnd.cosmocaller cmc +application/vnd.crick.clicker clkx +application/vnd.crick.clicker.keyboard clkk +application/vnd.crick.clicker.palette clkp +application/vnd.crick.clicker.template clkt +application/vnd.crick.clicker.wordbank clkw +application/vnd.criticaltools.wbs+xml wbs +application/vnd.ctc-posml pml +# application/vnd.ctct.ws+xml +# application/vnd.cups-pdf +# application/vnd.cups-postscript +application/vnd.cups-ppd ppd +# application/vnd.cups-raster +# application/vnd.cups-raw +# application/vnd.curl +application/vnd.curl.car car +application/vnd.curl.pcurl pcurl +# application/vnd.cybank +application/vnd.dart dart +application/vnd.data-vision.rdz rdz +application/vnd.dece.data uvf uvvf uvd uvvd +application/vnd.dece.ttml+xml uvt uvvt +application/vnd.dece.unspecified uvx uvvx +application/vnd.dece.zip uvz uvvz +application/vnd.denovo.fcselayout-link fe_launch +# application/vnd.dir-bi.plate-dl-nosuffix +application/vnd.dna dna +application/vnd.dolby.mlp mlp +# application/vnd.dolby.mobile.1 +# application/vnd.dolby.mobile.2 +application/vnd.dpgraph dpg +application/vnd.dreamfactory dfac +application/vnd.ds-keypoint kpxx +application/vnd.dvb.ait ait +# application/vnd.dvb.dvbj +# application/vnd.dvb.esgcontainer +# application/vnd.dvb.ipdcdftnotifaccess +# application/vnd.dvb.ipdcesgaccess +# application/vnd.dvb.ipdcesgaccess2 +# application/vnd.dvb.ipdcesgpdd +# application/vnd.dvb.ipdcroaming +# application/vnd.dvb.iptv.alfec-base +# application/vnd.dvb.iptv.alfec-enhancement +# application/vnd.dvb.notif-aggregate-root+xml +# application/vnd.dvb.notif-container+xml +# application/vnd.dvb.notif-generic+xml +# application/vnd.dvb.notif-ia-msglist+xml +# application/vnd.dvb.notif-ia-registration-request+xml +# application/vnd.dvb.notif-ia-registration-response+xml +# application/vnd.dvb.notif-init+xml +# application/vnd.dvb.pfr +application/vnd.dvb.service svc +# application/vnd.dxr +application/vnd.dynageo geo +# application/vnd.easykaraoke.cdgdownload +# application/vnd.ecdis-update +application/vnd.ecowin.chart mag +# application/vnd.ecowin.filerequest +# application/vnd.ecowin.fileupdate +# application/vnd.ecowin.series +# application/vnd.ecowin.seriesrequest +# application/vnd.ecowin.seriesupdate +# application/vnd.emclient.accessrequest+xml +application/vnd.enliven nml +# application/vnd.eprints.data+xml +application/vnd.epson.esf esf +application/vnd.epson.msf msf +application/vnd.epson.quickanime qam +application/vnd.epson.salt slt +application/vnd.epson.ssf ssf +# application/vnd.ericsson.quickcall +application/vnd.eszigno3+xml es3 et3 +# application/vnd.etsi.aoc+xml +# application/vnd.etsi.cug+xml +# application/vnd.etsi.iptvcommand+xml +# application/vnd.etsi.iptvdiscovery+xml +# application/vnd.etsi.iptvprofile+xml +# application/vnd.etsi.iptvsad-bc+xml +# application/vnd.etsi.iptvsad-cod+xml +# application/vnd.etsi.iptvsad-npvr+xml +# application/vnd.etsi.iptvservice+xml +# application/vnd.etsi.iptvsync+xml +# application/vnd.etsi.iptvueprofile+xml +# application/vnd.etsi.mcid+xml +# application/vnd.etsi.overload-control-policy-dataset+xml +# application/vnd.etsi.sci+xml +# application/vnd.etsi.simservs+xml +# application/vnd.etsi.tsl+xml +# application/vnd.etsi.tsl.der +# application/vnd.eudora.data +application/vnd.ezpix-album ez2 +application/vnd.ezpix-package ez3 +# application/vnd.f-secure.mobile +application/vnd.fdf fdf +application/vnd.fdsn.mseed mseed +application/vnd.fdsn.seed seed dataless +# application/vnd.ffsns +# application/vnd.fints +application/vnd.flographit gph +application/vnd.fluxtime.clip ftc +# application/vnd.font-fontforge-sfd +application/vnd.framemaker fm frame maker book +application/vnd.frogans.fnc fnc +application/vnd.frogans.ltf ltf +application/vnd.fsc.weblaunch fsc +application/vnd.fujitsu.oasys oas +application/vnd.fujitsu.oasys2 oa2 +application/vnd.fujitsu.oasys3 oa3 +application/vnd.fujitsu.oasysgp fg5 +application/vnd.fujitsu.oasysprs bh2 +# application/vnd.fujixerox.art-ex +# application/vnd.fujixerox.art4 +# application/vnd.fujixerox.hbpl +application/vnd.fujixerox.ddd ddd +application/vnd.fujixerox.docuworks xdw +application/vnd.fujixerox.docuworks.binder xbd +# application/vnd.fut-misnet +application/vnd.fuzzysheet fzs +application/vnd.genomatix.tuxedo txd +# application/vnd.geocube+xml +application/vnd.geogebra.file ggb +application/vnd.geogebra.tool ggt +application/vnd.geometry-explorer gex gre +application/vnd.geonext gxt +application/vnd.geoplan g2w +application/vnd.geospace g3w +# application/vnd.globalplatform.card-content-mgt +# application/vnd.globalplatform.card-content-mgt-response +application/vnd.gmx gmx +application/vnd.google-earth.kml+xml kml +application/vnd.google-earth.kmz kmz +application/vnd.grafeq gqf gqs +# application/vnd.gridmp +application/vnd.groove-account gac +application/vnd.groove-help ghf +application/vnd.groove-identity-message gim +application/vnd.groove-injector grv +application/vnd.groove-tool-message gtm +application/vnd.groove-tool-template tpl +application/vnd.groove-vcard vcg +# application/vnd.hal+json +application/vnd.hal+xml hal +application/vnd.handheld-entertainment+xml zmm +application/vnd.hbci hbci +# application/vnd.hcl-bireports +application/vnd.hhe.lesson-player les +application/vnd.hp-hpgl hpgl +application/vnd.hp-hpid hpid +application/vnd.hp-hps hps +application/vnd.hp-jlyt jlt +application/vnd.hp-pcl pcl +application/vnd.hp-pclxl pclxl +# application/vnd.httphone +application/vnd.hydrostatix.sof-data sfd-hdstx +# application/vnd.hzn-3d-crossword +# application/vnd.ibm.afplinedata +# application/vnd.ibm.electronic-media +application/vnd.ibm.minipay mpy +application/vnd.ibm.modcap afp listafp list3820 +application/vnd.ibm.rights-management irm +application/vnd.ibm.secure-container sc +application/vnd.iccprofile icc icm +application/vnd.igloader igl +application/vnd.immervision-ivp ivp +application/vnd.immervision-ivu ivu +# application/vnd.informedcontrol.rms+xml +# application/vnd.informix-visionary +# application/vnd.infotech.project +# application/vnd.infotech.project+xml +# application/vnd.innopath.wamp.notification +application/vnd.insors.igm igm +application/vnd.intercon.formnet xpw xpx +application/vnd.intergeo i2g +# application/vnd.intertrust.digibox +# application/vnd.intertrust.nncp +application/vnd.intu.qbo qbo +application/vnd.intu.qfx qfx +# application/vnd.iptc.g2.conceptitem+xml +# application/vnd.iptc.g2.knowledgeitem+xml +# application/vnd.iptc.g2.newsitem+xml +# application/vnd.iptc.g2.newsmessage+xml +# application/vnd.iptc.g2.packageitem+xml +# application/vnd.iptc.g2.planningitem+xml +application/vnd.ipunplugged.rcprofile rcprofile +application/vnd.irepository.package+xml irp +application/vnd.is-xpr xpr +application/vnd.isac.fcs fcs +application/vnd.jam jam +# application/vnd.japannet-directory-service +# application/vnd.japannet-jpnstore-wakeup +# application/vnd.japannet-payment-wakeup +# application/vnd.japannet-registration +# application/vnd.japannet-registration-wakeup +# application/vnd.japannet-setstore-wakeup +# application/vnd.japannet-verification +# application/vnd.japannet-verification-wakeup +application/vnd.jcp.javame.midlet-rms rms +application/vnd.jisp jisp +application/vnd.joost.joda-archive joda +application/vnd.kahootz ktz ktr +application/vnd.kde.karbon karbon +application/vnd.kde.kchart chrt +application/vnd.kde.kformula kfo +application/vnd.kde.kivio flw +application/vnd.kde.kontour kon +application/vnd.kde.kpresenter kpr kpt +application/vnd.kde.kspread ksp +application/vnd.kde.kword kwd kwt +application/vnd.kenameaapp htke +application/vnd.kidspiration kia +application/vnd.kinar kne knp +application/vnd.koan skp skd skt skm +application/vnd.kodak-descriptor sse +application/vnd.las.las+xml lasxml +# application/vnd.liberty-request+xml +application/vnd.llamagraphics.life-balance.desktop lbd +application/vnd.llamagraphics.life-balance.exchange+xml lbe +application/vnd.lotus-1-2-3 123 +application/vnd.lotus-approach apr +application/vnd.lotus-freelance pre +application/vnd.lotus-notes nsf +application/vnd.lotus-organizer org +application/vnd.lotus-screencam scm +application/vnd.lotus-wordpro lwp +application/vnd.macports.portpkg portpkg +# application/vnd.marlin.drm.actiontoken+xml +# application/vnd.marlin.drm.conftoken+xml +# application/vnd.marlin.drm.license+xml +# application/vnd.marlin.drm.mdcf +application/vnd.mcd mcd +application/vnd.medcalcdata mc1 +application/vnd.mediastation.cdkey cdkey +# application/vnd.meridian-slingshot +application/vnd.mfer mwf +application/vnd.mfmp mfm +application/vnd.micrografx.flo flo +application/vnd.micrografx.igx igx +application/vnd.mif mif +# application/vnd.minisoft-hp3000-save +# application/vnd.mitsubishi.misty-guard.trustweb +application/vnd.mobius.daf daf +application/vnd.mobius.dis dis +application/vnd.mobius.mbk mbk +application/vnd.mobius.mqy mqy +application/vnd.mobius.msl msl +application/vnd.mobius.plc plc +application/vnd.mobius.txf txf +application/vnd.mophun.application mpn +application/vnd.mophun.certificate mpc +# application/vnd.motorola.flexsuite +# application/vnd.motorola.flexsuite.adsi +# application/vnd.motorola.flexsuite.fis +# application/vnd.motorola.flexsuite.gotap +# application/vnd.motorola.flexsuite.kmr +# application/vnd.motorola.flexsuite.ttc +# application/vnd.motorola.flexsuite.wem +# application/vnd.motorola.iprm +application/vnd.mozilla.xul+xml xul +application/vnd.ms-artgalry cil +# application/vnd.ms-asf +application/vnd.ms-cab-compressed cab +# application/vnd.ms-color.iccprofile +application/vnd.ms-excel xls xlm xla xlc xlt xlw +application/vnd.ms-excel.addin.macroenabled.12 xlam +application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb +application/vnd.ms-excel.sheet.macroenabled.12 xlsm +application/vnd.ms-excel.template.macroenabled.12 xltm +application/vnd.ms-fontobject eot +application/vnd.ms-htmlhelp chm +application/vnd.ms-ims ims +application/vnd.ms-lrm lrm +# application/vnd.ms-office.activex+xml +application/vnd.ms-officetheme thmx +# application/vnd.ms-opentype +# application/vnd.ms-package.obfuscated-opentype +application/vnd.ms-pki.seccat cat +application/vnd.ms-pki.stl stl +# application/vnd.ms-playready.initiator+xml +application/vnd.ms-powerpoint ppt pps pot +application/vnd.ms-powerpoint.addin.macroenabled.12 ppam +application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm +application/vnd.ms-powerpoint.slide.macroenabled.12 sldm +application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm +application/vnd.ms-powerpoint.template.macroenabled.12 potm +# application/vnd.ms-printing.printticket+xml +application/vnd.ms-project mpp mpt +# application/vnd.ms-tnef +# application/vnd.ms-wmdrm.lic-chlg-req +# application/vnd.ms-wmdrm.lic-resp +# application/vnd.ms-wmdrm.meter-chlg-req +# application/vnd.ms-wmdrm.meter-resp +application/vnd.ms-word.document.macroenabled.12 docm +application/vnd.ms-word.template.macroenabled.12 dotm +application/vnd.ms-works wps wks wcm wdb +application/vnd.ms-wpl wpl +application/vnd.ms-xpsdocument xps +application/vnd.mseq mseq +# application/vnd.msign +# application/vnd.multiad.creator +# application/vnd.multiad.creator.cif +# application/vnd.music-niff +application/vnd.musician mus +application/vnd.muvee.style msty +application/vnd.mynfc taglet +# application/vnd.ncd.control +# application/vnd.ncd.reference +# application/vnd.nervana +# application/vnd.netfpx +application/vnd.neurolanguage.nlu nlu +application/vnd.nitf ntf nitf +application/vnd.noblenet-directory nnd +application/vnd.noblenet-sealer nns +application/vnd.noblenet-web nnw +# application/vnd.nokia.catalogs +# application/vnd.nokia.conml+wbxml +# application/vnd.nokia.conml+xml +# application/vnd.nokia.isds-radio-presets +# application/vnd.nokia.iptv.config+xml +# application/vnd.nokia.landmark+wbxml +# application/vnd.nokia.landmark+xml +# application/vnd.nokia.landmarkcollection+xml +# application/vnd.nokia.n-gage.ac+xml +application/vnd.nokia.n-gage.data ngdat +application/vnd.nokia.n-gage.symbian.install n-gage +# application/vnd.nokia.ncd +# application/vnd.nokia.pcd+wbxml +# application/vnd.nokia.pcd+xml +application/vnd.nokia.radio-preset rpst +application/vnd.nokia.radio-presets rpss +application/vnd.novadigm.edm edm +application/vnd.novadigm.edx edx +application/vnd.novadigm.ext ext +# application/vnd.ntt-local.file-transfer +# application/vnd.ntt-local.sip-ta_remote +# application/vnd.ntt-local.sip-ta_tcp_stream +application/vnd.oasis.opendocument.chart odc +application/vnd.oasis.opendocument.chart-template otc +application/vnd.oasis.opendocument.database odb +application/vnd.oasis.opendocument.formula odf +application/vnd.oasis.opendocument.formula-template odft +application/vnd.oasis.opendocument.graphics odg +application/vnd.oasis.opendocument.graphics-template otg +application/vnd.oasis.opendocument.image odi +application/vnd.oasis.opendocument.image-template oti +application/vnd.oasis.opendocument.presentation odp +application/vnd.oasis.opendocument.presentation-template otp +application/vnd.oasis.opendocument.spreadsheet ods +application/vnd.oasis.opendocument.spreadsheet-template ots +application/vnd.oasis.opendocument.text odt +application/vnd.oasis.opendocument.text-master odm +application/vnd.oasis.opendocument.text-template ott +application/vnd.oasis.opendocument.text-web oth +# application/vnd.obn +# application/vnd.oftn.l10n+json +# application/vnd.oipf.contentaccessdownload+xml +# application/vnd.oipf.contentaccessstreaming+xml +# application/vnd.oipf.cspg-hexbinary +# application/vnd.oipf.dae.svg+xml +# application/vnd.oipf.dae.xhtml+xml +# application/vnd.oipf.mippvcontrolmessage+xml +# application/vnd.oipf.pae.gem +# application/vnd.oipf.spdiscovery+xml +# application/vnd.oipf.spdlist+xml +# application/vnd.oipf.ueprofile+xml +# application/vnd.oipf.userprofile+xml +application/vnd.olpc-sugar xo +# application/vnd.oma-scws-config +# application/vnd.oma-scws-http-request +# application/vnd.oma-scws-http-response +# application/vnd.oma.bcast.associated-procedure-parameter+xml +# application/vnd.oma.bcast.drm-trigger+xml +# application/vnd.oma.bcast.imd+xml +# application/vnd.oma.bcast.ltkm +# application/vnd.oma.bcast.notification+xml +# application/vnd.oma.bcast.provisioningtrigger +# application/vnd.oma.bcast.sgboot +# application/vnd.oma.bcast.sgdd+xml +# application/vnd.oma.bcast.sgdu +# application/vnd.oma.bcast.simple-symbol-container +# application/vnd.oma.bcast.smartcard-trigger+xml +# application/vnd.oma.bcast.sprov+xml +# application/vnd.oma.bcast.stkm +# application/vnd.oma.cab-address-book+xml +# application/vnd.oma.cab-feature-handler+xml +# application/vnd.oma.cab-pcc+xml +# application/vnd.oma.cab-user-prefs+xml +# application/vnd.oma.dcd +# application/vnd.oma.dcdc +application/vnd.oma.dd2+xml dd2 +# application/vnd.oma.drm.risd+xml +# application/vnd.oma.group-usage-list+xml +# application/vnd.oma.pal+xml +# application/vnd.oma.poc.detailed-progress-report+xml +# application/vnd.oma.poc.final-report+xml +# application/vnd.oma.poc.groups+xml +# application/vnd.oma.poc.invocation-descriptor+xml +# application/vnd.oma.poc.optimized-progress-report+xml +# application/vnd.oma.push +# application/vnd.oma.scidm.messages+xml +# application/vnd.oma.xcap-directory+xml +# application/vnd.omads-email+xml +# application/vnd.omads-file+xml +# application/vnd.omads-folder+xml +# application/vnd.omaloc-supl-init +application/vnd.openofficeorg.extension oxt +# application/vnd.openxmlformats-officedocument.custom-properties+xml +# application/vnd.openxmlformats-officedocument.customxmlproperties+xml +# application/vnd.openxmlformats-officedocument.drawing+xml +# application/vnd.openxmlformats-officedocument.drawingml.chart+xml +# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml +# application/vnd.openxmlformats-officedocument.extended-properties+xml +# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml +# application/vnd.openxmlformats-officedocument.presentationml.comments+xml +# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml +application/vnd.openxmlformats-officedocument.presentationml.presentation pptx +# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml +application/vnd.openxmlformats-officedocument.presentationml.slide sldx +# application/vnd.openxmlformats-officedocument.presentationml.slide+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml +application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx +# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml +# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml +# application/vnd.openxmlformats-officedocument.presentationml.tags+xml +application/vnd.openxmlformats-officedocument.presentationml.template potx +# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx +# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml +# application/vnd.openxmlformats-officedocument.theme+xml +# application/vnd.openxmlformats-officedocument.themeoverride+xml +# application/vnd.openxmlformats-officedocument.vmldrawing +# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.document docx +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx +# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml +# application/vnd.openxmlformats-package.core-properties+xml +# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml +# application/vnd.openxmlformats-package.relationships+xml +# application/vnd.quobject-quoxdocument +# application/vnd.osa.netdeploy +application/vnd.osgeo.mapguide.package mgp +# application/vnd.osgi.bundle +application/vnd.osgi.dp dp +application/vnd.osgi.subsystem esa +# application/vnd.otps.ct-kip+xml +application/vnd.palm pdb pqa oprc +# application/vnd.paos.xml +application/vnd.pawaafile paw +application/vnd.pg.format str +application/vnd.pg.osasli ei6 +# application/vnd.piaccess.application-licence +application/vnd.picsel efif +application/vnd.pmi.widget wg +# application/vnd.poc.group-advertisement+xml +application/vnd.pocketlearn plf +application/vnd.powerbuilder6 pbd +# application/vnd.powerbuilder6-s +# application/vnd.powerbuilder7 +# application/vnd.powerbuilder7-s +# application/vnd.powerbuilder75 +# application/vnd.powerbuilder75-s +# application/vnd.preminet +application/vnd.previewsystems.box box +application/vnd.proteus.magazine mgz +application/vnd.publishare-delta-tree qps +application/vnd.pvi.ptid1 ptid +# application/vnd.pwg-multiplexed +# application/vnd.pwg-xhtml-print+xml +# application/vnd.qualcomm.brew-app-res +application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb +# application/vnd.radisys.moml+xml +# application/vnd.radisys.msml+xml +# application/vnd.radisys.msml-audit+xml +# application/vnd.radisys.msml-audit-conf+xml +# application/vnd.radisys.msml-audit-conn+xml +# application/vnd.radisys.msml-audit-dialog+xml +# application/vnd.radisys.msml-audit-stream+xml +# application/vnd.radisys.msml-conf+xml +# application/vnd.radisys.msml-dialog+xml +# application/vnd.radisys.msml-dialog-base+xml +# application/vnd.radisys.msml-dialog-fax-detect+xml +# application/vnd.radisys.msml-dialog-fax-sendrecv+xml +# application/vnd.radisys.msml-dialog-group+xml +# application/vnd.radisys.msml-dialog-speech+xml +# application/vnd.radisys.msml-dialog-transform+xml +# application/vnd.rainstor.data +# application/vnd.rapid +application/vnd.realvnc.bed bed +application/vnd.recordare.musicxml mxl +application/vnd.recordare.musicxml+xml musicxml +# application/vnd.renlearn.rlprint +application/vnd.rig.cryptonote cryptonote +application/vnd.rim.cod cod +application/vnd.rn-realmedia rm +application/vnd.rn-realmedia-vbr rmvb +application/vnd.route66.link66+xml link66 +# application/vnd.rs-274x +# application/vnd.ruckus.download +# application/vnd.s3sms +application/vnd.sailingtracker.track st +# application/vnd.sbm.cid +# application/vnd.sbm.mid2 +# application/vnd.scribus +# application/vnd.sealed.3df +# application/vnd.sealed.csf +# application/vnd.sealed.doc +# application/vnd.sealed.eml +# application/vnd.sealed.mht +# application/vnd.sealed.net +# application/vnd.sealed.ppt +# application/vnd.sealed.tiff +# application/vnd.sealed.xls +# application/vnd.sealedmedia.softseal.html +# application/vnd.sealedmedia.softseal.pdf +application/vnd.seemail see +application/vnd.sema sema +application/vnd.semd semd +application/vnd.semf semf +application/vnd.shana.informed.formdata ifm +application/vnd.shana.informed.formtemplate itp +application/vnd.shana.informed.interchange iif +application/vnd.shana.informed.package ipk +application/vnd.simtech-mindmapper twd twds +application/vnd.smaf mmf +# application/vnd.smart.notebook +application/vnd.smart.teacher teacher +# application/vnd.software602.filler.form+xml +# application/vnd.software602.filler.form-xml-zip +application/vnd.solent.sdkm+xml sdkm sdkd +application/vnd.spotfire.dxp dxp +application/vnd.spotfire.sfs sfs +# application/vnd.sss-cod +# application/vnd.sss-dtf +# application/vnd.sss-ntf +application/vnd.stardivision.calc sdc +application/vnd.stardivision.draw sda +application/vnd.stardivision.impress sdd +application/vnd.stardivision.math smf +application/vnd.stardivision.writer sdw vor +application/vnd.stardivision.writer-global sgl +application/vnd.stepmania.package smzip +application/vnd.stepmania.stepchart sm +# application/vnd.street-stream +application/vnd.sun.xml.calc sxc +application/vnd.sun.xml.calc.template stc +application/vnd.sun.xml.draw sxd +application/vnd.sun.xml.draw.template std +application/vnd.sun.xml.impress sxi +application/vnd.sun.xml.impress.template sti +application/vnd.sun.xml.math sxm +application/vnd.sun.xml.writer sxw +application/vnd.sun.xml.writer.global sxg +application/vnd.sun.xml.writer.template stw +# application/vnd.sun.wadl+xml +application/vnd.sus-calendar sus susp +application/vnd.svd svd +# application/vnd.swiftview-ics +application/vnd.symbian.install sis sisx +application/vnd.syncml+xml xsm +application/vnd.syncml.dm+wbxml bdm +application/vnd.syncml.dm+xml xdm +# application/vnd.syncml.dm.notification +# application/vnd.syncml.ds.notification +application/vnd.tao.intent-module-archive tao +application/vnd.tcpdump.pcap pcap cap dmp +application/vnd.tmobile-livetv tmo +application/vnd.trid.tpt tpt +application/vnd.triscape.mxs mxs +application/vnd.trueapp tra +# application/vnd.truedoc +# application/vnd.ubisoft.webplayer +application/vnd.ufdl ufd ufdl +application/vnd.uiq.theme utz +application/vnd.umajin umj +application/vnd.unity unityweb +application/vnd.uoml+xml uoml +# application/vnd.uplanet.alert +# application/vnd.uplanet.alert-wbxml +# application/vnd.uplanet.bearer-choice +# application/vnd.uplanet.bearer-choice-wbxml +# application/vnd.uplanet.cacheop +# application/vnd.uplanet.cacheop-wbxml +# application/vnd.uplanet.channel +# application/vnd.uplanet.channel-wbxml +# application/vnd.uplanet.list +# application/vnd.uplanet.list-wbxml +# application/vnd.uplanet.listcmd +# application/vnd.uplanet.listcmd-wbxml +# application/vnd.uplanet.signal +application/vnd.vcx vcx +# application/vnd.vd-study +# application/vnd.vectorworks +# application/vnd.verimatrix.vcas +# application/vnd.vidsoft.vidconference +application/vnd.visio vsd vst vss vsw +application/vnd.visionary vis +# application/vnd.vividence.scriptfile +application/vnd.vsf vsf +# application/vnd.wap.sic +# application/vnd.wap.slc +application/vnd.wap.wbxml wbxml +application/vnd.wap.wmlc wmlc +application/vnd.wap.wmlscriptc wmlsc +application/vnd.webturbo wtb +# application/vnd.wfa.wsc +# application/vnd.wmc +# application/vnd.wmf.bootstrap +# application/vnd.wolfram.mathematica +# application/vnd.wolfram.mathematica.package +application/vnd.wolfram.player nbp +application/vnd.wordperfect wpd +application/vnd.wqd wqd +# application/vnd.wrq-hp3000-labelled +application/vnd.wt.stf stf +# application/vnd.wv.csp+wbxml +# application/vnd.wv.csp+xml +# application/vnd.wv.ssp+xml +application/vnd.xara xar +application/vnd.xfdl xfdl +# application/vnd.xfdl.webform +# application/vnd.xmi+xml +# application/vnd.xmpie.cpkg +# application/vnd.xmpie.dpkg +# application/vnd.xmpie.plan +# application/vnd.xmpie.ppkg +# application/vnd.xmpie.xlim +application/vnd.yamaha.hv-dic hvd +application/vnd.yamaha.hv-script hvs +application/vnd.yamaha.hv-voice hvp +application/vnd.yamaha.openscoreformat osf +application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg +# application/vnd.yamaha.remote-setup +application/vnd.yamaha.smaf-audio saf +application/vnd.yamaha.smaf-phrase spf +# application/vnd.yamaha.through-ngn +# application/vnd.yamaha.tunnel-udpencap +application/vnd.yellowriver-custom-menu cmp +application/vnd.zul zir zirz +application/vnd.zzazz.deck+xml zaz +application/voicexml+xml vxml +# application/vq-rtcpxr +# application/watcherinfo+xml +# application/whoispp-query +# application/whoispp-response +application/widget wgt +application/winhlp hlp +# application/wita +# application/wordperfect5.1 +application/wsdl+xml wsdl +application/wspolicy+xml wspolicy +application/x-7z-compressed 7z +application/x-abiword abw +application/x-ace-compressed ace +# application/x-amf +application/x-apple-diskimage dmg +application/x-authorware-bin aab x32 u32 vox +application/x-authorware-map aam +application/x-authorware-seg aas +application/x-bcpio bcpio +application/x-bittorrent torrent +application/x-blorb blb blorb +application/x-bzip bz +application/x-bzip2 bz2 boz +application/x-cbr cbr cba cbt cbz cb7 +application/x-cdlink vcd +application/x-cfs-compressed cfs +application/x-chat chat +application/x-chess-pgn pgn +application/x-conference nsc +# application/x-compress +application/x-cpio cpio +application/x-csh csh +application/x-debian-package deb udeb +application/x-dgc-compressed dgc +application/x-director dir dcr dxr cst cct cxt w3d fgd swa +application/x-doom wad +application/x-dtbncx+xml ncx +application/x-dtbook+xml dtb +application/x-dtbresource+xml res +application/x-dvi dvi +application/x-envoy evy +application/x-eva eva +application/x-font-bdf bdf +# application/x-font-dos +# application/x-font-framemaker +application/x-font-ghostscript gsf +# application/x-font-libgrx +application/x-font-linux-psf psf +application/x-font-otf otf +application/x-font-pcf pcf +application/x-font-snf snf +# application/x-font-speedo +# application/x-font-sunos-news +application/x-font-ttf ttf ttc +application/x-font-type1 pfa pfb pfm afm +application/font-woff woff +# application/x-font-vfont +application/x-freearc arc +application/x-futuresplash spl +application/x-gca-compressed gca +application/x-glulx ulx +application/x-gnumeric gnumeric +application/x-gramps-xml gramps +application/x-gtar gtar +# application/x-gzip +application/x-hdf hdf +application/x-install-instructions install +application/x-iso9660-image iso +application/x-java-jnlp-file jnlp +application/x-latex latex +application/x-lzh-compressed lzh lha +application/x-mie mie +application/x-mobipocket-ebook prc mobi +application/x-ms-application application +application/x-ms-shortcut lnk +application/x-ms-wmd wmd +application/x-ms-wmz wmz +application/x-ms-xbap xbap +application/x-msaccess mdb +application/x-msbinder obd +application/x-mscardfile crd +application/x-msclip clp +application/x-msdownload exe dll com bat msi +application/x-msmediaview mvb m13 m14 +application/x-msmetafile wmf wmz emf emz +application/x-msmoney mny +application/x-mspublisher pub +application/x-msschedule scd +application/x-msterminal trm +application/x-mswrite wri +application/x-netcdf nc cdf +application/x-nzb nzb +application/x-pkcs12 p12 pfx +application/x-pkcs7-certificates p7b spc +application/x-pkcs7-certreqresp p7r +application/x-rar-compressed rar +application/x-research-info-systems ris +application/x-sh sh +application/x-shar shar +application/x-shockwave-flash swf +application/x-silverlight-app xap +application/x-sql sql +application/x-stuffit sit +application/x-stuffitx sitx +application/x-subrip srt +application/x-sv4cpio sv4cpio +application/x-sv4crc sv4crc +application/x-t3vm-image t3 +application/x-tads gam +application/x-tar tar +application/x-tcl tcl +application/x-tex tex +application/x-tex-tfm tfm +application/x-texinfo texinfo texi +application/x-tgif obj +application/x-ustar ustar +application/x-wais-source src +application/x-x509-ca-cert der crt +application/x-xfig fig +application/x-xliff+xml xlf +application/x-xpinstall xpi +application/x-xz xz +application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 +# application/x400-bp +application/xaml+xml xaml +# application/xcap-att+xml +# application/xcap-caps+xml +application/xcap-diff+xml xdf +# application/xcap-el+xml +# application/xcap-error+xml +# application/xcap-ns+xml +# application/xcon-conference-info-diff+xml +# application/xcon-conference-info+xml +application/xenc+xml xenc +application/xhtml+xml xhtml xht +# application/xhtml-voice+xml +application/xml xml xsl +application/xml-dtd dtd +# application/xml-external-parsed-entity +# application/xmpp+xml +application/xop+xml xop +application/xproc+xml xpl +application/xslt+xml xslt +application/xspf+xml xspf +application/xv+xml mxml xhvml xvml xvm +application/yang yang +application/yin+xml yin +application/zip zip +# audio/1d-interleaved-parityfec +# audio/32kadpcm +# audio/3gpp +# audio/3gpp2 +# audio/ac3 +audio/adpcm adp +# audio/amr +# audio/amr-wb +# audio/amr-wb+ +# audio/asc +# audio/atrac-advanced-lossless +# audio/atrac-x +# audio/atrac3 +audio/basic au snd +# audio/bv16 +# audio/bv32 +# audio/clearmode +# audio/cn +# audio/dat12 +# audio/dls +# audio/dsr-es201108 +# audio/dsr-es202050 +# audio/dsr-es202211 +# audio/dsr-es202212 +# audio/dv +# audio/dvi4 +# audio/eac3 +# audio/evrc +# audio/evrc-qcp +# audio/evrc0 +# audio/evrc1 +# audio/evrcb +# audio/evrcb0 +# audio/evrcb1 +# audio/evrcwb +# audio/evrcwb0 +# audio/evrcwb1 +# audio/example +# audio/fwdred +# audio/g719 +# audio/g722 +# audio/g7221 +# audio/g723 +# audio/g726-16 +# audio/g726-24 +# audio/g726-32 +# audio/g726-40 +# audio/g728 +# audio/g729 +# audio/g7291 +# audio/g729d +# audio/g729e +# audio/gsm +# audio/gsm-efr +# audio/gsm-hr-08 +# audio/ilbc +# audio/ip-mr_v2.5 +# audio/isac +# audio/l16 +# audio/l20 +# audio/l24 +# audio/l8 +# audio/lpc +audio/midi mid midi kar rmi +# audio/mobile-xmf +audio/mp4 mp4a +# audio/mp4a-latm +# audio/mpa +# audio/mpa-robust +audio/mpeg mpga mp2 mp2a mp3 m2a m3a +# audio/mpeg4-generic +# audio/musepack +audio/ogg oga ogg spx +# audio/opus +# audio/parityfec +# audio/pcma +# audio/pcma-wb +# audio/pcmu-wb +# audio/pcmu +# audio/prs.sid +# audio/qcelp +# audio/red +# audio/rtp-enc-aescm128 +# audio/rtp-midi +# audio/rtx +audio/s3m s3m +audio/silk sil +# audio/smv +# audio/smv0 +# audio/smv-qcp +# audio/sp-midi +# audio/speex +# audio/t140c +# audio/t38 +# audio/telephone-event +# audio/tone +# audio/uemclip +# audio/ulpfec +# audio/vdvi +# audio/vmr-wb +# audio/vnd.3gpp.iufp +# audio/vnd.4sb +# audio/vnd.audiokoz +# audio/vnd.celp +# audio/vnd.cisco.nse +# audio/vnd.cmles.radio-events +# audio/vnd.cns.anp1 +# audio/vnd.cns.inf1 +audio/vnd.dece.audio uva uvva +audio/vnd.digital-winds eol +# audio/vnd.dlna.adts +# audio/vnd.dolby.heaac.1 +# audio/vnd.dolby.heaac.2 +# audio/vnd.dolby.mlp +# audio/vnd.dolby.mps +# audio/vnd.dolby.pl2 +# audio/vnd.dolby.pl2x +# audio/vnd.dolby.pl2z +# audio/vnd.dolby.pulse.1 +audio/vnd.dra dra +audio/vnd.dts dts +audio/vnd.dts.hd dtshd +# audio/vnd.dvb.file +# audio/vnd.everad.plj +# audio/vnd.hns.audio +audio/vnd.lucent.voice lvp +audio/vnd.ms-playready.media.pya pya +# audio/vnd.nokia.mobile-xmf +# audio/vnd.nortel.vbk +audio/vnd.nuera.ecelp4800 ecelp4800 +audio/vnd.nuera.ecelp7470 ecelp7470 +audio/vnd.nuera.ecelp9600 ecelp9600 +# audio/vnd.octel.sbc +# audio/vnd.qcelp +# audio/vnd.rhetorex.32kadpcm +audio/vnd.rip rip +# audio/vnd.sealedmedia.softseal.mpeg +# audio/vnd.vmx.cvsd +# audio/vorbis +# audio/vorbis-config +audio/webm weba +audio/x-aac aac +audio/x-aiff aif aiff aifc +audio/x-caf caf +audio/x-flac flac +audio/x-matroska mka +audio/x-mpegurl m3u +audio/x-ms-wax wax +audio/x-ms-wma wma +audio/x-pn-realaudio ram ra +audio/x-pn-realaudio-plugin rmp +# audio/x-tta +audio/x-wav wav +audio/xm xm +chemical/x-cdx cdx +chemical/x-cif cif +chemical/x-cmdf cmdf +chemical/x-cml cml +chemical/x-csml csml +# chemical/x-pdb +chemical/x-xyz xyz +image/bmp bmp +image/cgm cgm +# image/example +# image/fits +image/g3fax g3 +image/gif gif +image/ief ief +# image/jp2 +image/jpeg jpeg jpg jpe +# image/jpm +# image/jpx +image/ktx ktx +# image/naplps +image/png png +image/prs.btif btif +# image/prs.pti +image/sgi sgi +image/svg+xml svg svgz +# image/t38 +image/tiff tiff tif +# image/tiff-fx +image/vnd.adobe.photoshop psd +# image/vnd.cns.inf2 +image/vnd.dece.graphic uvi uvvi uvg uvvg +image/vnd.dvb.subtitle sub +image/vnd.djvu djvu djv +image/vnd.dwg dwg +image/vnd.dxf dxf +image/vnd.fastbidsheet fbs +image/vnd.fpx fpx +image/vnd.fst fst +image/vnd.fujixerox.edmics-mmr mmr +image/vnd.fujixerox.edmics-rlc rlc +# image/vnd.globalgraphics.pgb +# image/vnd.microsoft.icon +# image/vnd.mix +image/vnd.ms-modi mdi +image/vnd.ms-photo wdp +image/vnd.net-fpx npx +# image/vnd.radiance +# image/vnd.sealed.png +# image/vnd.sealedmedia.softseal.gif +# image/vnd.sealedmedia.softseal.jpg +# image/vnd.svf +image/vnd.wap.wbmp wbmp +image/vnd.xiff xif +image/webp webp +image/x-3ds 3ds +image/x-cmu-raster ras +image/x-cmx cmx +image/x-freehand fh fhc fh4 fh5 fh7 +image/x-icon ico +image/x-mrsid-image sid +image/x-pcx pcx +image/x-pict pic pct +image/x-portable-anymap pnm +image/x-portable-bitmap pbm +image/x-portable-graymap pgm +image/x-portable-pixmap ppm +image/x-rgb rgb +image/x-tga tga +image/x-xbitmap xbm +image/x-xpixmap xpm +image/x-xwindowdump xwd +# message/cpim +# message/delivery-status +# message/disposition-notification +# message/example +# message/external-body +# message/feedback-report +# message/global +# message/global-delivery-status +# message/global-disposition-notification +# message/global-headers +# message/http +# message/imdn+xml +# message/news +# message/partial +message/rfc822 eml mime +# message/s-http +# message/sip +# message/sipfrag +# message/tracking-status +# message/vnd.si.simp +# model/example +model/iges igs iges +model/mesh msh mesh silo +model/vnd.collada+xml dae +model/vnd.dwf dwf +# model/vnd.flatland.3dml +model/vnd.gdl gdl +# model/vnd.gs-gdl +# model/vnd.gs.gdl +model/vnd.gtw gtw +# model/vnd.moml+xml +model/vnd.mts mts +# model/vnd.parasolid.transmit.binary +# model/vnd.parasolid.transmit.text +model/vnd.vtu vtu +model/vrml wrl vrml +model/x3d+binary x3db x3dbz +model/x3d+vrml x3dv x3dvz +model/x3d+xml x3d x3dz +# multipart/alternative +# multipart/appledouble +# multipart/byteranges +# multipart/digest +# multipart/encrypted +# multipart/example +# multipart/form-data +# multipart/header-set +# multipart/mixed +# multipart/parallel +# multipart/related +# multipart/report +# multipart/signed +# multipart/voice-message +# text/1d-interleaved-parityfec +text/cache-manifest appcache +text/calendar ics ifb +text/css css +text/csv csv +# text/directory +# text/dns +# text/ecmascript +# text/enriched +# text/example +# text/fwdred +text/html html htm +# text/javascript +text/n3 n3 +# text/parityfec +text/plain txt text conf def list log in +# text/prs.fallenstein.rst +text/prs.lines.tag dsc +# text/vnd.radisys.msml-basic-layout +# text/red +# text/rfc822-headers +text/richtext rtx +# text/rtf +# text/rtp-enc-aescm128 +# text/rtx +text/sgml sgml sgm +# text/t140 +text/tab-separated-values tsv +text/troff t tr roff man me ms +text/turtle ttl +# text/ulpfec +text/uri-list uri uris urls +text/vcard vcard +# text/vnd.abc +text/vnd.curl curl +text/vnd.curl.dcurl dcurl +text/vnd.curl.scurl scurl +text/vnd.curl.mcurl mcurl +# text/vnd.dmclientscript +text/vnd.dvb.subtitle sub +# text/vnd.esmertec.theme-descriptor +text/vnd.fly fly +text/vnd.fmi.flexstor flx +text/vnd.graphviz gv +text/vnd.in3d.3dml 3dml +text/vnd.in3d.spot spot +# text/vnd.iptc.newsml +# text/vnd.iptc.nitf +# text/vnd.latex-z +# text/vnd.motorola.reflex +# text/vnd.ms-mediapackage +# text/vnd.net2phone.commcenter.command +# text/vnd.si.uricatalogue +text/vnd.sun.j2me.app-descriptor jad +# text/vnd.trolltech.linguist +# text/vnd.wap.si +# text/vnd.wap.sl +text/vnd.wap.wml wml +text/vnd.wap.wmlscript wmls +text/x-asm s asm +text/x-c c cc cxx cpp h hh dic +text/x-fortran f for f77 f90 +text/x-java-source java +text/x-opml opml +text/x-pascal p pas +text/x-nfo nfo +text/x-setext etx +text/x-sfv sfv +text/x-uuencode uu +text/x-vcalendar vcs +text/x-vcard vcf +# text/xml +# text/xml-external-parsed-entity +# video/1d-interleaved-parityfec +video/3gpp 3gp +# video/3gpp-tt +video/3gpp2 3g2 +# video/bmpeg +# video/bt656 +# video/celb +# video/dv +# video/example +video/h261 h261 +video/h263 h263 +# video/h263-1998 +# video/h263-2000 +video/h264 h264 +# video/h264-rcdo +# video/h264-svc +video/jpeg jpgv +# video/jpeg2000 +video/jpm jpm jpgm +video/mj2 mj2 mjp2 +# video/mp1s +# video/mp2p +# video/mp2t +video/mp4 mp4 mp4v mpg4 +# video/mp4v-es +video/mpeg mpeg mpg mpe m1v m2v +# video/mpeg4-generic +# video/mpv +# video/nv +video/ogg ogv +# video/parityfec +# video/pointer +video/quicktime qt mov +# video/raw +# video/rtp-enc-aescm128 +# video/rtx +# video/smpte292m +# video/ulpfec +# video/vc1 +# video/vnd.cctv +video/vnd.dece.hd uvh uvvh +video/vnd.dece.mobile uvm uvvm +# video/vnd.dece.mp4 +video/vnd.dece.pd uvp uvvp +video/vnd.dece.sd uvs uvvs +video/vnd.dece.video uvv uvvv +# video/vnd.directv.mpeg +# video/vnd.directv.mpeg-tts +# video/vnd.dlna.mpeg-tts +video/vnd.dvb.file dvb +video/vnd.fvt fvt +# video/vnd.hns.video +# video/vnd.iptvforum.1dparityfec-1010 +# video/vnd.iptvforum.1dparityfec-2005 +# video/vnd.iptvforum.2dparityfec-1010 +# video/vnd.iptvforum.2dparityfec-2005 +# video/vnd.iptvforum.ttsavc +# video/vnd.iptvforum.ttsmpeg2 +# video/vnd.motorola.video +# video/vnd.motorola.videop +video/vnd.mpegurl mxu m4u +video/vnd.ms-playready.media.pyv pyv +# video/vnd.nokia.interleaved-multimedia +# video/vnd.nokia.videovoip +# video/vnd.objectvideo +# video/vnd.sealed.mpeg1 +# video/vnd.sealed.mpeg4 +# video/vnd.sealed.swf +# video/vnd.sealedmedia.softseal.mov +video/vnd.uvvu.mp4 uvu uvvu +video/vnd.vivo viv +video/webm webm +video/x-f4v f4v +video/x-fli fli +video/x-flv flv +video/x-m4v m4v +video/x-matroska mkv mk3d mks +video/x-mng mng +video/x-ms-asf asf asx +video/x-ms-vob vob +video/x-ms-wm wm +video/x-ms-wmv wmv +video/x-ms-wmx wmx +video/x-ms-wvx wvx +video/x-msvideo avi +video/x-sgi-movie movie +video/x-smv smv +x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/type-is/node_modules/mime/types/node.types b/node_modules/express/node_modules/type-is/node_modules/mime/types/node.types new file mode 100644 index 000000000..55b2cf794 --- /dev/null +++ b/node_modules/express/node_modules/type-is/node_modules/mime/types/node.types @@ -0,0 +1,77 @@ +# What: WebVTT +# Why: To allow formats intended for marking up external text track resources. +# http://dev.w3.org/html5/webvtt/ +# Added by: niftylettuce +text/vtt vtt + +# What: Google Chrome Extension +# Why: To allow apps to (work) be served with the right content type header. +# http://codereview.chromium.org/2830017 +# Added by: niftylettuce +application/x-chrome-extension crx + +# What: HTC support +# Why: To properly render .htc files such as CSS3PIE +# Added by: niftylettuce +text/x-component htc + +# What: HTML5 application cache manifes ('.manifest' extension) +# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps +# per https://developer.mozilla.org/en/offline_resources_in_firefox +# Added by: louisremi +text/cache-manifest manifest + +# What: node binary buffer format +# Why: semi-standard extension w/in the node community +# Added by: tootallnate +application/octet-stream buffer + +# What: The "protected" MP-4 formats used by iTunes. +# Why: Required for streaming music to browsers (?) +# Added by: broofa +application/mp4 m4p +audio/mp4 m4a + +# What: Video format, Part of RFC1890 +# Why: See https://github.com/bentomas/node-mime/pull/6 +# Added by: mjrusso +video/MP2T ts + +# What: EventSource mime type +# Why: mime type of Server-Sent Events stream +# http://www.w3.org/TR/eventsource/#text-event-stream +# Added by: francois2metz +text/event-stream event-stream + +# What: Mozilla App manifest mime type +# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests +# Added by: ednapiranha +application/x-web-app-manifest+json webapp + +# What: Lua file types +# Why: Googling around shows de-facto consensus on these +# Added by: creationix (Issue #45) +text/x-lua lua +application/x-lua-bytecode luac + +# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax +# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown +# Added by: avoidwork +text/x-markdown markdown md mkd + +# What: ini files +# Why: because they're just text files +# Added by: Matthew Kastor +text/plain ini + +# What: DASH Adaptive Streaming manifest +# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video +# Added by: eelcocramer +application/dash+xml mdp + +# What: OpenType font files - http://www.microsoft.com/typography/otspec/ +# Why: Browsers usually ignore the font MIME types and sniff the content, +# but Chrome, shows a warning if OpenType fonts aren't served with +# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. +# Added by: alrra +font/opentype otf diff --git a/node_modules/express/node_modules/type-is/package.json b/node_modules/express/node_modules/type-is/package.json new file mode 100644 index 000000000..037066625 --- /dev/null +++ b/node_modules/express/node_modules/type-is/package.json @@ -0,0 +1,33 @@ +{ + "name": "type-is", + "description": "Infer the content type if a request", + "version": "1.1.0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/type-is" + }, + "dependencies": { + "mime": "~1.2.11" + }, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec --bail" + }, + "readme": "# Type Is [![Build Status](https://travis-ci.org/expressjs/type-is.png)](https://travis-ci.org/expressjs/type-is)\n\nInfer the content type of a request. \nExtracted from [koa](https://github.com/koajs/koa) for general use.\n\nHere's an example body parser:\n\n```js\nvar is = require('type-is');\nvar parse = require('body');\nvar busboy = require('busboy');\n\nfunction bodyParser(req, res, next) {\n var hasRequestBody = 'content-type' in req.headers\n || 'transfer-encoding' in req.headers;\n if (!hasRequestBody) return next();\n \n switch (is(req, ['urlencoded', 'json', 'multipart'])) {\n case 'urlencoded':\n // parse urlencoded body\n break\n case 'json':\n // parse json body\n break\n case 'multipart':\n // parse multipart body\n break\n default:\n // 415 error code\n }\n}\n```\n\n## API\n\n### var type = is(request, types)\n\n```js\nvar is = require('type-is')\n\nhttp.createServer(function (req, res) {\n is(req, ['text/*'])\n})\n```\n\n`request` is the node HTTP request. `types` is an array of types. Each type can be:\n\n- An extension name such as `json`. This name will be returned if matched.\n- A mime type such as `application/json`.\n- A mime type with a wildcard such as `*/json` or `application/*`. The full mime type will be returned if matched\n\n`false` will be returned if no type matches.\n\nExamples:\n\n```js\n// req.headers.content-type = 'application/json'\nis(req, ['json']) // -> 'json'\nis(req, ['html', 'json']) // -> 'json'\nis(req, ['application/*']) // -> 'application/json'\nis(req, ['application/json']) // -> 'application/json'\nis(req, ['html']) // -> false\n```\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/expressjs/type-is/issues" + }, + "homepage": "https://github.com/expressjs/type-is", + "_id": "type-is@1.1.0", + "_from": "type-is@1.1.0" +} diff --git a/node_modules/express/node_modules/utils-merge/.travis.yml b/node_modules/express/node_modules/utils-merge/.travis.yml new file mode 100644 index 000000000..af92b021b --- /dev/null +++ b/node_modules/express/node_modules/utils-merge/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" diff --git a/node_modules/express/node_modules/utils-merge/LICENSE b/node_modules/express/node_modules/utils-merge/LICENSE new file mode 100644 index 000000000..e33bd10bb --- /dev/null +++ b/node_modules/express/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +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/express/node_modules/utils-merge/README.md b/node_modules/express/node_modules/utils-merge/README.md new file mode 100644 index 000000000..2f94e9bd2 --- /dev/null +++ b/node_modules/express/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +Merges the properties from a source object into a destination object. + +## Install + + $ npm install utils-merge + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## Tests + + $ npm install + $ npm test + +[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge) + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/node_modules/express/node_modules/utils-merge/index.js b/node_modules/express/node_modules/utils-merge/index.js new file mode 100644 index 000000000..4265c694f --- /dev/null +++ b/node_modules/express/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/node_modules/express/node_modules/utils-merge/package.json b/node_modules/express/node_modules/utils-merge/package.json new file mode 100644 index 000000000..e65538390 --- /dev/null +++ b/node_modules/express/node_modules/utils-merge/package.json @@ -0,0 +1,61 @@ +{ + "name": "utils-merge", + "version": "1.0.0", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "engines": { + "node": ">= 0.4.0" + }, + "readme": "# utils-merge\n\nMerges the properties from a source object into a destination object.\n\n## Install\n\n $ npm install utils-merge\n\n## Usage\n\n```javascript\nvar a = { foo: 'bar' }\n , b = { bar: 'baz' };\n\nmerge(a, b);\n// => { foo: 'bar', bar: 'baz' }\n```\n\n## Tests\n\n $ npm install\n $ npm test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge)\n\n## Credits\n\n - [Jared Hanson](http://github.com/jaredhanson)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n", + "readmeFilename": "README.md", + "_id": "utils-merge@1.0.0", + "dist": { + "shasum": "0294fb922bb9375153541c4f7096231f287c8af8", + "tarball": "http://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz" + }, + "_from": "utils-merge@1.0.0", + "_npmVersion": "1.2.25", + "_npmUser": { + "name": "jaredhanson", + "email": "jaredhanson@gmail.com" + }, + "maintainers": [ + { + "name": "jaredhanson", + "email": "jaredhanson@gmail.com" + } + ], + "directories": {}, + "_shasum": "0294fb922bb9375153541c4f7096231f287c8af8", + "_resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", + "homepage": "https://github.com/jaredhanson/utils-merge" +} diff --git a/node_modules/express/package.json b/node_modules/express/package.json new file mode 100644 index 000000000..c018dc90b --- /dev/null +++ b/node_modules/express/package.json @@ -0,0 +1,103 @@ +{ + "name": "express", + "description": "Sinatra inspired web development framework", + "version": "4.1.2", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + } + ], + "dependencies": { + "parseurl": "1.0.1", + "accepts": "1.0.1", + "type-is": "1.1.0", + "range-parser": "1.0.0", + "cookie": "0.1.2", + "buffer-crc32": "0.2.1", + "fresh": "0.2.2", + "methods": "0.1.0", + "send": "0.3.0", + "cookie-signature": "1.0.3", + "merge-descriptors": "0.0.2", + "utils-merge": "1.0.0", + "escape-html": "1.0.1", + "qs": "0.6.6", + "serve-static": "1.1.0", + "path-to-regexp": "0.1.2", + "debug": ">= 0.7.3 < 1" + }, + "devDependencies": { + "mocha": "~1.18.2", + "body-parser": "1.0.2", + "connect-redis": "~2.0.0", + "ejs": "~1.0.0", + "express-session": "1.0.3", + "jade": "~0.35.0", + "marked": "0.3.2", + "multiparty": "~3.2.4", + "static-favicon": "1.0.2", + "hjs": "~0.0.6", + "should": "~3.3.1", + "supertest": "~0.11.0", + "method-override": "1.0.0", + "cookie-parser": "1.0.1", + "morgan": "1.0.0", + "vhost": "1.0.0" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/express" + }, + "scripts": { + "prepublish": "npm prune", + "test": "make test" + }, + "engines": { + "node": ">= 0.10.0" + }, + "license": "MIT", + "readme": "[![express logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/)\n\n Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).\n\n [![Build Status](https://travis-ci.org/visionmedia/express.svg?branch=master)](https://travis-ci.org/visionmedia/express) [![Gittip](https://img.shields.io/gittip/visionmedia.svg)](https://www.gittip.com/visionmedia/)\n\n```js\nvar express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n res.send('Hello World');\n});\n\napp.listen(3000);\n```\n\n**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/visionmedia/express/wiki/New-features-in-4.x).\n\n## Installation\n\n $ npm install express\n\n## Quick Start\n\n The quickest way to get started with express is to utilize the executable [`express(1)`](http://github.com/expressjs/generator) to generate an application as shown below:\n \n Install the executable. The executable's major version will match Express's:\n \n $ npm install -g express-generator@3\n\n Create the app:\n\n $ express /tmp/foo && cd /tmp/foo\n\n Install dependencies:\n\n $ npm install\n\n Start the server:\n\n $ npm start\n\n## Features\n\n * Robust routing\n * HTTP helpers (redirection, caching, etc)\n * View system supporting 14+ template engines\n * Content negotiation\n * Focus on high performance\n * Executable for generating applications quickly\n * High test coverage\n\n## Philosophy\n\n The Express philosophy is to provide small, robust tooling for HTTP servers, making\n it a great solution for single page applications, web sites, hybrids, or public\n HTTP APIs.\n\n Express does not force you to use any specific ORM or template engine. With support for over\n 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js),\n you can quickly craft your perfect framework.\n\n## More Information\n\n * [Website and Documentation](http://expressjs.com/) stored at [visionmedia/expressjs.com](https://github.com/visionmedia/expressjs.com)\n * Join #express on freenode\n * [Google Group](http://groups.google.com/group/express-js) for discussion\n * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) and [defunctzombie](https://twitter.com/defunctzombie) on twitter for updates\n * Visit the [Wiki](http://github.com/visionmedia/express/wiki)\n * [Русскоязычная документация](http://jsman.ru/express/)\n * Run express examples [online](https://runnable.com/express)\n\n## Viewing Examples\n\nClone the Express repo, then install the dev dependencies to install all the example / test suite dependencies:\n\n $ git clone git://github.com/visionmedia/express.git --depth 1\n $ cd express\n $ npm install\n\nThen run whichever tests you want:\n\n $ node examples/content-negotiation\n\nYou can also view live examples here:\n\n\n\n## Running Tests\n\nTo run the test suite, first invoke the following command within the repo, installing the development dependencies:\n\n $ npm install\n\nThen run the tests:\n\n $ make test\n\n## Contributors\n \n Author: [TJ Holowaychuk](http://github.com/visionmedia) \n Lead Maintainer: [Roman Shtylman](https://github.com/defunctzombie) \n Contributors: https://github.com/visionmedia/express/graphs/contributors \n\n## License\n\nMIT\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/visionmedia/express/issues" + }, + "homepage": "https://github.com/visionmedia/express", + "_id": "express@4.1.2", + "_from": "express@~4.1.1" +} diff --git a/node_modules/jade/.npmignore b/node_modules/jade/.npmignore new file mode 100644 index 000000000..fdc7b8933 --- /dev/null +++ b/node_modules/jade/.npmignore @@ -0,0 +1,14 @@ +test +support +benchmarks +examples +lib-cov +coverage.html +.gitmodules +.travis.yml +History.md +Makefile +test/ +support/ +benchmarks/ +examples/ diff --git a/node_modules/jade/LICENSE b/node_modules/jade/LICENSE new file mode 100644 index 000000000..8ad0e0d3e --- /dev/null +++ b/node_modules/jade/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2009-2010 TJ Holowaychuk + +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. \ No newline at end of file diff --git a/node_modules/jade/Readme.md b/node_modules/jade/Readme.md new file mode 100644 index 000000000..9eb6fbc33 --- /dev/null +++ b/node_modules/jade/Readme.md @@ -0,0 +1,1308 @@ +# Jade - template engine +[![Build Status](https://secure.travis-ci.org/visionmedia/jade.png)](http://travis-ci.org/visionmedia/jade) +[![Dependency Status](https://gemnasium.com/visionmedia/jade.png)](https://gemnasium.com/visionmedia/jade) +[![NPM version](https://badge.fury.io/js/jade.png)](http://badge.fury.io/js/jade) + + Jade is a high performance template engine heavily influenced by [Haml](http://haml-lang.com) + and implemented with JavaScript for [node](http://nodejs.org). For discussion join the [Google Group](http://groups.google.com/group/jadejs). + +## Announcement + +Jade version 0.31.0 deprecated implicit text only support for scripts and styles. To fix this all you need to do is add a `.` character after the script or style tag. + +It is hoped that this change will make Jade easier for newcomers to learn without affecting the power of the language or leading to excessive verboseness. + +If you have a lot of Jade files that need fixing you can use [fix-jade](https://github.com/ForbesLindesay/fix-jade) to attempt to automate the process. + +## Test drive + + You can test drive Jade online [here](http://naltatis.github.com/jade-syntax-docs). + +## README Contents + +- [Features](#a1) +- [Implementations](#a2) +- [Installation](#a3) +- [Browser Support](#a4) +- [Public API](#a5) +- [Syntax](#a6) + - [Line Endings](#a6-1) + - [Tags](#a6-2) + - [Tag Text](#a6-3) + - [Comments](#a6-4) + - [Block Comments](#a6-5) + - [Nesting](#a6-6) + - [Block Expansion](#a6-7) + - [Case](#a6-8) + - [Attributes](#a6-9) + - [HTML](#a6-10) + - [Doctypes](#a6-11) +- [Filters](#a7) +- [Code](#a8) +- [Iteration](#a9) +- [Conditionals](#a10) +- [Template inheritance](#a11) +- [Block append / prepend](#a12) +- [Includes](#a13) +- [Mixins](#a14) +- [Generated Output](#a15) +- [Example Makefile](#a16) +- [jade(1)](#a17) +- [Tutorials](#a18) +- [License](#a19) + + +## Features + + - client-side support + - great readability + - flexible indentation + - block-expansion + - mixins + - static includes + - attribute interpolation + - code is escaped by default for security + - contextual error reporting at compile & run time + - executable for compiling jade templates via the command line + - html 5 mode (the default doctype) + - optional memory caching + - combine dynamic and static tag classes + - parse tree manipulation via _filters_ + - template inheritance + - block append / prepend + - supports [Express JS](http://expressjs.com) out of the box + - transparent iteration over objects, arrays, and even non-enumerables via `each` + - block comments + - no tag prefix + - filters + - :stylus must have [stylus](http://github.com/LearnBoost/stylus) installed + - :less must have [less.js](http://github.com/cloudhead/less.js) installed + - :markdown must have [markdown-js](http://github.com/evilstreak/markdown-js), [node-discount](http://github.com/visionmedia/node-discount), or [marked](http://github.com/chjj/marked) installed + - :cdata + - :coffeescript must have [coffee-script](http://jashkenas.github.com/coffee-script/) installed + - [Emacs Mode](https://github.com/brianc/jade-mode) + - [Vim Syntax](https://github.com/digitaltoad/vim-jade) + - [TextMate Bundle](http://github.com/miksago/jade-tmbundle) + - [Coda/SubEtha syntax Mode](https://github.com/aaronmccall/jade.mode) + - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs) + - [html2jade](https://github.com/donpark/html2jade) converter + + +## Implementations + + - [php](http://github.com/everzet/jade.php) + - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html) + - [ruby](https://github.com/slim-template/slim) + - [python](https://github.com/SyrusAkbary/pyjade) + - [java](https://github.com/neuland/jade4j) + + +## Installation + +via npm: + +```bash +$ npm install jade +``` + + +## Browser Support + + To compile jade to a single file compatible for client-side use simply execute: + +```bash +$ make jade.js +``` + + Alternatively, if uglifyjs is installed via npm (`npm install uglify-js`) you may execute the following which will create both files. However each release builds these for you. + +```bash +$ make jade.min.js +``` + + By default Jade instruments templates with line number statements such as `__.lineno = 3` for debugging purposes. When used in a browser it's useful to minimize this boiler plate, you can do so by passing the option `{ compileDebug: false }`. The following template + +```jade +p Hello #{name} +``` + + Can then be as small as the following generated function: + +```js +function anonymous(locals, attrs, escape, rethrow) { + var buf = []; + with (locals || {}) { + var interp; + buf.push('\n

Hello ' + escape((interp = name) == null ? '' : interp) + '\n

'); + } + return buf.join(""); +} +``` + + Through the use of Jade's `./runtime.js` you may utilize these pre-compiled templates on the client-side _without_ Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as `jade.attrs`, `jade.escape` etc. To enable this you should pass `{ client: true }` to `jade.compile()` to tell Jade to reference the helper functions + via `jade.attrs`, `jade.escape` etc. + +```js +function anonymous(locals, attrs, escape, rethrow) { + var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; + var buf = []; + with (locals || {}) { + var interp; + buf.push('\n

Hello ' + escape((interp = name) == null ? '' : interp) + '\n

'); + } + return buf.join(""); +} +``` + +
+## Public API + +```js +var jade = require('jade'); + +// Compile a function +var fn = jade.compile('string of jade', options); +fn(locals); +``` + +### Options + + - `self` Use a `self` namespace to hold the locals _(false by default)_ + - `locals` Local variable object + - `filename` Used in exceptions, and required when using includes + - `debug` Outputs tokens and function body generated + - `compiler` Compiler to replace jade's default + - `compileDebug` When `false` no debug instrumentation is compiled + - `pretty` Add pretty-indentation whitespace to output _(false by default)_ + + +## Syntax + + +### Line Endings + +**CRLF** and **CR** are converted to **LF** before parsing. + + +### Tags + +A tag is simply a leading word: + +```jade +html +``` + +for example is converted to `` + +tags can also have ids: + +```jade +div#container +``` + +which would render `
` + +how about some classes? + +```jade +div.user-details +``` + +renders `
` + +multiple classes? _and_ an id? sure: + +```jade +div#foo.bar.baz +``` + +renders `
` + +div div div sure is annoying, how about: + +```jade +#foo +.bar +``` + +which is syntactic sugar for what we have already been doing, and outputs: + +```html +
+``` + +
+### Tag Text + +Simply place some content after the tag: + +```jade +p wahoo! +``` + +renders `

wahoo!

`. + +well cool, but how about large bodies of text: + +```jade +p + | foo bar baz + | rawr rawr + | super cool + | go jade go +``` + +renders `

foo bar baz rawr.....

` + +interpolation? yup! both types of text can utilize interpolation, +if we passed `{ name: 'tj', email: 'tj@vision-media.ca' }` to the compiled function we can do the following: + +```jade +#user #{name} <#{email}> +``` + +outputs `
tj <tj@vision-media.ca>
` + +Actually want `#{}` for some reason? escape it! + +```jade +p \#{something} +``` + +now we have `

#{something}

` + +We can also utilize the unescaped variant `!{html}`, so the following +will result in a literal script tag: + +```jade +- var html = "" +| !{html} +``` + +Nested tags that also contain text can optionally use a text block: + +```jade +label + | Username: + input(name='user[name]') +``` + +or immediate tag text: + +```jade +label Username: + input(name='user[name]') +``` + +As an alternative, we may use a trailing `.` to indicate a text block, for example: + +```jade +p. + foo asdf + asdf + asdfasdfaf + asdf + asd. +``` + +outputs: + +```html +

foo asdf +asdf + asdfasdfaf + asdf +asd. +

+``` + +This however differs from a trailing `.` followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal: + +```jade +p . +``` + +outputs: + +```html +

.

+``` + +It should be noted that text blocks should be doubled escaped. For example if you desire the following output. + +```html +

foo\bar

+``` + +use: + +```jade +p. + foo\\bar +``` + +
+### Comments + +Single line comments currently look the same as JavaScript comments, +aka `//` and must be placed on their own line: + +```jade +// just some paragraphs +p foo +p bar +``` + +would output + +```html + +

foo

+

bar

+``` + +Jade also supports unbuffered comments, by simply adding a hyphen: + +```jade +//- will not output within markup +p foo +p bar +``` + +outputting + +```html +

foo

+

bar

+``` + +
+### Block Comments + + A block comment is legal as well: + +```jade +body + // + #content + h1 Example +``` + +outputting + +```html + + + +``` + +Jade supports conditional-comments as well, for example: + +```jade +head + //if lt IE 8 + script(src='/ie-sucks.js') +``` + +outputs: + +```html + + + +``` + + +### Nesting + + Jade supports nesting to define the tags in a natural way: + +```jade +ul + li.first + a(href='#') foo + li + a(href='#') bar + li.last + a(href='#') baz +``` + + +### Block Expansion + + Block expansion allows you to create terse single-line nested tags, + the following example is equivalent to the nesting example above. + +```jade +ul + li.first: a(href='#') foo + li: a(href='#') bar + li.last: a(href='#') baz +``` + + +### Case + + The case statement takes the following form: + +```jade +html + body + friends = 10 + case friends + when 0 + p you have no friends + when 1 + p you have a friend + default + p you have #{friends} friends +``` + + Block expansion may also be used: + +```jade +friends = 5 + +html + body + case friends + when 0: p you have no friends + when 1: p you have a friend + default: p you have #{friends} friends +``` + + +### Attributes + +Jade currently supports `(` and `)` as attribute delimiters. + +```jade +a(href='/login', title='View login page') Login +``` + +When a value is `undefined` or `null` the attribute is _not_ added, +so this is fine, it will not compile `something="null"`. + +```jade +div(something=null) +``` + +Boolean attributes are also supported: + +```jade +input(type="checkbox", checked) +``` + +Boolean attributes with code will only output the attribute when `true`: + +```jade +input(type="checkbox", checked=someValue) +``` + +Multiple lines work too: + +```jade +input(type='checkbox', + name='agreement', + checked) +``` + +Multiple lines without the comma work fine: + +```jade +input(type='checkbox' + name='agreement' + checked) +``` + +Funky whitespace? fine: + +```jade +input( + type='checkbox' + name='agreement' + checked) +``` + +Colons work: + +```jade +rss(xmlns:atom="atom") +``` + +Suppose we have the `user` local `{ id: 12, name: 'tobi' }` +and we wish to create an anchor tag with `href` pointing to "/user/12" +we could use regular javascript concatenation: + +```jade +a(href='/user/' + user.id)= user.name +``` + +or we could use jade's interpolation, which I added because everyone +using Ruby or CoffeeScript seems to think this is legal js..: + +```jade +a(href='/user/#{user.id}')= user.name +``` + +The `class` attribute is special-cased when an array is given, +allowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly: + +```jade +body(class=bodyClasses) +``` + + +### HTML + + Inline html is fine, we can use the pipe syntax to + write arbitrary text, in this case some html: + +```jade +html + body + |

Title

+ |

foo bar baz

+``` + + Or we can use the trailing `.` to indicate to Jade that we + only want text in this block, allowing us to omit the pipes: + +```jade +html + body. +

Title

+

foo bar baz

+``` + + Both of these examples yield the same result: + +```html +

Title

+

foo bar baz

+ +``` + + The same rule applies for anywhere you can have text + in jade, raw html is fine: + +```jade +html + body + h1 User #{name} +``` + +
+### Doctypes + +To add a doctype simply use `!!!`, or `doctype` followed by an optional value: + +```jade +!!! +``` + +or + +```jade +doctype +``` + +Will output the _html 5_ doctype, however: + +```jade +!!! transitional +``` + +Will output the _transitional_ doctype. + +Doctypes are case-insensitive, so the following are equivalent: + +```jade +doctype Basic +doctype basic +``` + +it's also possible to simply pass a doctype literal: + +```jade +doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" +``` + +yielding: + +```html + +``` + +Below are the doctypes defined by default, which can easily be extended: + +```js +var doctypes = exports.doctypes = { + '5': '', + 'default': '', + 'xml': '', + 'transitional': '', + 'strict': '', + 'frameset': '', + '1.1': '', + 'basic': '', + 'mobile': '' +}; +``` + +To alter the default simply change: + +```js +jade.doctypes.default = 'whatever you want'; +``` + + +## Filters + +Filters are prefixed with `:`, for example `:markdown` and +pass the following block of text to an arbitrary function for processing. View the _features_ +at the top of this document for available filters. + +```jade +body + :markdown + Woah! jade _and_ markdown, very **cool** + we can even link to [stuff](http://google.com) +``` + +Renders: + +```html +

Woah! jade and markdown, very cool we can even link to stuff

+``` + + +## Code + +Jade currently supports three classifications of executable code. The first +is prefixed by `-`, and is not buffered: + +```jade +- var foo = 'bar'; +``` + +This can be used for conditionals, or iteration: + +```jade +- for (var key in obj) + p= obj[key] +``` + +Due to Jade's buffering techniques the following is valid as well: + +```jade +- if (foo) + ul + li yay + li foo + li worked +- else + p oh no! didnt work +``` + +Hell, even verbose iteration: + +```jade +- if (items.length) + ul + - items.forEach(function(item){ + li= item + - }) +``` + +Anything you want! + +Next up we have _escaped_ buffered code, which is used to +buffer a return value, which is prefixed by `=`: + +```jade +- var foo = 'bar' += foo +h1= foo +``` + +Which outputs `bar

bar

`. Code buffered by `=` is escaped +by default for security, however to output unescaped return values +you may use `!=`: + +```jade +p!= aVarContainingMoreHTML +``` + + Jade also has designer-friendly variants, making the literal JavaScript + more expressive and declarative. For example the following assignments + are equivalent, and the expression is still regular javascript: + +```jade +- var foo = 'foo ' + 'bar' +foo = 'foo ' + 'bar' +``` + + Likewise Jade has first-class `if`, `else if`, `else`, `until`, `while`, `unless` among others, however you must remember that the expressions are still regular javascript: + +```jade +if foo == 'bar' + ul + li yay + li foo + li worked +else + p oh no! didnt work +``` + +
+## Iteration + + Along with vanilla JavaScript Jade also supports a subset of + constructs that allow you to create more designer-friendly templates, + one of these constructs is `each`, taking the form: + +```jade +each VAL[, KEY] in OBJ +``` + +An example iterating over an array: + +```jade +- var items = ["one", "two", "three"] +each item in items + li= item +``` + +outputs: + +```html +
  • one
  • +
  • two
  • +
  • three
  • +``` + +iterating an array with index: + +```jade +items = ["one", "two", "three"] +each item, i in items + li #{item}: #{i} +``` + +outputs: + +```html +
  • one: 0
  • +
  • two: 1
  • +
  • three: 2
  • +``` + +iterating an object's keys and values: + +```jade +obj = { foo: 'bar' } +each val, key in obj + li #{key}: #{val} +``` + +would output `
  • foo: bar
  • ` + +Internally Jade converts these statements to regular +JavaScript loops such as `users.forEach(function(user){`, +so lexical scope and nesting applies as it would with regular +JavaScript: + +```jade +each user in users + each role in user.roles + li= role +``` + + You may also use `for` if you prefer: + +```jade +for user in users + for role in user.roles + li= role +``` + +
    +## Conditionals + + Jade conditionals are equivalent to those using the code (`-`) prefix, + however allow you to ditch parenthesis to become more designer friendly, + however keep in mind the expression given is _regular_ JavaScript: + +```jade +for user in users + if user.role == 'admin' + p #{user.name} is an admin + else + p= user.name +``` + + is equivalent to the following using vanilla JavaScript literals: + +```jade +for user in users + - if (user.role == 'admin') + p #{user.name} is an admin + - else + p= user.name +``` + + Jade also provides `unless` which is equivalent to `if (!(expr))`: + +```jade +for user in users + unless user.isAnonymous + p + | Click to view + a(href='/users/' + user.id)= user.name +``` + + +## Template inheritance + + Jade supports template inheritance via the `block` and `extends` keywords. A block is simply a "block" of Jade that may be replaced within a child template, this process is recursive. To activate template inheritance in Express 2.x you must add: `app.set('view options', { layout: false });`. + + Jade blocks can provide default content if desired, however optional as shown below by `block scripts`, `block content`, and `block foot`. + +```jade +html + head + h1 My Site - #{title} + block scripts + script(src='/jquery.js') + body + block content + block foot + #footer + p some footer content +``` + + Now to extend the layout, simply create a new file and use the `extends` directive as shown below, giving the path (with or without the .jade extension). You may now define one or more blocks that will override the parent block content, note that here the `foot` block is _not_ redefined and will output "some footer content". + +```jade +extends layout + +block scripts + script(src='/jquery.js') + script(src='/pets.js') + +block content + h1= title + each pet in pets + include pet +``` + + It's also possible to override a block to provide additional blocks, as shown in the following example where `content` now exposes a `sidebar` and `primary` block for overriding, or the child template could override `content` all together. + +```jade +extends regular-layout + +block content + .sidebar + block sidebar + p nothing + .primary + block primary + p nothing +``` + + +## Block append / prepend + + Jade allows you to _replace_ (default), _prepend_, or _append_ blocks. Suppose for example you have default scripts in a "head" block that you wish to utilize on _every_ page, you might do this: + +```jade +html + head + block head + script(src='/vendor/jquery.js') + script(src='/vendor/caustic.js') + body + block content +``` + + Now suppose you have a page of your application for a JavaScript game, you want some game related scripts as well as these defaults, you can simply `append` the block: + +```jade +extends layout + +block append head + script(src='/vendor/three.js') + script(src='/game.js') +``` + + When using `block append` or `block prepend` the `block` is optional: + +```jade +extends layout + +append head + script(src='/vendor/three.js') + script(src='/game.js') +``` + + +## Includes + + Includes allow you to statically include chunks of Jade, + or other content like css, or html which lives in separate files. The classical example is including a header and footer. Suppose we have the following directory structure: + + ./layout.jade + ./includes/ + ./head.jade + ./foot.jade + +and the following _layout.jade_: + +```jade +html + include includes/head + body + h1 My Site + p Welcome to my super amazing site. + include includes/foot +``` + +both includes _includes/head_ and _includes/foot_ are +read relative to the `filename` option given to _layout.jade_, +which should be an absolute path to this file, however Express +does this for you. Include then parses these files, and injects +the AST produced to render what you would expect: + +```html + + + My Site + + + +

    My Site

    +

    Welcome to my super lame site.

    + + + +``` + +As mentioned `include` can be used to include other content +such as html or css. By providing an extension, Jade will +read that file in, apply any [filter](#a7) matching the file's +extension, and insert that content into the output. + +```jade +html + head + //- css and js have simple filters that wrap them in + '; + } else if (transformers[name].outputFormat === 'xml') { + res = res.replace(/'/g, '''); + } + } else { + throw new Error('unknown filter ":' + name + '"'); + } + return res; +} +filter.exists = function (name, str, options) { + return typeof filter[name] === 'function' || transformers[name]; +}; diff --git a/node_modules/jade/lib/index.js b/node_modules/jade/lib/index.js new file mode 100644 index 000000000..6a783c22e --- /dev/null +++ b/node_modules/jade/lib/index.js @@ -0,0 +1 @@ +jade.js \ No newline at end of file diff --git a/node_modules/jade/lib/inline-tags.js b/node_modules/jade/lib/inline-tags.js new file mode 100644 index 000000000..491de0b51 --- /dev/null +++ b/node_modules/jade/lib/inline-tags.js @@ -0,0 +1,28 @@ + +/*! + * Jade - inline tags + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +module.exports = [ + 'a' + , 'abbr' + , 'acronym' + , 'b' + , 'br' + , 'code' + , 'em' + , 'font' + , 'i' + , 'img' + , 'ins' + , 'kbd' + , 'map' + , 'samp' + , 'small' + , 'span' + , 'strong' + , 'sub' + , 'sup' +]; \ No newline at end of file diff --git a/node_modules/jade/lib/jade.js b/node_modules/jade/lib/jade.js new file mode 100644 index 000000000..22cbae022 --- /dev/null +++ b/node_modules/jade/lib/jade.js @@ -0,0 +1,242 @@ +/*! + * Jade + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Parser = require('./parser') + , Lexer = require('./lexer') + , Compiler = require('./compiler') + , runtime = require('./runtime') + , addWith = require('with') + , fs = require('fs'); + +/** + * Library version. + */ + +exports.version = '0.30.0'; + +/** + * Expose self closing tags. + */ + +exports.selfClosing = require('./self-closing'); + +/** + * Default supported doctypes. + */ + +exports.doctypes = require('./doctypes'); + +/** + * Text filters. + */ + +exports.filters = require('./filters'); + +/** + * Utilities. + */ + +exports.utils = require('./utils'); + +/** + * Expose `Compiler`. + */ + +exports.Compiler = Compiler; + +/** + * Expose `Parser`. + */ + +exports.Parser = Parser; + +/** + * Expose `Lexer`. + */ + +exports.Lexer = Lexer; + +/** + * Nodes. + */ + +exports.nodes = require('./nodes'); + +/** + * Jade runtime helpers. + */ + +exports.runtime = runtime; + +/** + * Template function cache. + */ + +exports.cache = {}; + +/** + * Parse the given `str` of jade and return a function body. + * + * @param {String} str + * @param {Object} options + * @return {String} + * @api private + */ + +function parse(str, options){ + try { + // Parse + var parser = new (options.parser || Parser)(str, options.filename, options); + + // Compile + var compiler = new (options.compiler || Compiler)(parser.parse(), options) + , js = compiler.compile(); + + // Debug compiler + if (options.debug) { + console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); + } + + return '' + + 'var buf = [];\n' + + (options.self + ? 'var self = locals || {};\n' + js + : addWith('locals || {}', js, ['jade', 'buf'])) + ';' + + 'return buf.join("");'; + } catch (err) { + parser = parser.context(); + runtime.rethrow(err, parser.filename, parser.lexer.lineno); + } +} + +/** + * Strip any UTF-8 BOM off of the start of `str`, if it exists. + * + * @param {String} str + * @return {String} + * @api private + */ + +function stripBOM(str){ + return 0xFEFF == str.charCodeAt(0) + ? str.substring(1) + : str; +} + +/** + * Compile a `Function` representation of the given jade `str`. + * + * Options: + * + * - `compileDebug` when `false` debugging code is stripped from the compiled template + * - `filename` used to improve errors when `compileDebug` is not `false` + * + * @param {String} str + * @param {Options} options + * @return {Function} + * @api public + */ + +exports.compile = function(str, options){ + var options = options || {} + , filename = options.filename + ? JSON.stringify(options.filename) + : 'undefined' + , fn; + + str = stripBOM(String(str)); + + if (options.compileDebug !== false) { + fn = [ + 'jade.debug = [{ lineno: 1, filename: ' + filename + ' }];' + , 'try {' + , parse(str, options) + , '} catch (err) {' + , ' jade.rethrow(err, jade.debug[0].filename, jade.debug[0].lineno);' + , '}' + ].join('\n'); + } else { + fn = parse(str, options); + } + + if (options.client) return new Function('locals', fn) + fn = new Function('locals, jade', fn) + return function(locals){ return fn(locals, Object.create(runtime)) } +}; + +/** + * Render the given `str` of jade and invoke + * the callback `fn(err, str)`. + * + * Options: + * + * - `cache` enable template caching + * - `filename` filename required for `include` / `extends` and caching + * + * @param {String} str + * @param {Object|Function} options or fn + * @param {Function} fn + * @api public + */ + +exports.render = function(str, options, fn){ + // swap args + if ('function' == typeof options) { + fn = options, options = {}; + } + + // cache requires .filename + if (options.cache && !options.filename) { + return fn(new Error('the "filename" option is required for caching')); + } + + try { + var path = options.filename; + var tmpl = options.cache + ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) + : exports.compile(str, options); + fn(null, tmpl(options)); + } catch (err) { + fn(err); + } +}; + +/** + * Render a Jade file at the given `path` and callback `fn(err, str)`. + * + * @param {String} path + * @param {Object|Function} options or callback + * @param {Function} fn + * @api public + */ + +exports.renderFile = function(path, options, fn){ + var key = path + ':string'; + + if ('function' == typeof options) { + fn = options, options = {}; + } + + try { + options.filename = path; + var str = options.cache + ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) + : fs.readFileSync(path, 'utf8'); + exports.render(str, options, fn); + } catch (err) { + fn(err); + } +}; + +/** + * Express support. + */ + +exports.__express = exports.renderFile; diff --git a/node_modules/jade/lib/lexer.js b/node_modules/jade/lib/lexer.js new file mode 100644 index 000000000..ac0ce2b26 --- /dev/null +++ b/node_modules/jade/lib/lexer.js @@ -0,0 +1,782 @@ +/*! + * Jade - Lexer + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +var utils = require('./utils'); +var parseJSExpression = require('character-parser').parseMax; + +/** + * Initialize `Lexer` with the given `str`. + * + * Options: + * + * - `colons` allow colons for attr delimiters + * + * @param {String} str + * @param {Object} options + * @api private + */ + +var Lexer = module.exports = function Lexer(str, options) { + options = options || {}; + this.input = str.replace(/\r\n|\r/g, '\n'); + this.colons = options.colons; + this.deferredTokens = []; + this.lastIndents = 0; + this.lineno = 1; + this.stash = []; + this.indentStack = []; + this.indentRe = null; + this.pipeless = false; +}; + +/** + * Lexer prototype. + */ + +Lexer.prototype = { + + /** + * Construct a token with the given `type` and `val`. + * + * @param {String} type + * @param {String} val + * @return {Object} + * @api private + */ + + tok: function(type, val){ + return { + type: type + , line: this.lineno + , val: val + } + }, + + /** + * Consume the given `len` of input. + * + * @param {Number} len + * @api private + */ + + consume: function(len){ + this.input = this.input.substr(len); + }, + + /** + * Scan for `type` with the given `regexp`. + * + * @param {String} type + * @param {RegExp} regexp + * @return {Object} + * @api private + */ + + scan: function(regexp, type){ + var captures; + if (captures = regexp.exec(this.input)) { + this.consume(captures[0].length); + return this.tok(type, captures[1]); + } + }, + + /** + * Defer the given `tok`. + * + * @param {Object} tok + * @api private + */ + + defer: function(tok){ + this.deferredTokens.push(tok); + }, + + /** + * Lookahead `n` tokens. + * + * @param {Number} n + * @return {Object} + * @api private + */ + + lookahead: function(n){ + var fetch = n - this.stash.length; + while (fetch-- > 0) this.stash.push(this.next()); + return this.stash[--n]; + }, + + /** + * Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters. + * + * @return {Number} + * @api private + */ + + bracketExpression: function(skip){ + skip = skip || 0; + var start = this.input[skip]; + if (start != '(' && start != '{' && start != '[') throw new Error('unrecognized start character'); + var end = ({'(': ')', '{': '}', '[': ']'})[start]; + var range = parseJSExpression(this.input, {start: skip + 1}); + if (this.input[range.end] !== end) throw new Error('start character ' + start + ' does not match end character ' + this.input[range.end]); + return range; + }, + + /** + * Stashed token. + */ + + stashed: function() { + return this.stash.length + && this.stash.shift(); + }, + + /** + * Deferred token. + */ + + deferred: function() { + return this.deferredTokens.length + && this.deferredTokens.shift(); + }, + + /** + * end-of-source. + */ + + eos: function() { + if (this.input.length) return; + if (this.indentStack.length) { + this.indentStack.shift(); + return this.tok('outdent'); + } else { + return this.tok('eos'); + } + }, + + /** + * Blank line. + */ + + blank: function() { + var captures; + if (captures = /^\n *\n/.exec(this.input)) { + this.consume(captures[0].length - 1); + ++this.lineno; + if (this.pipeless) return this.tok('text', ''); + return this.next(); + } + }, + + /** + * Comment. + */ + + comment: function() { + var captures; + if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { + this.consume(captures[0].length); + var tok = this.tok('comment', captures[2]); + tok.buffer = '-' != captures[1]; + return tok; + } + }, + + /** + * Interpolated tag. + */ + + interpolation: function() { + if (/^#\{/.test(this.input)) { + var match; + try { + match = this.bracketExpression(1); + } catch (ex) { + return;//not an interpolation expression, just an unmatched open interpolation + } + + this.consume(match.end + 1); + return this.tok('interpolation', match.src); + } + }, + + /** + * Tag. + */ + + tag: function() { + var captures; + if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) { + this.consume(captures[0].length); + var tok, name = captures[1]; + if (':' == name[name.length - 1]) { + name = name.slice(0, -1); + tok = this.tok('tag', name); + this.defer(this.tok(':')); + while (' ' == this.input[0]) this.input = this.input.substr(1); + } else { + tok = this.tok('tag', name); + } + tok.selfClosing = !! captures[2]; + return tok; + } + }, + + /** + * Filter. + */ + + filter: function() { + return this.scan(/^:(\w+)/, 'filter'); + }, + + /** + * Doctype. + */ + + doctype: function() { + return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); + }, + + /** + * Id. + */ + + id: function() { + return this.scan(/^#([\w-]+)/, 'id'); + }, + + /** + * Class. + */ + + className: function() { + return this.scan(/^\.([\w-]+)/, 'class'); + }, + + /** + * Text. + */ + + text: function() { + return this.scan(/^(?:\| ?| ?)?([^\n]+)/, 'text'); + }, + + /** + * Extends. + */ + + "extends": function() { + return this.scan(/^extends? +([^\n]+)/, 'extends'); + }, + + /** + * Block prepend. + */ + + prepend: function() { + var captures; + if (captures = /^prepend +([^\n]+)/.exec(this.input)) { + this.consume(captures[0].length); + var mode = 'prepend' + , name = captures[1] + , tok = this.tok('block', name); + tok.mode = mode; + return tok; + } + }, + + /** + * Block append. + */ + + append: function() { + var captures; + if (captures = /^append +([^\n]+)/.exec(this.input)) { + this.consume(captures[0].length); + var mode = 'append' + , name = captures[1] + , tok = this.tok('block', name); + tok.mode = mode; + return tok; + } + }, + + /** + * Block. + */ + + block: function() { + var captures; + if (captures = /^block\b *(?:(prepend|append) +)?([^\n]*)/.exec(this.input)) { + this.consume(captures[0].length); + var mode = captures[1] || 'replace' + , name = captures[2] + , tok = this.tok('block', name); + + tok.mode = mode; + return tok; + } + }, + + /** + * Yield. + */ + + yield: function() { + return this.scan(/^yield */, 'yield'); + }, + + /** + * Include. + */ + + include: function() { + return this.scan(/^include +([^\n]+)/, 'include'); + }, + + /** + * Case. + */ + + "case": function() { + return this.scan(/^case +([^\n]+)/, 'case'); + }, + + /** + * When. + */ + + when: function() { + return this.scan(/^when +([^:\n]+)/, 'when'); + }, + + /** + * Default. + */ + + "default": function() { + return this.scan(/^default */, 'default'); + }, + + /** + * Assignment. + */ + + assignment: function() { + var captures; + if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { + this.consume(captures[0].length); + var name = captures[1] + , val = captures[2]; + return this.tok('code', 'var ' + name + ' = (' + val + ');'); + } + }, + + /** + * Call mixin. + */ + + call: function(){ + var captures; + if (captures = /^\+([-\w]+)/.exec(this.input)) { + this.consume(captures[0].length); + var tok = this.tok('call', captures[1]); + + // Check for args (not attributes) + if (captures = /^ *\(/.exec(this.input)) { + try { + var range = this.bracketExpression(captures[0].length - 1); + if (!/^ *[-\w]+ *=/.test(range.src)) { // not attributes + this.consume(range.end + 1); + tok.args = range.src; + } + } catch (ex) { + //not a bracket expcetion, just unmatched open parens + } + } + + return tok; + } + }, + + /** + * Mixin. + */ + + mixin: function(){ + var captures; + if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { + this.consume(captures[0].length); + var tok = this.tok('mixin', captures[1]); + tok.args = captures[2]; + return tok; + } + }, + + /** + * Conditional. + */ + + conditional: function() { + var captures; + if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { + this.consume(captures[0].length); + var type = captures[1] + , js = captures[2]; + + switch (type) { + case 'if': js = 'if (' + js + ')'; break; + case 'unless': js = 'if (!(' + js + '))'; break; + case 'else if': js = 'else if (' + js + ')'; break; + case 'else': js = 'else'; break; + } + + return this.tok('code', js); + } + }, + + /** + * While. + */ + + "while": function() { + var captures; + if (captures = /^while +([^\n]+)/.exec(this.input)) { + this.consume(captures[0].length); + return this.tok('code', 'while (' + captures[1] + ')'); + } + }, + + /** + * Each. + */ + + each: function() { + var captures; + if (captures = /^(?:- *)?(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec(this.input)) { + this.consume(captures[0].length); + var tok = this.tok('each', captures[1]); + tok.key = captures[2] || '$index'; + tok.code = captures[3]; + return tok; + } + }, + + /** + * Code. + */ + + code: function() { + var captures; + if (captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input)) { + this.consume(captures[0].length); + var flags = captures[1]; + captures[1] = captures[2]; + var tok = this.tok('code', captures[1]); + tok.escape = flags.charAt(0) === '='; + tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '='; + return tok; + } + }, + + /** + * Attributes. + */ + + attrs: function() { + if ('(' == this.input.charAt(0)) { + var index = this.bracketExpression().end + , str = this.input.substr(1, index-1) + , tok = this.tok('attrs') + , len = str.length + , colons = this.colons + , states = ['key'] + , escapedAttr + , key = '' + , val = '' + , quote + , c + , p; + + function state(){ + return states[states.length - 1]; + } + + function interpolate(attr) { + return attr.replace(/(\\)?#\{(.+)/g, function(_, escape, expr){ + if (escape) return _; + try { + var range = parseJSExpression(expr); + if (expr[range.end] !== '}') return _.substr(0, 2) + interpolate(_.substr(2)); + return quote + " + (" + range.src + ") + " + quote + interpolate(expr.substr(range.end + 1)); + } catch (ex) { + return _.substr(0, 2) + interpolate(_.substr(2)); + } + }); + } + + this.consume(index + 1); + tok.attrs = {}; + tok.escaped = {}; + + function parse(c) { + var real = c; + // TODO: remove when people fix ":" + if (colons && ':' == c) c = '='; + switch (c) { + case ',': + case '\n': + switch (state()) { + case 'expr': + case 'array': + case 'string': + case 'object': + val += c; + break; + default: + states.push('key'); + val = val.trim(); + key = key.trim(); + if ('' == key) return; + key = key.replace(/^['"]|['"]$/g, '').replace('!', ''); + tok.escaped[key] = escapedAttr; + tok.attrs[key] = '' == val + ? true + : interpolate(val); + key = val = ''; + } + break; + case '=': + switch (state()) { + case 'key char': + key += real; + break; + case 'val': + case 'expr': + case 'array': + case 'string': + case 'object': + val += real; + break; + default: + escapedAttr = '!' != p; + states.push('val'); + } + break; + case '(': + if ('val' == state() + || 'expr' == state()) states.push('expr'); + val += c; + break; + case ')': + if ('expr' == state() + || 'val' == state()) states.pop(); + val += c; + break; + case '{': + if ('val' == state()) states.push('object'); + val += c; + break; + case '}': + if ('object' == state()) states.pop(); + val += c; + break; + case '[': + if ('val' == state()) states.push('array'); + val += c; + break; + case ']': + if ('array' == state()) states.pop(); + val += c; + break; + case '"': + case "'": + switch (state()) { + case 'key': + states.push('key char'); + break; + case 'key char': + states.pop(); + break; + case 'string': + if (c == quote) states.pop(); + val += c; + break; + default: + states.push('string'); + val += c; + quote = c; + } + break; + case '': + break; + default: + switch (state()) { + case 'key': + case 'key char': + key += c; + break; + default: + val += c; + } + } + p = c; + } + + for (var i = 0; i < len; ++i) { + parse(str.charAt(i)); + } + + parse(','); + + if ('/' == this.input.charAt(0)) { + this.consume(1); + tok.selfClosing = true; + } + + return tok; + } + }, + + /** + * Indent | Outdent | Newline. + */ + + indent: function() { + var captures, re; + + // established regexp + if (this.indentRe) { + captures = this.indentRe.exec(this.input); + // determine regexp + } else { + // tabs + re = /^\n(\t*) */; + captures = re.exec(this.input); + + // spaces + if (captures && !captures[1].length) { + re = /^\n( *)/; + captures = re.exec(this.input); + } + + // established + if (captures && captures[1].length) this.indentRe = re; + } + + if (captures) { + var tok + , indents = captures[1].length; + + ++this.lineno; + this.consume(indents + 1); + + if (' ' == this.input[0] || '\t' == this.input[0]) { + throw new Error('Invalid indentation, you can use tabs or spaces but not both'); + } + + // blank line + if ('\n' == this.input[0]) return this.tok('newline'); + + // outdent + if (this.indentStack.length && indents < this.indentStack[0]) { + while (this.indentStack.length && this.indentStack[0] > indents) { + this.stash.push(this.tok('outdent')); + this.indentStack.shift(); + } + tok = this.stash.pop(); + // indent + } else if (indents && indents != this.indentStack[0]) { + this.indentStack.unshift(indents); + tok = this.tok('indent', indents); + // newline + } else { + tok = this.tok('newline'); + } + + return tok; + } + }, + + /** + * Pipe-less text consumed only when + * pipeless is true; + */ + + pipelessText: function() { + if (this.pipeless) { + if ('\n' == this.input[0]) return; + var i = this.input.indexOf('\n'); + if (-1 == i) i = this.input.length; + var str = this.input.substr(0, i); + this.consume(str.length); + return this.tok('text', str); + } + }, + + /** + * ':' + */ + + colon: function() { + return this.scan(/^: */, ':'); + }, + + /** + * Return the next token object, or those + * previously stashed by lookahead. + * + * @return {Object} + * @api private + */ + + advance: function(){ + return this.stashed() + || this.next(); + }, + + /** + * Return the next token object. + * + * @return {Object} + * @api private + */ + + next: function() { + return this.deferred() + || this.blank() + || this.eos() + || this.pipelessText() + || this.yield() + || this.doctype() + || this.interpolation() + || this["case"]() + || this.when() + || this["default"]() + || this["extends"]() + || this.append() + || this.prepend() + || this.block() + || this.include() + || this.mixin() + || this.call() + || this.conditional() + || this.each() + || this["while"]() + || this.assignment() + || this.tag() + || this.filter() + || this.code() + || this.id() + || this.className() + || this.attrs() + || this.indent() + || this.comment() + || this.colon() + || this.text(); + } +}; diff --git a/node_modules/jade/lib/nodes/attrs.js b/node_modules/jade/lib/nodes/attrs.js new file mode 100644 index 000000000..5de9b59cc --- /dev/null +++ b/node_modules/jade/lib/nodes/attrs.js @@ -0,0 +1,77 @@ + +/*! + * Jade - nodes - Attrs + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'), + Block = require('./block'); + +/** + * Initialize a `Attrs` node. + * + * @api public + */ + +var Attrs = module.exports = function Attrs() { + this.attrs = []; +}; + +/** + * Inherit from `Node`. + */ + +Attrs.prototype.__proto__ = Node.prototype; + +/** + * Set attribute `name` to `val`, keep in mind these become + * part of a raw js object literal, so to quote a value you must + * '"quote me"', otherwise or example 'user.name' is literal JavaScript. + * + * @param {String} name + * @param {String} val + * @param {Boolean} escaped + * @return {Tag} for chaining + * @api public + */ + +Attrs.prototype.setAttribute = function(name, val, escaped){ + this.attrs.push({ name: name, val: val, escaped: escaped }); + return this; +}; + +/** + * Remove attribute `name` when present. + * + * @param {String} name + * @api public + */ + +Attrs.prototype.removeAttribute = function(name){ + for (var i = 0, len = this.attrs.length; i < len; ++i) { + if (this.attrs[i] && this.attrs[i].name == name) { + delete this.attrs[i]; + } + } +}; + +/** + * Get attribute value by `name`. + * + * @param {String} name + * @return {String} + * @api public + */ + +Attrs.prototype.getAttribute = function(name){ + for (var i = 0, len = this.attrs.length; i < len; ++i) { + if (this.attrs[i] && this.attrs[i].name == name) { + return this.attrs[i].val; + } + } +}; diff --git a/node_modules/jade/lib/nodes/block-comment.js b/node_modules/jade/lib/nodes/block-comment.js new file mode 100644 index 000000000..4f41e4a57 --- /dev/null +++ b/node_modules/jade/lib/nodes/block-comment.js @@ -0,0 +1,33 @@ + +/*! + * Jade - nodes - BlockComment + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `BlockComment` with the given `block`. + * + * @param {String} val + * @param {Block} block + * @param {Boolean} buffer + * @api public + */ + +var BlockComment = module.exports = function BlockComment(val, block, buffer) { + this.block = block; + this.val = val; + this.buffer = buffer; +}; + +/** + * Inherit from `Node`. + */ + +BlockComment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/block.js b/node_modules/jade/lib/nodes/block.js new file mode 100644 index 000000000..6bb18c943 --- /dev/null +++ b/node_modules/jade/lib/nodes/block.js @@ -0,0 +1,122 @@ + +/*! + * Jade - nodes - Block + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a new `Block` with an optional `node`. + * + * @param {Node} node + * @api public + */ + +var Block = module.exports = function Block(node){ + this.nodes = []; + if (node) this.push(node); +}; + +/** + * Inherit from `Node`. + */ + +Block.prototype.__proto__ = Node.prototype; + +/** + * Block flag. + */ + +Block.prototype.isBlock = true; + +/** + * Replace the nodes in `other` with the nodes + * in `this` block. + * + * @param {Block} other + * @api private + */ + +Block.prototype.replace = function(other){ + other.nodes = this.nodes; +}; + +/** + * Pust the given `node`. + * + * @param {Node} node + * @return {Number} + * @api public + */ + +Block.prototype.push = function(node){ + return this.nodes.push(node); +}; + +/** + * Check if this block is empty. + * + * @return {Boolean} + * @api public + */ + +Block.prototype.isEmpty = function(){ + return 0 == this.nodes.length; +}; + +/** + * Unshift the given `node`. + * + * @param {Node} node + * @return {Number} + * @api public + */ + +Block.prototype.unshift = function(node){ + return this.nodes.unshift(node); +}; + +/** + * Return the "last" block, or the first `yield` node. + * + * @return {Block} + * @api private + */ + +Block.prototype.includeBlock = function(){ + var ret = this + , node; + + for (var i = 0, len = this.nodes.length; i < len; ++i) { + node = this.nodes[i]; + if (node.yield) return node; + else if (node.textOnly) continue; + else if (node.includeBlock) ret = node.includeBlock(); + else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); + if (ret.yield) return ret; + } + + return ret; +}; + +/** + * Return a clone of this block. + * + * @return {Block} + * @api private + */ + +Block.prototype.clone = function(){ + var clone = new Block; + for (var i = 0, len = this.nodes.length; i < len; ++i) { + clone.push(this.nodes[i].clone()); + } + return clone; +}; + diff --git a/node_modules/jade/lib/nodes/case.js b/node_modules/jade/lib/nodes/case.js new file mode 100644 index 000000000..08ff03378 --- /dev/null +++ b/node_modules/jade/lib/nodes/case.js @@ -0,0 +1,43 @@ + +/*! + * Jade - nodes - Case + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a new `Case` with `expr`. + * + * @param {String} expr + * @api public + */ + +var Case = exports = module.exports = function Case(expr, block){ + this.expr = expr; + this.block = block; +}; + +/** + * Inherit from `Node`. + */ + +Case.prototype.__proto__ = Node.prototype; + +var When = exports.When = function When(expr, block){ + this.expr = expr; + this.block = block; + this.debug = false; +}; + +/** + * Inherit from `Node`. + */ + +When.prototype.__proto__ = Node.prototype; + diff --git a/node_modules/jade/lib/nodes/code.js b/node_modules/jade/lib/nodes/code.js new file mode 100644 index 000000000..babc67598 --- /dev/null +++ b/node_modules/jade/lib/nodes/code.js @@ -0,0 +1,35 @@ + +/*! + * Jade - nodes - Code + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `Code` node with the given code `val`. + * Code may also be optionally buffered and escaped. + * + * @param {String} val + * @param {Boolean} buffer + * @param {Boolean} escape + * @api public + */ + +var Code = module.exports = function Code(val, buffer, escape) { + this.val = val; + this.buffer = buffer; + this.escape = escape; + if (val.match(/^ *else/)) this.debug = false; +}; + +/** + * Inherit from `Node`. + */ + +Code.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/comment.js b/node_modules/jade/lib/nodes/comment.js new file mode 100644 index 000000000..2e1469e7e --- /dev/null +++ b/node_modules/jade/lib/nodes/comment.js @@ -0,0 +1,32 @@ + +/*! + * Jade - nodes - Comment + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `Comment` with the given `val`, optionally `buffer`, + * otherwise the comment may render in the output. + * + * @param {String} val + * @param {Boolean} buffer + * @api public + */ + +var Comment = module.exports = function Comment(val, buffer) { + this.val = val; + this.buffer = buffer; +}; + +/** + * Inherit from `Node`. + */ + +Comment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/doctype.js b/node_modules/jade/lib/nodes/doctype.js new file mode 100644 index 000000000..b8f33e56c --- /dev/null +++ b/node_modules/jade/lib/nodes/doctype.js @@ -0,0 +1,29 @@ + +/*! + * Jade - nodes - Doctype + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `Doctype` with the given `val`. + * + * @param {String} val + * @api public + */ + +var Doctype = module.exports = function Doctype(val) { + this.val = val; +}; + +/** + * Inherit from `Node`. + */ + +Doctype.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/each.js b/node_modules/jade/lib/nodes/each.js new file mode 100644 index 000000000..f54101f13 --- /dev/null +++ b/node_modules/jade/lib/nodes/each.js @@ -0,0 +1,35 @@ + +/*! + * Jade - nodes - Each + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize an `Each` node, representing iteration + * + * @param {String} obj + * @param {String} val + * @param {String} key + * @param {Block} block + * @api public + */ + +var Each = module.exports = function Each(obj, val, key, block) { + this.obj = obj; + this.val = val; + this.key = key; + this.block = block; +}; + +/** + * Inherit from `Node`. + */ + +Each.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/filter.js b/node_modules/jade/lib/nodes/filter.js new file mode 100644 index 000000000..0d7ff6e22 --- /dev/null +++ b/node_modules/jade/lib/nodes/filter.js @@ -0,0 +1,34 @@ + +/*! + * Jade - nodes - Filter + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node') + , Block = require('./block'); + +/** + * Initialize a `Filter` node with the given + * filter `name` and `block`. + * + * @param {String} name + * @param {Block|Node} block + * @api public + */ + +var Filter = module.exports = function Filter(name, block, attrs) { + this.name = name; + this.block = block; + this.attrs = attrs; +}; + +/** + * Inherit from `Node`. + */ + +Filter.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/index.js b/node_modules/jade/lib/nodes/index.js new file mode 100644 index 000000000..386ad2f9d --- /dev/null +++ b/node_modules/jade/lib/nodes/index.js @@ -0,0 +1,20 @@ + +/*! + * Jade - nodes + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +exports.Node = require('./node'); +exports.Tag = require('./tag'); +exports.Code = require('./code'); +exports.Each = require('./each'); +exports.Case = require('./case'); +exports.Text = require('./text'); +exports.Block = require('./block'); +exports.Mixin = require('./mixin'); +exports.Filter = require('./filter'); +exports.Comment = require('./comment'); +exports.Literal = require('./literal'); +exports.BlockComment = require('./block-comment'); +exports.Doctype = require('./doctype'); diff --git a/node_modules/jade/lib/nodes/literal.js b/node_modules/jade/lib/nodes/literal.js new file mode 100644 index 000000000..a8a02a2c9 --- /dev/null +++ b/node_modules/jade/lib/nodes/literal.js @@ -0,0 +1,29 @@ + +/*! + * Jade - nodes - Literal + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `Literal` node with the given `str. + * + * @param {String} str + * @api public + */ + +var Literal = module.exports = function Literal(str) { + this.str = str; +}; + +/** + * Inherit from `Node`. + */ + +Literal.prototype.__proto__ = Node.prototype; diff --git a/node_modules/jade/lib/nodes/mixin.js b/node_modules/jade/lib/nodes/mixin.js new file mode 100644 index 000000000..8407bc792 --- /dev/null +++ b/node_modules/jade/lib/nodes/mixin.js @@ -0,0 +1,36 @@ + +/*! + * Jade - nodes - Mixin + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Attrs = require('./attrs'); + +/** + * Initialize a new `Mixin` with `name` and `block`. + * + * @param {String} name + * @param {String} args + * @param {Block} block + * @api public + */ + +var Mixin = module.exports = function Mixin(name, args, block, call){ + this.name = name; + this.args = args; + this.block = block; + this.attrs = []; + this.call = call; +}; + +/** + * Inherit from `Attrs`. + */ + +Mixin.prototype.__proto__ = Attrs.prototype; + diff --git a/node_modules/jade/lib/nodes/node.js b/node_modules/jade/lib/nodes/node.js new file mode 100644 index 000000000..e98f042c5 --- /dev/null +++ b/node_modules/jade/lib/nodes/node.js @@ -0,0 +1,25 @@ + +/*! + * Jade - nodes - Node + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Initialize a `Node`. + * + * @api public + */ + +var Node = module.exports = function Node(){}; + +/** + * Clone this node (return itself) + * + * @return {Node} + * @api private + */ + +Node.prototype.clone = function(){ + return this; +}; diff --git a/node_modules/jade/lib/nodes/tag.js b/node_modules/jade/lib/nodes/tag.js new file mode 100644 index 000000000..4b6728adc --- /dev/null +++ b/node_modules/jade/lib/nodes/tag.js @@ -0,0 +1,95 @@ + +/*! + * Jade - nodes - Tag + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Attrs = require('./attrs'), + Block = require('./block'), + inlineTags = require('../inline-tags'); + +/** + * Initialize a `Tag` node with the given tag `name` and optional `block`. + * + * @param {String} name + * @param {Block} block + * @api public + */ + +var Tag = module.exports = function Tag(name, block) { + this.name = name; + this.attrs = []; + this.block = block || new Block; +}; + +/** + * Inherit from `Attrs`. + */ + +Tag.prototype.__proto__ = Attrs.prototype; + +/** + * Clone this tag. + * + * @return {Tag} + * @api private + */ + +Tag.prototype.clone = function(){ + var clone = new Tag(this.name, this.block.clone()); + clone.line = this.line; + clone.attrs = this.attrs; + clone.textOnly = this.textOnly; + return clone; +}; + +/** + * Check if this tag is an inline tag. + * + * @return {Boolean} + * @api private + */ + +Tag.prototype.isInline = function(){ + return ~inlineTags.indexOf(this.name); +}; + +/** + * Check if this tag's contents can be inlined. Used for pretty printing. + * + * @return {Boolean} + * @api private + */ + +Tag.prototype.canInline = function(){ + var nodes = this.block.nodes; + + function isInline(node){ + // Recurse if the node is a block + if (node.isBlock) return node.nodes.every(isInline); + return node.isText || (node.isInline && node.isInline()); + } + + // Empty tag + if (!nodes.length) return true; + + // Text-only or inline-only tag + if (1 == nodes.length) return isInline(nodes[0]); + + // Multi-line inline-only tag + if (this.block.nodes.every(isInline)) { + for (var i = 1, len = nodes.length; i < len; ++i) { + if (nodes[i-1].isText && nodes[i].isText) + return false; + } + return true; + } + + // Mixed tag + return false; +}; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/text.js b/node_modules/jade/lib/nodes/text.js new file mode 100644 index 000000000..3b5dd5573 --- /dev/null +++ b/node_modules/jade/lib/nodes/text.js @@ -0,0 +1,36 @@ + +/*! + * Jade - nodes - Text + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Node = require('./node'); + +/** + * Initialize a `Text` node with optional `line`. + * + * @param {String} line + * @api public + */ + +var Text = module.exports = function Text(line) { + this.val = ''; + if ('string' == typeof line) this.val = line; +}; + +/** + * Inherit from `Node`. + */ + +Text.prototype.__proto__ = Node.prototype; + +/** + * Flag as text. + */ + +Text.prototype.isText = true; \ No newline at end of file diff --git a/node_modules/jade/lib/parser.js b/node_modules/jade/lib/parser.js new file mode 100644 index 000000000..8de145501 --- /dev/null +++ b/node_modules/jade/lib/parser.js @@ -0,0 +1,719 @@ +/*! + * Jade - Parser + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var Lexer = require('./lexer') + , nodes = require('./nodes') + , utils = require('./utils') + , filters = require('./filters') + , path = require('path') + , extname = path.extname; + +/** + * Initialize `Parser` with the given input `str` and `filename`. + * + * @param {String} str + * @param {String} filename + * @param {Object} options + * @api public + */ + +var Parser = exports = module.exports = function Parser(str, filename, options){ + this.input = str; + this.lexer = new Lexer(str, options); + this.filename = filename; + this.blocks = {}; + this.mixins = {}; + this.options = options; + this.contexts = [this]; +}; + +/** + * Tags that may not contain tags. + */ + +var textOnly = exports.textOnly = ['script', 'style']; + +/** + * Parser prototype. + */ + +Parser.prototype = { + + /** + * Push `parser` onto the context stack, + * or pop and return a `Parser`. + */ + + context: function(parser){ + if (parser) { + this.contexts.push(parser); + } else { + return this.contexts.pop(); + } + }, + + /** + * Return the next token object. + * + * @return {Object} + * @api private + */ + + advance: function(){ + return this.lexer.advance(); + }, + + /** + * Skip `n` tokens. + * + * @param {Number} n + * @api private + */ + + skip: function(n){ + while (n--) this.advance(); + }, + + /** + * Single token lookahead. + * + * @return {Object} + * @api private + */ + + peek: function() { + return this.lookahead(1); + }, + + /** + * Return lexer lineno. + * + * @return {Number} + * @api private + */ + + line: function() { + return this.lexer.lineno; + }, + + /** + * `n` token lookahead. + * + * @param {Number} n + * @return {Object} + * @api private + */ + + lookahead: function(n){ + return this.lexer.lookahead(n); + }, + + /** + * Parse input returning a string of js for evaluation. + * + * @return {String} + * @api public + */ + + parse: function(){ + var block = new nodes.Block, parser; + block.line = this.line(); + + while ('eos' != this.peek().type) { + if ('newline' == this.peek().type) { + this.advance(); + } else { + block.push(this.parseExpr()); + } + } + + if (parser = this.extending) { + this.context(parser); + var ast = parser.parse(); + this.context(); + + // hoist mixins + for (var name in this.mixins) + ast.unshift(this.mixins[name]); + return ast; + } + + return block; + }, + + /** + * Expect the given type, or throw an exception. + * + * @param {String} type + * @api private + */ + + expect: function(type){ + if (this.peek().type === type) { + return this.advance(); + } else { + throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); + } + }, + + /** + * Accept the given `type`. + * + * @param {String} type + * @api private + */ + + accept: function(type){ + if (this.peek().type === type) { + return this.advance(); + } + }, + + /** + * tag + * | doctype + * | mixin + * | include + * | filter + * | comment + * | text + * | each + * | code + * | yield + * | id + * | class + * | interpolation + */ + + parseExpr: function(){ + switch (this.peek().type) { + case 'tag': + return this.parseTag(); + case 'mixin': + return this.parseMixin(); + case 'block': + return this.parseBlock(); + case 'case': + return this.parseCase(); + case 'when': + return this.parseWhen(); + case 'default': + return this.parseDefault(); + case 'extends': + return this.parseExtends(); + case 'include': + return this.parseInclude(); + case 'doctype': + return this.parseDoctype(); + case 'filter': + return this.parseFilter(); + case 'comment': + return this.parseComment(); + case 'text': + return this.parseText(); + case 'each': + return this.parseEach(); + case 'code': + return this.parseCode(); + case 'call': + return this.parseCall(); + case 'interpolation': + return this.parseInterpolation(); + case 'yield': + this.advance(); + var block = new nodes.Block; + block.yield = true; + return block; + case 'id': + case 'class': + var tok = this.advance(); + this.lexer.defer(this.lexer.tok('tag', 'div')); + this.lexer.defer(tok); + return this.parseExpr(); + default: + throw new Error('unexpected token "' + this.peek().type + '"'); + } + }, + + /** + * Text + */ + + parseText: function(){ + var tok = this.expect('text'); + var node = new nodes.Text(tok.val); + node.line = this.line(); + return node; + }, + + /** + * ':' expr + * | block + */ + + parseBlockExpansion: function(){ + if (':' == this.peek().type) { + this.advance(); + return new nodes.Block(this.parseExpr()); + } else { + return this.block(); + } + }, + + /** + * case + */ + + parseCase: function(){ + var val = this.expect('case').val; + var node = new nodes.Case(val); + node.line = this.line(); + node.block = this.block(); + return node; + }, + + /** + * when + */ + + parseWhen: function(){ + var val = this.expect('when').val + return new nodes.Case.When(val, this.parseBlockExpansion()); + }, + + /** + * default + */ + + parseDefault: function(){ + this.expect('default'); + return new nodes.Case.When('default', this.parseBlockExpansion()); + }, + + /** + * code + */ + + parseCode: function(){ + var tok = this.expect('code'); + var node = new nodes.Code(tok.val, tok.buffer, tok.escape); + var block; + var i = 1; + node.line = this.line(); + while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; + block = 'indent' == this.lookahead(i).type; + if (block) { + this.skip(i-1); + node.block = this.block(); + } + return node; + }, + + /** + * comment + */ + + parseComment: function(){ + var tok = this.expect('comment'); + var node; + + if ('indent' == this.peek().type) { + node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); + } else { + node = new nodes.Comment(tok.val, tok.buffer); + } + + node.line = this.line(); + return node; + }, + + /** + * doctype + */ + + parseDoctype: function(){ + var tok = this.expect('doctype'); + var node = new nodes.Doctype(tok.val); + node.line = this.line(); + return node; + }, + + /** + * filter attrs? text-block + */ + + parseFilter: function(){ + var tok = this.expect('filter'); + var attrs = this.accept('attrs'); + var block; + + this.lexer.pipeless = true; + block = this.parseTextBlock(); + this.lexer.pipeless = false; + + var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); + node.line = this.line(); + return node; + }, + + /** + * each block + */ + + parseEach: function(){ + var tok = this.expect('each'); + var node = new nodes.Each(tok.code, tok.val, tok.key); + node.line = this.line(); + node.block = this.block(); + if (this.peek().type == 'code' && this.peek().val == 'else') { + this.advance(); + node.alternative = this.block(); + } + return node; + }, + + /** + * Resolves a path relative to the template for use in + * includes and extends + * + * @param {String} path + * @param {String} purpose Used in error messages. + * @return {String} + * @api private + */ + + resolvePath: function (path, purpose) { + var p = require('path'); + var dirname = p.dirname; + var basename = p.basename; + var join = p.join; + + if (path[0] !== '/' && !this.filename) + throw new Error('the "filename" option is required to use "' + purpose + '" with "relative" paths'); + + if (path[0] === '/' && !this.options.basedir) + throw new Error('the "basedir" option is required to use "' + purpose + '" with "absolute" paths'); + + path = join(path[0] === '/' ? this.options.basedir : dirname(this.filename), path); + + if (basename(path).indexOf('.') === -1) path += '.jade'; + + return path; + }, + + /** + * 'extends' name + */ + + parseExtends: function(){ + var fs = require('fs'); + + var path = this.resolvePath(this.expect('extends').val.trim(), 'extends'); + if ('.jade' != path.substr(-5)) path += '.jade'; + + var str = fs.readFileSync(path, 'utf8'); + var parser = new Parser(str, path, this.options); + + parser.blocks = this.blocks; + parser.contexts = this.contexts; + this.extending = parser; + + // TODO: null node + return new nodes.Literal(''); + }, + + /** + * 'block' name block + */ + + parseBlock: function(){ + var block = this.expect('block'); + var mode = block.mode; + var name = block.val.trim(); + + block = 'indent' == this.peek().type + ? this.block() + : new nodes.Block(new nodes.Literal('')); + + var prev = this.blocks[name] || {prepended: [], appended: []} + if (prev.mode === 'replace') return this.blocks[name] = prev; + + var allNodes = prev.prepended.concat(block.nodes).concat(prev.appended); + + switch (mode) { + case 'append': + prev.appended = prev.parser === this ? + prev.appended.concat(block.nodes) : + block.nodes.concat(prev.appended); + break; + case 'prepend': + prev.prepended = prev.parser === this ? + block.nodes.concat(prev.prepended) : + prev.prepended.concat(block.nodes); + break; + } + block.nodes = allNodes; + block.appended = prev.appended; + block.prepended = prev.prepended; + block.mode = mode; + block.parser = this; + + return this.blocks[name] = block; + }, + + /** + * include block? + */ + + parseInclude: function(){ + var fs = require('fs'); + + var path = this.resolvePath(this.expect('include').val.trim(), 'include'); + + // non-jade + if ('.jade' != path.substr(-5)) { + var str = fs.readFileSync(path, 'utf8').replace(/\r/g, ''); + var ext = extname(path).slice(1); + if (filters.exists(ext)) str = filters(ext, str, { filename: path }); + return new nodes.Literal(str); + } + + var str = fs.readFileSync(path, 'utf8'); + var parser = new Parser(str, path, this.options); + parser.blocks = utils.merge({}, this.blocks); + + parser.mixins = this.mixins; + + this.context(parser); + var ast = parser.parse(); + this.context(); + ast.filename = path; + + if ('indent' == this.peek().type) { + ast.includeBlock().push(this.block()); + } + + return ast; + }, + + /** + * call ident block + */ + + parseCall: function(){ + var tok = this.expect('call'); + var name = tok.val; + var args = tok.args; + var mixin = new nodes.Mixin(name, args, new nodes.Block, true); + + this.tag(mixin); + if (mixin.code) { + mixin.block.push(mixin.code); + mixin.code = null; + } + if (mixin.block.isEmpty()) mixin.block = null; + return mixin; + }, + + /** + * mixin block + */ + + parseMixin: function(){ + var tok = this.expect('mixin'); + var name = tok.val; + var args = tok.args; + var mixin; + + // definition + if ('indent' == this.peek().type) { + mixin = new nodes.Mixin(name, args, this.block(), false); + this.mixins[name] = mixin; + return mixin; + // call + } else { + return new nodes.Mixin(name, args, null, true); + } + }, + + /** + * indent (text | newline)* outdent + */ + + parseTextBlock: function(){ + var block = new nodes.Block; + block.line = this.line(); + var spaces = this.expect('indent').val; + if (null == this._spaces) this._spaces = spaces; + var indent = Array(spaces - this._spaces + 1).join(' '); + while ('outdent' != this.peek().type) { + switch (this.peek().type) { + case 'newline': + this.advance(); + break; + case 'indent': + this.parseTextBlock().nodes.forEach(function(node){ + block.push(node); + }); + break; + default: + var text = new nodes.Text(indent + this.advance().val); + text.line = this.line(); + block.push(text); + } + } + + if (spaces == this._spaces) this._spaces = null; + this.expect('outdent'); + return block; + }, + + /** + * indent expr* outdent + */ + + block: function(){ + var block = new nodes.Block; + block.line = this.line(); + this.expect('indent'); + while ('outdent' != this.peek().type) { + if ('newline' == this.peek().type) { + this.advance(); + } else { + block.push(this.parseExpr()); + } + } + this.expect('outdent'); + return block; + }, + + /** + * interpolation (attrs | class | id)* (text | code | ':')? newline* block? + */ + + parseInterpolation: function(){ + var tok = this.advance(); + var tag = new nodes.Tag(tok.val); + tag.buffer = true; + return this.tag(tag); + }, + + /** + * tag (attrs | class | id)* (text | code | ':')? newline* block? + */ + + parseTag: function(){ + // ast-filter look-ahead + var i = 2; + if ('attrs' == this.lookahead(i).type) ++i; + + var tok = this.advance(); + var tag = new nodes.Tag(tok.val); + + tag.selfClosing = tok.selfClosing; + + return this.tag(tag); + }, + + /** + * Parse tag. + */ + + tag: function(tag){ + var dot; + + tag.line = this.line(); + + // (attrs | class | id)* + out: + while (true) { + switch (this.peek().type) { + case 'id': + case 'class': + var tok = this.advance(); + tag.setAttribute(tok.type, "'" + tok.val + "'"); + continue; + case 'attrs': + var tok = this.advance() + , obj = tok.attrs + , escaped = tok.escaped + , names = Object.keys(obj); + + if (tok.selfClosing) tag.selfClosing = true; + + for (var i = 0, len = names.length; i < len; ++i) { + var name = names[i] + , val = obj[name]; + tag.setAttribute(name, val, escaped[name]); + } + continue; + default: + break out; + } + } + + // check immediate '.' + if ('.' == this.peek().val) { + dot = tag.textOnly = true; + this.advance(); + } + + // (text | code | ':')? + switch (this.peek().type) { + case 'text': + tag.block.push(this.parseText()); + break; + case 'code': + tag.code = this.parseCode(); + break; + case ':': + this.advance(); + tag.block = new nodes.Block; + tag.block.push(this.parseExpr()); + break; + } + + // newline* + while ('newline' == this.peek().type) this.advance(); + + tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); + + // script special-case + if ('script' == tag.name) { + var type = tag.getAttribute('type'); + if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { + tag.textOnly = false; + } + } + + // block? + if ('indent' == this.peek().type) { + if (tag.textOnly) { + if (!dot) { + console.warn('Implicit textOnly for `script` and `style` is deprecated. Use `script.` or `style.` instead.'); + } + this.lexer.pipeless = true; + tag.block = this.parseTextBlock(); + this.lexer.pipeless = false; + } else { + var block = this.block(); + if (tag.block) { + for (var i = 0, len = block.nodes.length; i < len; ++i) { + tag.block.push(block.nodes[i]); + } + } else { + tag.block = block; + } + } + } + + return tag; + } +}; diff --git a/node_modules/jade/lib/runtime.js b/node_modules/jade/lib/runtime.js new file mode 100644 index 000000000..7bc81ef86 --- /dev/null +++ b/node_modules/jade/lib/runtime.js @@ -0,0 +1,187 @@ + +/*! + * Jade - runtime + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Lame Array.isArray() polyfill for now. + */ + +if (!Array.isArray) { + Array.isArray = function(arr){ + return '[object Array]' == Object.prototype.toString.call(arr); + }; +} + +/** + * Lame Object.keys() polyfill for now. + */ + +if (!Object.keys) { + Object.keys = function(obj){ + var arr = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + arr.push(key); + } + } + return arr; + } +} + +/** + * Merge two attribute objects giving precedence + * to values in object `b`. Classes are special-cased + * allowing for arrays and merging/joining appropriately + * resulting in a string. + * + * @param {Object} a + * @param {Object} b + * @return {Object} a + * @api private + */ + +exports.merge = function merge(a, b) { + var ac = a['class']; + var bc = b['class']; + + if (ac || bc) { + ac = ac || []; + bc = bc || []; + if (!Array.isArray(ac)) ac = [ac]; + if (!Array.isArray(bc)) bc = [bc]; + a['class'] = ac.concat(bc).filter(nulls); + } + + for (var key in b) { + if (key != 'class') { + a[key] = b[key]; + } + } + + return a; +}; + +/** + * Filter null `val`s. + * + * @param {*} val + * @return {Boolean} + * @api private + */ + +function nulls(val) { + return val != null && val !== ''; +} + +/** + * join array as classes. + * + * @param {*} val + * @return {String} + * @api private + */ + +function joinClasses(val) { + return Array.isArray(val) ? val.map(joinClasses).filter(nulls).join(' ') : val; +} + +/** + * Render the given attributes object. + * + * @param {Object} obj + * @param {Object} escaped + * @return {String} + * @api private + */ + +exports.attrs = function attrs(obj, escaped){ + var buf = [] + , terse = obj.terse; + + delete obj.terse; + var keys = Object.keys(obj) + , len = keys.length; + + if (len) { + buf.push(''); + for (var i = 0; i < len; ++i) { + var key = keys[i] + , val = obj[key]; + + if ('boolean' == typeof val || null == val) { + if (val) { + terse + ? buf.push(key) + : buf.push(key + '="' + key + '"'); + } + } else if (0 == key.indexOf('data') && 'string' != typeof val) { + buf.push(key + "='" + JSON.stringify(val) + "'"); + } else if ('class' == key) { + if (val = exports.escape(joinClasses(val))) { + buf.push(key + '="' + val + '"'); + } + } else if (escaped && escaped[key]) { + buf.push(key + '="' + exports.escape(val) + '"'); + } else { + buf.push(key + '="' + val + '"'); + } + } + } + + return buf.join(' '); +}; + +/** + * Escape the given string of `html`. + * + * @param {String} html + * @return {String} + * @api private + */ + +exports.escape = function escape(html){ + return String(html) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +}; + +/** + * Re-throw the given `err` in context to the + * the jade in `filename` at the given `lineno`. + * + * @param {Error} err + * @param {String} filename + * @param {String} lineno + * @api private + */ + +exports.rethrow = function rethrow(err, filename, lineno){ + if (!filename) throw err; + if (typeof window != 'undefined') throw err; + + var context = 3 + , str = require('fs').readFileSync(filename, 'utf8') + , lines = str.split('\n') + , start = Math.max(lineno - context, 0) + , end = Math.min(lines.length, lineno + context); + + // Error context + var context = lines.slice(start, end).map(function(line, i){ + var curr = i + start + 1; + return (curr == lineno ? ' > ' : ' ') + + curr + + '| ' + + line; + }).join('\n'); + + // Alter exception message + err.path = filename; + err.message = (filename || 'Jade') + ':' + lineno + + '\n' + context + '\n\n' + err.message; + throw err; +}; diff --git a/node_modules/jade/lib/self-closing.js b/node_modules/jade/lib/self-closing.js new file mode 100644 index 000000000..054877121 --- /dev/null +++ b/node_modules/jade/lib/self-closing.js @@ -0,0 +1,19 @@ + +/*! + * Jade - self closing tags + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +module.exports = [ + 'meta' + , 'img' + , 'link' + , 'input' + , 'source' + , 'area' + , 'base' + , 'col' + , 'br' + , 'hr' +]; \ No newline at end of file diff --git a/node_modules/jade/lib/utils.js b/node_modules/jade/lib/utils.js new file mode 100644 index 000000000..9d308ccc7 --- /dev/null +++ b/node_modules/jade/lib/utils.js @@ -0,0 +1,21 @@ + +/*! + * Jade - utils + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Merge `b` into `a`. + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports.merge = function(a, b) { + for (var key in b) a[key] = b[key]; + return a; +}; + diff --git a/node_modules/jade/node_modules/character-parser/.npmignore b/node_modules/jade/node_modules/character-parser/.npmignore new file mode 100644 index 000000000..699b5d4f1 --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log + +node_modules diff --git a/node_modules/jade/node_modules/character-parser/.travis.yml b/node_modules/jade/node_modules/character-parser/.travis.yml new file mode 100644 index 000000000..2ca91f289 --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.10" + - "0.8" \ No newline at end of file diff --git a/node_modules/jade/node_modules/character-parser/README.md b/node_modules/jade/node_modules/character-parser/README.md new file mode 100644 index 000000000..4485cbf01 --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/README.md @@ -0,0 +1,123 @@ +# character-parser + +Parse JavaScript one character at a time to look for snippets in Templates. This is not a validator, it's just designed to allow you to have sections of JavaScript delimited by brackets robustly. + +[![Build Status](https://travis-ci.org/ForbesLindesay/character-parser.png?branch=master)](https://travis-ci.org/ForbesLindesay/character-parser) + +## Installation + + npm install character-parser + +## Usage + +Work out how much depth changes: + +```js +var state = parse('foo(arg1, arg2, {\n foo: [a, b\n'); +assert(state.roundDepth === 1); +assert(state.curlyDepth === 1); +assert(state.squareDepth === 1); +parse(' c, d]\n })', state); +assert(state.squareDepth === 0); +assert(state.curlyDepth === 0); +assert(state.roundDepth === 0); +``` + +### Bracketed Expressions + +Find all the contents of a bracketed expression: + +```js +var section = parser.parseMax('foo="(", bar="}") bing bong'); +assert(section.start === 0); +assert(section.end === 16);//exclusive end of string +assert(section.src = 'foo="(", bar="}"'); + + +var section = parser.parseMax('{foo="(", bar="}"} bing bong', {start: 1}); +assert(section.start === 1); +assert(section.end === 17);//exclusive end of string +assert(section.src = 'foo="(", bar="}"'); +``` + +The bracketed expression parsing simply parses up to but excluding the first unmatched closed bracket (`)`, `}`, `]`). It is clever enough to ignore brackets in comments or strings. + + +### Custom Delimited Expressions + +Find code up to a custom delimiter: + +```js +var section = parser.parseUntil('foo.bar("%>").baz%> bing bong', '%>'); +assert(section.start === 0); +assert(section.end === 17);//exclusive end of string +assert(section.src = 'foo.bar("%>").baz'); + +var section = parser.parseUntil('<%foo.bar("%>").baz%> bing bong', '%>', {start: 2}); +assert(section.start === 2); +assert(section.end === 19);//exclusive end of string +assert(section.src = 'foo.bar("%>").baz'); +``` + +Delimiters are ignored if they are inside strings or comments. + +## API + +### parse(str, state = defaultState(), options = {start: 0, end: src.length}) + +Parse a string starting at the index start, and return the state after parsing that string. + +If you want to parse one string in multiple sections you should keep passing the resulting state to the next parse operation. + +The resulting object has the structure: + +```js +{ + lineComment: false, //true if inside a line comment + blockComment: false, //true if inside a block comment + + singleQuote: false, //true if inside a single quoted string + doubleQuote: false, //true if inside a double quoted string + escaped: false, //true if in a string and the last character was an escape character + + roundDepth: 0, //number of un-closed open `(` brackets + curlyDepth: 0, //number of un-closed open `{` brackets + squareDepth: 0 //number of un-closed open `[` brackets +} +``` + +### parseMax(src, options = {start: 0}) + +Parses the source until the first unmatched close bracket (any of `)`, `}`, `]`). It returns an object with the structure: + +```js +{ + start: 0,//index of first character of string + end: 13,//index of first character after the end of string + src: 'source string' +} +``` + +### parseUntil(src, delimiter, options = {start: 0, includeLineComment: false}) + +Parses the source until the first occurence of `delimiter` which is not in a string or a comment. If `includeLineComment` is `true`, it will still count if the delimiter occurs in a line comment, but not in a block comment. It returns an object with the structure: + +```js +{ + start: 0,//index of first character of string + end: 13,//index of first character after the end of string + src: 'source string' +} +``` + +### parseChar(character, state = defaultState()) + +Parses the single character and returns the state. See `parse` for the structure of the returned state object. N.B. character must be a single character not a multi character string. + +### defaultState() + +Get a default starting state. See `parse` for the structure of the returned state object. + +## License + +MIT \ No newline at end of file diff --git a/node_modules/jade/node_modules/character-parser/index.js b/node_modules/jade/node_modules/character-parser/index.js new file mode 100644 index 000000000..c80022bf7 --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/index.js @@ -0,0 +1,205 @@ +exports = (module.exports = parse); +exports.parse = parse; +function parse(src, state, options) { + options = options || {}; + state = state || exports.defaultState(); + var start = options.start || 0; + var end = options.end || src.length; + var index = start; + while (index < end) { + if (state.roundDepth < 0 || state.curlyDepth < 0 || state.squareDepth < 0) { + throw new SyntaxError('Mismatched Bracket: ' + src[index - 1]); + } + exports.parseChar(src[index++], state); + } + return state; +} + +exports.parseMax = parseMax; +function parseMax(src, options) { + options = options || {}; + var start = options.start || 0; + var index = start; + var state = exports.defaultState(); + while (state.roundDepth >= 0 && state.curlyDepth >= 0 && state.squareDepth >= 0) { + if (index >= src.length) { + throw new Error('The end of the string was reached with no closing bracket found.'); + } + exports.parseChar(src[index++], state); + } + var end = index - 1; + return { + start: start, + end: end, + src: src.substring(start, end) + }; +} + +exports.parseUntil = parseUntil; +function parseUntil(src, delimiter, options) { + options = options || {}; + var includeLineComment = options.includeLineComment || false; + var start = options.start || 0; + var index = start; + var state = exports.defaultState(); + while (state.singleQuote || state.doubleQuote || state.regexp || state.blockComment || + (!includeLineComment && state.lineComment) || !startsWith(src, delimiter, index)) { + exports.parseChar(src[index++], state); + } + var end = index; + return { + start: start, + end: end, + src: src.substring(start, end) + }; +} + + +exports.parseChar = parseChar; +function parseChar(character, state) { + if (character.length !== 1) throw new Error('Character must be a string of length 1'); + state = state || defaultState(); + var wasComment = state.blockComment || state.lineComment; + var lastChar = state.history ? state.history[0] : ''; + if (state.lineComment) { + if (character === '\n') { + state.lineComment = false; + } + } else if (state.blockComment) { + if (state.lastChar === '*' && character === '/') { + state.blockComment = false; + } + } else if (state.singleQuote) { + if (character === '\'' && !state.escaped) { + state.singleQuote = false; + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + } else if (state.doubleQuote) { + if (character === '"' && !state.escaped) { + state.doubleQuote = false; + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + } else if (state.regexp) { + if (character === '/' && !state.escaped) { + state.regexp = false; + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + } else if (lastChar === '/' && character === '/') { + history = history.substr(1); + state.lineComment = true; + } else if (lastChar === '/' && character === '*') { + history = history.substr(1); + state.blockComment = true; + } else if (character === '/') { + //could be start of regexp or divide sign + var history = state.history.replace(/^\s*/, ''); + if (history[0] === ')') { + //unless its an `if`, `while`, `for` or `with` it's a divide + //this is probably best left though + } else if (history[0] === '}') { + //unless it's a function expression, it's a regexp + //this is probably best left though + } else if (isPunctuator(history[0])) { + state.regexp = true; + } else if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0])) { + state.regexp = true; + } else { + // assume it's divide + } + } else if (character === '\'') { + state.singleQuote = true; + } else if (character === '"') { + state.doubleQuote = true; + } else if (character === '(') { + state.roundDepth++; + } else if (character === ')') { + state.roundDepth--; + } else if (character === '{') { + state.curlyDepth++; + } else if (character === '}') { + state.curlyDepth--; + } else if (character === '[') { + state.squareDepth++; + } else if (character === ']') { + state.squareDepth--; + } + if (!state.blockComment && !state.lineComment && !wasComment) state.history = character + state.history; + return state; +} + +exports.defaultState = defaultState; +function defaultState() { + return { + lineComment: false, + blockComment: false, + + singleQuote: false, + doubleQuote: false, + regexp: false, + escaped: false, + + roundDepth: 0, + curlyDepth: 0, + squareDepth: 0, + + history: '' + }; +} + +function startsWith(str, start, i) { + return str.substr(i || 0, start.length) === start; +} + +function isPunctuator(c) { + var code = c.charCodeAt(0) + + switch (code) { + case 46: // . dot + case 40: // ( open bracket + case 41: // ) close bracket + case 59: // ; semicolon + case 44: // , comma + case 123: // { open curly brace + case 125: // } close curly brace + case 91: // [ + case 93: // ] + case 58: // : + case 63: // ? + case 126: // ~ + case 37: // % + case 38: // & + case 42: // *: + case 43: // + + case 45: // - + case 47: // / + case 60: // < + case 62: // > + case 94: // ^ + case 124: // | + case 33: // ! + case 61: // = + return true; + default: + return false; + } +} +function isKeyword(id) { + return (id === 'if') || (id === 'in') || (id === 'do') || (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let') || (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum') || (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super') || + (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || + (id === 'import') || (id === 'default') || (id === 'finally') || (id === 'extends') || (id === 'function') || + (id === 'continue') || (id === 'debugger') || (id === 'package') || (id === 'private') || (id === 'interface') || + (id === 'instanceof') || (id === 'implements') || (id === 'protected') || (id === 'public') || (id === 'static') || + (id === 'yield') || (id === 'let'); +} diff --git a/node_modules/jade/node_modules/character-parser/package.json b/node_modules/jade/node_modules/character-parser/package.json new file mode 100644 index 000000000..fb0954e8b --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/package.json @@ -0,0 +1,51 @@ +{ + "name": "character-parser", + "version": "1.0.2", + "description": "Parse JavaScript one character at a time to look for snippets in Templates. This is not a validator, it's just designed to allow you to have sections of JavaScript delimited by brackets robustly.", + "main": "index.js", + "scripts": { + "test": "mocha -R spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/ForbesLindesay/character-parser.git" + }, + "keywords": [ + "parser", + "JavaScript", + "bracket", + "nesting", + "comment", + "string", + "escape", + "escaping" + ], + "author": { + "name": "ForbesLindesay" + }, + "license": "MIT", + "devDependencies": { + "better-assert": "~1.0.0", + "mocha": "~1.9.0" + }, + "_id": "character-parser@1.0.2", + "dist": { + "shasum": "55384d6afcf8c6b9dd483e8347646a790e4545e7", + "tarball": "http://registry.npmjs.org/character-parser/-/character-parser-1.0.2.tgz" + }, + "_from": "character-parser@1.0.2", + "_npmVersion": "1.2.10", + "_npmUser": { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + }, + "maintainers": [ + { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + } + ], + "directories": {}, + "_shasum": "55384d6afcf8c6b9dd483e8347646a790e4545e7", + "_resolved": "https://registry.npmjs.org/character-parser/-/character-parser-1.0.2.tgz" +} diff --git a/node_modules/jade/node_modules/character-parser/test/index.js b/node_modules/jade/node_modules/character-parser/test/index.js new file mode 100644 index 000000000..6ea0da729 --- /dev/null +++ b/node_modules/jade/node_modules/character-parser/test/index.js @@ -0,0 +1,50 @@ +var assert = require('better-assert'); +var parser = require('../'); +var parse = parser; + +it('works out how much depth changes', function () { + var state = parse('foo(arg1, arg2, {\n foo: [a, b\n'); + assert(state.roundDepth === 1); + assert(state.curlyDepth === 1); + assert(state.squareDepth === 1); + + parse(' c, d]\n })', state); + assert(state.squareDepth === 0); + assert(state.curlyDepth === 0); + assert(state.roundDepth === 0); +}); + +it('finds contents of bracketed expressions', function () { + var section = parser.parseMax('foo="(", bar="}") bing bong'); + assert(section.start === 0); + assert(section.end === 16);//exclusive end of string + assert(section.src = 'foo="(", bar="}"'); + + var section = parser.parseMax('{foo="(", bar="}"} bing bong', {start: 1}); + assert(section.start === 1); + assert(section.end === 17);//exclusive end of string + assert(section.src = 'foo="(", bar="}"'); +}); + +it('finds code up to a custom delimiter', function () { + var section = parser.parseUntil('foo.bar("%>").baz%> bing bong', '%>'); + assert(section.start === 0); + assert(section.end === 17);//exclusive end of string + assert(section.src = 'foo.bar("%>").baz'); + + var section = parser.parseUntil('<%foo.bar("%>").baz%> bing bong', '%>', {start: 2}); + assert(section.start === 2); + assert(section.end === 19);//exclusive end of string + assert(section.src = 'foo.bar("%>").baz'); +}); + +describe('regressions', function () { + describe('#1', function () { + it('parses regular expressions', function () { + var section = parser.parseMax('foo=/\\//g, bar="}") bing bong'); + assert(section.start === 0); + assert(section.end === 18);//exclusive end of string + assert(section.src = 'foo=/\\//g, bar="}"'); + }) + }) +}) \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/.npmignore b/node_modules/jade/node_modules/commander/.npmignore new file mode 100644 index 000000000..f1250e584 --- /dev/null +++ b/node_modules/jade/node_modules/commander/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/jade/node_modules/commander/.travis.yml b/node_modules/jade/node_modules/commander/.travis.yml new file mode 100644 index 000000000..f1d0f13c8 --- /dev/null +++ b/node_modules/jade/node_modules/commander/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/jade/node_modules/commander/History.md b/node_modules/jade/node_modules/commander/History.md new file mode 100644 index 000000000..160dc6bd1 --- /dev/null +++ b/node_modules/jade/node_modules/commander/History.md @@ -0,0 +1,152 @@ + +1.1.1 / 2012-11-20 +================== + + * add more sub-command padding + * fix .usage() when args are present. Closes #106 + +1.1.0 / 2012-11-16 +================== + + * add git-style executable subcommand support. Closes #94 + +1.0.5 / 2012-10-09 +================== + + * fix `--name` clobbering. Closes #92 + * fix examples/help. Closes #89 + +1.0.4 / 2012-09-03 +================== + + * add `outputHelp()` method. + +1.0.3 / 2012-08-30 +================== + + * remove invalid .version() defaulting + +1.0.2 / 2012-08-24 +================== + + * add `--foo=bar` support [arv] + * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] + +1.0.1 / 2012-08-03 +================== + + * fix issue #56 + * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) + +1.0.0 / 2012-07-05 +================== + + * add support for optional option descriptions + * add defaulting of `.version()` to package.json's version + +0.6.1 / 2012-06-01 +================== + + * Added: append (yes or no) on confirmation + * Added: allow node.js v0.7.x + +0.6.0 / 2012-04-10 +================== + + * Added `.prompt(obj, callback)` support. Closes #49 + * Added default support to .choose(). Closes #41 + * Fixed the choice example + +0.5.1 / 2011-12-20 +================== + + * Fixed `password()` for recent nodes. Closes #36 + +0.5.0 / 2011-12-04 +================== + + * Added sub-command option support [itay] + +0.4.3 / 2011-12-04 +================== + + * Fixed custom help ordering. Closes #32 + +0.4.2 / 2011-11-24 +================== + + * Added travis support + * Fixed: line-buffered input automatically trimmed. Closes #31 + +0.4.1 / 2011-11-18 +================== + + * Removed listening for "close" on --help + +0.4.0 / 2011-11-15 +================== + + * Added support for `--`. Closes #24 + +0.3.3 / 2011-11-14 +================== + + * Fixed: wait for close event when writing help info [Jerry Hamlet] + +0.3.2 / 2011-11-01 +================== + + * Fixed long flag definitions with values [felixge] + +0.3.1 / 2011-10-31 +================== + + * Changed `--version` short flag to `-V` from `-v` + * Changed `.version()` so it's configurable [felixge] + +0.3.0 / 2011-10-31 +================== + + * Added support for long flags only. Closes #18 + +0.2.1 / 2011-10-24 +================== + + * "node": ">= 0.4.x < 0.7.0". Closes #20 + +0.2.0 / 2011-09-26 +================== + + * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] + +0.1.0 / 2011-08-24 +================== + + * Added support for custom `--help` output + +0.0.5 / 2011-08-18 +================== + + * Changed: when the user enters nothing prompt for password again + * Fixed issue with passwords beginning with numbers [NuckChorris] + +0.0.4 / 2011-08-15 +================== + + * Fixed `Commander#args` + +0.0.3 / 2011-08-15 +================== + + * Added default option value support + +0.0.2 / 2011-08-15 +================== + + * Added mask support to `Command#password(str[, mask], fn)` + * Added `Command#password(str, fn)` + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/jade/node_modules/commander/Makefile b/node_modules/jade/node_modules/commander/Makefile new file mode 100644 index 000000000..007462553 --- /dev/null +++ b/node_modules/jade/node_modules/commander/Makefile @@ -0,0 +1,7 @@ + +TESTS = $(shell find test/test.*.js) + +test: + @./test/run $(TESTS) + +.PHONY: test \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/Readme.md b/node_modules/jade/node_modules/commander/Readme.md new file mode 100644 index 000000000..f93f3622a --- /dev/null +++ b/node_modules/jade/node_modules/commander/Readme.md @@ -0,0 +1,270 @@ +# Commander.js + + The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). + + [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) + +## Installation + + $ npm install commander + +## Option parsing + + Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.0.1') + .option('-p, --peppers', 'Add peppers') + .option('-P, --pineapple', 'Add pineapple') + .option('-b, --bbq', 'Add bbq sauce') + .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') + .parse(process.argv); + +console.log('you ordered a pizza with:'); +if (program.peppers) console.log(' - peppers'); +if (program.pineapple) console.log(' - pineappe'); +if (program.bbq) console.log(' - bbq'); +console.log(' - %s cheese', program.cheese); +``` + + Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +``` + $ ./examples/pizza --help + + Usage: pizza [options] + + Options: + + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineappe + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese [marble] + -h, --help output usage information + +``` + +## Coercion + +```js +function range(val) { + return val.split('..').map(Number); +} + +function list(val) { + return val.split(','); +} + +program + .version('0.0.1') + .usage('[options] ') + .option('-i, --integer ', 'An integer argument', parseInt) + .option('-f, --float ', 'A float argument', parseFloat) + .option('-r, --range
    ..', 'A range', range) + .option('-l, --list ', 'A list', list) + .option('-o, --optional [value]', 'An optional value') + .parse(process.argv); + +console.log(' int: %j', program.integer); +console.log(' float: %j', program.float); +console.log(' optional: %j', program.optional); +program.range = program.range || []; +console.log(' range: %j..%j', program.range[0], program.range[1]); +console.log(' list: %j', program.list); +console.log(' args: %j', program.args); +``` + +## Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviours, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('../'); + +function list(val) { + return val.split(',').map(Number); +} + +program + .version('0.0.1') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log(' Examples:'); + console.log(''); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); + console.log(''); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +yielding the following help output: + +``` + +Usage: custom-help [options] + +Options: + + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + + $ custom-help --help + $ custom-help -h + +``` + +## .prompt(msg, fn) + + Single-line prompt: + +```js +program.prompt('name: ', function(name){ + console.log('hi %s', name); +}); +``` + + Multi-line prompt: + +```js +program.prompt('description:', function(name){ + console.log('hi %s', name); +}); +``` + + Coercion: + +```js +program.prompt('Age: ', Number, function(age){ + console.log('age: %j', age); +}); +``` + +```js +program.prompt('Birthdate: ', Date, function(date){ + console.log('date: %s', date); +}); +``` + +## .password(msg[, mask], fn) + +Prompt for password without echoing: + +```js +program.password('Password: ', function(pass){ + console.log('got "%s"', pass); + process.stdin.destroy(); +}); +``` + +Prompt for password with mask char "*": + +```js +program.password('Password: ', '*', function(pass){ + console.log('got "%s"', pass); + process.stdin.destroy(); +}); +``` + +## .confirm(msg, fn) + + Confirm with the given `msg`: + +```js +program.confirm('continue? ', function(ok){ + console.log(' got %j', ok); +}); +``` + +## .choose(list, fn) + + Let the user choose from a `list`: + +```js +var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; + +console.log('Choose the coolest pet:'); +program.choose(list, function(i){ + console.log('you chose %d "%s"', i, list[i]); +}); +``` + +## .outputHelp() + + Output help information without exiting. + +## .help() + + Output help information and exit immediately. + +## Links + + - [API documentation](http://visionmedia.github.com/commander.js/) + - [ascii tables](https://github.com/LearnBoost/cli-table) + - [progress bars](https://github.com/visionmedia/node-progress) + - [more progress bars](https://github.com/substack/node-multimeter) + - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/index.js b/node_modules/jade/node_modules/commander/index.js new file mode 100644 index 000000000..bddca73af --- /dev/null +++ b/node_modules/jade/node_modules/commander/index.js @@ -0,0 +1,1131 @@ +/*! + * commander + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter + , spawn = require('child_process').spawn + , keypress = require('keypress') + , fs = require('fs') + , exists = fs.existsSync + , path = require('path') + , tty = require('tty') + , dirname = path.dirname + , basename = path.basename; + +/** + * Expose the root command. + */ + +exports = module.exports = new Command; + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = ~flags.indexOf('<'); + this.optional = ~flags.indexOf('['); + this.bool = !~flags.indexOf('-no-'); + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function(){ + return this.long + .replace('--', '') + .replace('no-', ''); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg){ + return arg == this.short + || arg == this.long; +}; + +/** + * Initialize a new `Command`. + * + * @param {String} name + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._args = []; + this._name = name; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +Command.prototype.__proto__ = EventEmitter.prototype; + +/** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * Examples: + * + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function(){ + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd){ + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env){ + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] + * @return {Command} the new command + * @api public + */ + +Command.prototype.command = function(name, desc){ + var args = name.split(/ +/); + var cmd = new Command(args.shift()); + if (desc) cmd.description(desc); + if (desc) this.executables = true; + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + if (desc) return this; + return cmd; +}; + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args){ + if (!args.length) return; + var self = this; + args.forEach(function(arg){ + switch (arg[0]) { + case '<': + self._args.push({ required: true, name: arg.slice(1, -1) }); + break; + case '[': + self._args.push({ required: false, name: arg.slice(1, -1) }); + break; + } + }); + return this; +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function(){ + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn){ + var self = this; + this.parent.on(this._name, function(args, unknown){ + // Parse any so-far unknown options + unknown = unknown || []; + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfNecessary(self, parsed.unknown); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i){ + if (arg.required && null == args[i]) { + self.missingArgument(arg.name); + } + }); + + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; + } else { + args.push(self); + } + + fn.apply(this, args); + }); + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to false + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => true + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|Mixed} fn or default + * @param {Mixed} defaultValue + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue){ + var self = this + , option = new Option(flags, description) + , oname = option.name() + , name = camelcase(oname); + + // default as 3rd arg + if ('function' != typeof fn) defaultValue = fn, fn = null; + + // preassign default value only for --no-*, [optional], or + if (false == option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (false == option.bool) defaultValue = true; + // preassign only if we have a default + if (undefined !== defaultValue) self[name] = defaultValue; + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on(oname, function(val){ + // coercion + if (null != val && fn) val = fn(val); + + // unassigned or bool + if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { + // if no value, bool true, and we have a default, then use it! + if (null == val) { + self[name] = option.bool + ? defaultValue || true + : false; + } else { + self[name] = val; + } + } else if (null !== val) { + // reassign + self[name] = val; + } + }); + + return this; +}; + +/** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv){ + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1]); + + // process argv + var parsed = this.parseOptions(this.normalize(argv.slice(2))); + var args = this.args = parsed.args; + + // executable sub-commands, skip .parseArgs() + if (this.executables) return this.executeSubCommand(argv, args, parsed.unknown); + + return this.parseArgs(this.args, parsed.unknown); +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown) { + args = args.concat(unknown); + + if (!args.length) this.help(); + if ('help' == args[0] && 1 == args.length) this.help(); + + // --help + if ('help' == args[0]) { + args[0] = args[1]; + args[1] = '--help'; + } + + // executable + var dir = dirname(argv[1]); + var bin = basename(argv[1]) + '-' + args[0]; + + // check for ./ first + var local = path.join(dir, bin); + if (exists(local)) bin = local; + + // run it + args = args.slice(1); + var proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); + proc.on('exit', function(code){ + if (code == 127) { + console.error('\n %s(1) does not exist\n', bin); + } + }); +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args){ + var ret = [] + , arg + , index; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { + arg.slice(1).split('').forEach(function(c){ + ret.push('-' + c); + }); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown){ + var cmds = this.commands + , len = cmds.length + , name; + + if (args.length) { + name = args[0]; + if (this.listeners(name).length) { + this.emit(args.shift(), args, unknown); + } else { + this.emit('*', args); + } + } else { + outputHelpIfNecessary(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0) { + this.unknownOption(unknown[0]); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg){ + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {Array} + * @api public + */ + +Command.prototype.parseOptions = function(argv){ + var args = [] + , len = argv.length + , literal + , option + , arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if ('--' == arg) { + literal = true; + continue; + } + + if (literal) { + args.push(arg); + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (null == arg) return this.optionMissingArgument(option); + if ('-' == arg[0]) return this.optionMissingArgument(option, arg); + this.emit(option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i+1]; + if (null == arg || '-' == arg[0]) { + arg = null; + } else { + ++i; + } + this.emit(option.name(), arg); + // bool + } else { + this.emit(option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && '-' == arg[0]) { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if (argv[i+1] && '-' != argv[i+1][0]) { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name){ + console.error(); + console.error(" error: missing required argument `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {String} option + * @param {String} flag + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag){ + console.error(); + if (flag) { + console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); + } else { + console.error(" error: option `%s' argument missing", option.flags); + } + console.error(); + process.exit(1); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag){ + console.error(); + console.error(" error: unknown option `%s'", flag); + console.error(); + process.exit(1); +}; + + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {String} str + * @param {String} flags + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags){ + if (0 == arguments.length) return this._version; + this._version = str; + flags = flags || '-V, --version'; + this.option(flags, 'output the version number'); + this.on('version', function(){ + console.log(str); + process.exit(0); + }); + return this; +}; + +/** + * Set the description `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str){ + if (0 == arguments.length) return this._description; + this._description = str; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str){ + var args = this._args.map(function(arg){ + return arg.required + ? '<' + arg.name + '>' + : '[' + arg.name + ']'; + }); + + var usage = '[options' + + (this.commands.length ? '] [command' : '') + + ']' + + (this._args.length ? ' ' + args : ''); + + if (0 == arguments.length) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function(){ + return this.options.reduce(function(max, option){ + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function(){ + var width = this.largestOptionLength(); + + // Prepend the help information + return [pad('-h, --help', width) + ' ' + 'output usage information'] + .concat(this.options.map(function(option){ + return pad(option.flags, width) + + ' ' + option.description; + })) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function(){ + if (!this.commands.length) return ''; + return [ + '' + , ' Commands:' + , '' + , this.commands.map(function(cmd){ + var args = cmd._args.map(function(arg){ + return arg.required + ? '<' + arg.name + '>' + : '[' + arg.name + ']'; + }).join(' '); + + return pad(cmd._name + + (cmd.options.length + ? ' [options]' + : '') + ' ' + args, 22) + + (cmd.description() + ? ' ' + cmd.description() + : ''); + }).join('\n').replace(/^/gm, ' ') + , '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function(){ + return [ + '' + , ' Usage: ' + this._name + ' ' + this.usage() + , '' + this.commandHelp() + , ' Options:' + , '' + , '' + this.optionHelp().replace(/^/gm, ' ') + , '' + , '' + ].join('\n'); +}; + +/** + * Prompt for a `Number`. + * + * @param {String} str + * @param {Function} fn + * @api private + */ + +Command.prototype.promptForNumber = function(str, fn){ + var self = this; + this.promptSingleLine(str, function parseNumber(val){ + val = Number(val); + if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); + fn(val); + }); +}; + +/** + * Prompt for a `Date`. + * + * @param {String} str + * @param {Function} fn + * @api private + */ + +Command.prototype.promptForDate = function(str, fn){ + var self = this; + this.promptSingleLine(str, function parseDate(val){ + val = new Date(val); + if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); + fn(val); + }); +}; + +/** + * Single-line prompt. + * + * @param {String} str + * @param {Function} fn + * @api private + */ + +Command.prototype.promptSingleLine = function(str, fn){ + if ('function' == typeof arguments[2]) { + return this['promptFor' + (fn.name || fn)](str, arguments[2]); + } + + process.stdout.write(str); + process.stdin.setEncoding('utf8'); + process.stdin.once('data', function(val){ + fn(val.trim()); + }).resume(); +}; + +/** + * Multi-line prompt. + * + * @param {String} str + * @param {Function} fn + * @api private + */ + +Command.prototype.promptMultiLine = function(str, fn){ + var buf = []; + console.log(str); + process.stdin.setEncoding('utf8'); + process.stdin.on('data', function(val){ + if ('\n' == val || '\r\n' == val) { + process.stdin.removeAllListeners('data'); + fn(buf.join('\n')); + } else { + buf.push(val.trimRight()); + } + }).resume(); +}; + +/** + * Prompt `str` and callback `fn(val)` + * + * Commander supports single-line and multi-line prompts. + * To issue a single-line prompt simply add white-space + * to the end of `str`, something like "name: ", whereas + * for a multi-line prompt omit this "description:". + * + * + * Examples: + * + * program.prompt('Username: ', function(name){ + * console.log('hi %s', name); + * }); + * + * program.prompt('Description:', function(desc){ + * console.log('description was "%s"', desc.trim()); + * }); + * + * @param {String|Object} str + * @param {Function} fn + * @api public + */ + +Command.prototype.prompt = function(str, fn){ + var self = this; + + if ('string' == typeof str) { + if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); + this.promptMultiLine(str, fn); + } else { + var keys = Object.keys(str) + , obj = {}; + + function next() { + var key = keys.shift() + , label = str[key]; + + if (!key) return fn(obj); + self.prompt(label, function(val){ + obj[key] = val; + next(); + }); + } + + next(); + } +}; + +/** + * Prompt for password with `str`, `mask` char and callback `fn(val)`. + * + * The mask string defaults to '', aka no output is + * written while typing, you may want to use "*" etc. + * + * Examples: + * + * program.password('Password: ', function(pass){ + * console.log('got "%s"', pass); + * process.stdin.destroy(); + * }); + * + * program.password('Password: ', '*', function(pass){ + * console.log('got "%s"', pass); + * process.stdin.destroy(); + * }); + * + * @param {String} str + * @param {String} mask + * @param {Function} fn + * @api public + */ + +Command.prototype.password = function(str, mask, fn){ + var self = this + , buf = ''; + + // default mask + if ('function' == typeof mask) { + fn = mask; + mask = ''; + } + + keypress(process.stdin); + + function setRawMode(mode) { + if (process.stdin.setRawMode) { + process.stdin.setRawMode(mode); + } else { + tty.setRawMode(mode); + } + }; + setRawMode(true); + process.stdout.write(str); + + // keypress + process.stdin.on('keypress', function(c, key){ + if (key && 'enter' == key.name) { + console.log(); + process.stdin.pause(); + process.stdin.removeAllListeners('keypress'); + setRawMode(false); + if (!buf.trim().length) return self.password(str, mask, fn); + fn(buf); + return; + } + + if (key && key.ctrl && 'c' == key.name) { + console.log('%s', buf); + process.exit(); + } + + process.stdout.write(mask); + buf += c; + }).resume(); +}; + +/** + * Confirmation prompt with `str` and callback `fn(bool)` + * + * Examples: + * + * program.confirm('continue? ', function(ok){ + * console.log(' got %j', ok); + * process.stdin.destroy(); + * }); + * + * @param {String} str + * @param {Function} fn + * @api public + */ + + +Command.prototype.confirm = function(str, fn, verbose){ + var self = this; + this.prompt(str, function(ok){ + if (!ok.trim()) { + if (!verbose) str += '(yes or no) '; + return self.confirm(str, fn, true); + } + fn(parseBool(ok)); + }); +}; + +/** + * Choice prompt with `list` of items and callback `fn(index, item)` + * + * Examples: + * + * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; + * + * console.log('Choose the coolest pet:'); + * program.choose(list, function(i){ + * console.log('you chose %d "%s"', i, list[i]); + * process.stdin.destroy(); + * }); + * + * @param {Array} list + * @param {Number|Function} index or fn + * @param {Function} fn + * @api public + */ + +Command.prototype.choose = function(list, index, fn){ + var self = this + , hasDefault = 'number' == typeof index; + + if (!hasDefault) { + fn = index; + index = null; + } + + list.forEach(function(item, i){ + if (hasDefault && i == index) { + console.log('* %d) %s', i + 1, item); + } else { + console.log(' %d) %s', i + 1, item); + } + }); + + function again() { + self.prompt(' : ', function(val){ + val = parseInt(val, 10) - 1; + if (hasDefault && isNaN(val)) val = index; + + if (null == list[val]) { + again(); + } else { + fn(val, list[val]); + } + }); + } + + again(); +}; + + +/** + * Output help information for this command + * + * @api public + */ + +Command.prototype.outputHelp = function(){ + process.stdout.write(this.helpInformation()); + this.emit('--help'); +}; + +/** + * Output help information and exit. + * + * @api public + */ + +Command.prototype.help = function(){ + this.outputHelp(); + process.exit(); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word){ + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Parse a boolean `str`. + * + * @param {String} str + * @return {Boolean} + * @api private + */ + +function parseBool(str) { + return /^y|yes|ok|true$/i.test(str); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Output help information if necessary + * + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help + * @api private + */ + +function outputHelpIfNecessary(cmd, options) { + options = options || []; + for (var i = 0; i < options.length; i++) { + if (options[i] == '--help' || options[i] == '-h') { + cmd.outputHelp(); + process.exit(0); + } + } +} diff --git a/node_modules/jade/node_modules/commander/node_modules/keypress/README.md b/node_modules/jade/node_modules/commander/node_modules/keypress/README.md new file mode 100644 index 000000000..a768e8f59 --- /dev/null +++ b/node_modules/jade/node_modules/commander/node_modules/keypress/README.md @@ -0,0 +1,101 @@ +keypress +======== +### Make any Node ReadableStream emit "keypress" events + + +Previous to Node `v0.8.x`, there was an undocumented `"keypress"` event that +`process.stdin` would emit when it was a TTY. Some people discovered this hidden +gem, and started using it in their own code. + +Now in Node `v0.8.x`, this `"keypress"` event does not get emitted by default, +but rather only when it is being used in conjuction with the `readline` (or by +extension, the `repl`) module. + +This module is the exact logic from the node `v0.8.x` releases ripped out into its +own module. + +__Bonus:__ Now with mouse support! + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install keypress +``` + +Or add it to the `"dependencies"` section of your _package.json_ file. + + +Example +------- + +#### Listening for "keypress" events + +``` js +var keypress = require('keypress'); + +// make `process.stdin` begin emitting "keypress" events +keypress(process.stdin); + +// listen for the "keypress" event +process.stdin.on('keypress', function (ch, key) { + console.log('got "keypress"', key); + if (key && key.ctrl && key.name == 'c') { + process.stdin.pause(); + } +}); + +process.stdin.setRawMode(true); +process.stdin.resume(); +``` + +#### Listening for "mousepress" events + +``` js +var keypress = require('keypress'); + +// make `process.stdin` begin emitting "mousepress" (and "keypress") events +keypress(process.stdin); + +// you must enable the mouse events before they will begin firing +keypress.enableMouse(process.stdout); + +process.stdin.on('mousepress', function (info) { + console.log('got "mousepress" event at %d x %d', info.x, info.y); +}); + +process.on('exit', function () { + // disable mouse on exit, so that the state + // is back to normal for the terminal + keypress.disableMouse(process.stdout); +}); +``` + + +License +------- + +(The MIT License) + +Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> + +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/jade/node_modules/commander/node_modules/keypress/index.js b/node_modules/jade/node_modules/commander/node_modules/keypress/index.js new file mode 100644 index 000000000..c2ba488ba --- /dev/null +++ b/node_modules/jade/node_modules/commander/node_modules/keypress/index.js @@ -0,0 +1,346 @@ + +/** + * This module offers the internal "keypress" functionality from node-core's + * `readline` module, for your own programs and modules to use. + * + * Usage: + * + * require('keypress')(process.stdin); + * + * process.stdin.on('keypress', function (ch, key) { + * console.log(ch, key); + * if (key.ctrl && key.name == 'c') { + * process.stdin.pause(); + * } + * }); + * proces.stdin.resume(); + */ +var exports = module.exports = keypress; + +exports.enableMouse = function (stream) { + stream.write('\x1b' +'[?1000h') +} + +exports.disableMouse = function (stream) { + stream.write('\x1b' +'[?1000l') +} + + +/** + * accepts a readable Stream instance and makes it emit "keypress" events + */ + +function keypress(stream) { + if (isEmittingKeypress(stream)) return; + stream._emitKeypress = true; + + function onData(b) { + if (stream.listeners('keypress').length > 0) { + emitKey(stream, b); + } else { + // Nobody's watching anyway + stream.removeListener('data', onData); + stream.on('newListener', onNewListener); + } + } + + function onNewListener(event) { + if (event == 'keypress') { + stream.on('data', onData); + stream.removeListener('newListener', onNewListener); + } + } + + if (stream.listeners('keypress').length > 0) { + stream.on('data', onData); + } else { + stream.on('newListener', onNewListener); + } +} + +/** + * Returns `true` if the stream is already emitting "keypress" events. + * `false` otherwise. + */ + +function isEmittingKeypress(stream) { + var rtn = stream._emitKeypress; + if (!rtn) { + // hack: check for the v0.6.x "data" event + stream.listeners('data').forEach(function (l) { + if (l.name == 'onData' && /emitKey/.test(l.toString())) { + rtn = true; + stream._emitKeypress = true; + } + }); + } + if (!rtn) { + // hack: check for the v0.6.x "newListener" event + stream.listeners('newListener').forEach(function (l) { + if (l.name == 'onNewListener' && /keypress/.test(l.toString())) { + rtn = true; + stream._emitKeypress = true; + } + }); + } + return rtn; +} + + +/* + Some patterns seen in terminal key escape codes, derived from combos seen + at http://www.midnight-commander.org/browser/lib/tty/key.c + + ESC letter + ESC [ letter + ESC [ modifier letter + ESC [ 1 ; modifier letter + ESC [ num char + ESC [ num ; modifier char + ESC O letter + ESC O modifier letter + ESC O 1 ; modifier letter + ESC N letter + ESC [ [ num ; modifier char + ESC [ [ 1 ; modifier letter + ESC ESC [ num char + ESC ESC O letter + + - char is usually ~ but $ and ^ also happen with rxvt + - modifier is 1 + + (shift * 1) + + (left_alt * 2) + + (ctrl * 4) + + (right_alt * 8) + - two leading ESCs apparently mean the same as one leading ESC +*/ + +// Regexes used for ansi escape code splitting +var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/; +var functionKeyCodeRe = + /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/; + +function emitKey(stream, s) { + var ch, + key = { + name: undefined, + ctrl: false, + meta: false, + shift: false + }, + parts; + + if (Buffer.isBuffer(s)) { + if (s[0] > 127 && s[1] === undefined) { + s[0] -= 128; + s = '\x1b' + s.toString(stream.encoding || 'utf-8'); + } else { + s = s.toString(stream.encoding || 'utf-8'); + } + } + + key.sequence = s; + + if (s === '\r' || s === '\n') { + // enter + key.name = 'enter'; + + } else if (s === '\t') { + // tab + key.name = 'tab'; + + } else if (s === '\b' || s === '\x7f' || + s === '\x1b\x7f' || s === '\x1b\b') { + // backspace or ctrl+h + key.name = 'backspace'; + key.meta = (s.charAt(0) === '\x1b'); + + } else if (s === '\x1b' || s === '\x1b\x1b') { + // escape key + key.name = 'escape'; + key.meta = (s.length === 2); + + } else if (s === ' ' || s === '\x1b ') { + key.name = 'space'; + key.meta = (s.length === 2); + + } else if (s <= '\x1a') { + // ctrl+letter + key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); + key.ctrl = true; + + } else if (s.length === 1 && s >= 'a' && s <= 'z') { + // lowercase letter + key.name = s; + + } else if (s.length === 1 && s >= 'A' && s <= 'Z') { + // shift+letter + key.name = s.toLowerCase(); + key.shift = true; + + } else if (parts = metaKeyCodeRe.exec(s)) { + // meta+character key + key.name = parts[1].toLowerCase(); + key.meta = true; + key.shift = /^[A-Z]$/.test(parts[1]); + + } else if (parts = functionKeyCodeRe.exec(s)) { + // ansi escape sequence + + // reassemble the key code leaving out leading \x1b's, + // the modifier key bitflag and any meaningless "1;" sequence + var code = (parts[1] || '') + (parts[2] || '') + + (parts[4] || '') + (parts[6] || ''), + modifier = (parts[3] || parts[5] || 1) - 1; + + // Parse the key modifier + key.ctrl = !!(modifier & 4); + key.meta = !!(modifier & 10); + key.shift = !!(modifier & 1); + key.code = code; + + // Parse the key itself + switch (code) { + /* xterm/gnome ESC O letter */ + case 'OP': key.name = 'f1'; break; + case 'OQ': key.name = 'f2'; break; + case 'OR': key.name = 'f3'; break; + case 'OS': key.name = 'f4'; break; + + /* xterm/rxvt ESC [ number ~ */ + case '[11~': key.name = 'f1'; break; + case '[12~': key.name = 'f2'; break; + case '[13~': key.name = 'f3'; break; + case '[14~': key.name = 'f4'; break; + + /* from Cygwin and used in libuv */ + case '[[A': key.name = 'f1'; break; + case '[[B': key.name = 'f2'; break; + case '[[C': key.name = 'f3'; break; + case '[[D': key.name = 'f4'; break; + case '[[E': key.name = 'f5'; break; + + /* common */ + case '[15~': key.name = 'f5'; break; + case '[17~': key.name = 'f6'; break; + case '[18~': key.name = 'f7'; break; + case '[19~': key.name = 'f8'; break; + case '[20~': key.name = 'f9'; break; + case '[21~': key.name = 'f10'; break; + case '[23~': key.name = 'f11'; break; + case '[24~': key.name = 'f12'; break; + + /* xterm ESC [ letter */ + case '[A': key.name = 'up'; break; + case '[B': key.name = 'down'; break; + case '[C': key.name = 'right'; break; + case '[D': key.name = 'left'; break; + case '[E': key.name = 'clear'; break; + case '[F': key.name = 'end'; break; + case '[H': key.name = 'home'; break; + + /* xterm/gnome ESC O letter */ + case 'OA': key.name = 'up'; break; + case 'OB': key.name = 'down'; break; + case 'OC': key.name = 'right'; break; + case 'OD': key.name = 'left'; break; + case 'OE': key.name = 'clear'; break; + case 'OF': key.name = 'end'; break; + case 'OH': key.name = 'home'; break; + + /* xterm/rxvt ESC [ number ~ */ + case '[1~': key.name = 'home'; break; + case '[2~': key.name = 'insert'; break; + case '[3~': key.name = 'delete'; break; + case '[4~': key.name = 'end'; break; + case '[5~': key.name = 'pageup'; break; + case '[6~': key.name = 'pagedown'; break; + + /* putty */ + case '[[5~': key.name = 'pageup'; break; + case '[[6~': key.name = 'pagedown'; break; + + /* rxvt */ + case '[7~': key.name = 'home'; break; + case '[8~': key.name = 'end'; break; + + /* rxvt keys with modifiers */ + case '[a': key.name = 'up'; key.shift = true; break; + case '[b': key.name = 'down'; key.shift = true; break; + case '[c': key.name = 'right'; key.shift = true; break; + case '[d': key.name = 'left'; key.shift = true; break; + case '[e': key.name = 'clear'; key.shift = true; break; + + case '[2$': key.name = 'insert'; key.shift = true; break; + case '[3$': key.name = 'delete'; key.shift = true; break; + case '[5$': key.name = 'pageup'; key.shift = true; break; + case '[6$': key.name = 'pagedown'; key.shift = true; break; + case '[7$': key.name = 'home'; key.shift = true; break; + case '[8$': key.name = 'end'; key.shift = true; break; + + case 'Oa': key.name = 'up'; key.ctrl = true; break; + case 'Ob': key.name = 'down'; key.ctrl = true; break; + case 'Oc': key.name = 'right'; key.ctrl = true; break; + case 'Od': key.name = 'left'; key.ctrl = true; break; + case 'Oe': key.name = 'clear'; key.ctrl = true; break; + + case '[2^': key.name = 'insert'; key.ctrl = true; break; + case '[3^': key.name = 'delete'; key.ctrl = true; break; + case '[5^': key.name = 'pageup'; key.ctrl = true; break; + case '[6^': key.name = 'pagedown'; key.ctrl = true; break; + case '[7^': key.name = 'home'; key.ctrl = true; break; + case '[8^': key.name = 'end'; key.ctrl = true; break; + + /* misc. */ + case '[Z': key.name = 'tab'; key.shift = true; break; + default: key.name = 'undefined'; break; + + } + } else if (s.length > 1 && s[0] !== '\x1b') { + // Got a longer-than-one string of characters. + // Probably a paste, since it wasn't a control sequence. + Array.prototype.forEach.call(s, function(c) { + emitKey(stream, c); + }); + return; + } + + if (key.code == '[M') { + key.name = 'mouse'; + var s = key.sequence; + var b = s.charCodeAt(3); + key.x = s.charCodeAt(4) - 040; + key.y = s.charCodeAt(5) - 040; + + key.scroll = 0; + + key.ctrl = !!(1<<4 & b); + key.meta = !!(1<<3 & b); + key.shift = !!(1<<2 & b); + + key.release = (3 & b) === 3; + + if (1<<6 & b) { //scroll + key.scroll = 1 & b ? 1 : -1; + } + + if (!key.release && !key.scroll) { + key.button = b & 3; + } + } + + // Don't emit a key if no name was found + if (key.name === undefined) { + key = undefined; + } + + if (s.length === 1) { + ch = s; + } + + if (key && key.name == 'mouse') { + stream.emit('mousepress', key) + } else if (key || ch) { + stream.emit('keypress', ch, key); + } +} diff --git a/node_modules/jade/node_modules/commander/node_modules/keypress/package.json b/node_modules/jade/node_modules/commander/node_modules/keypress/package.json new file mode 100644 index 000000000..c5462052c --- /dev/null +++ b/node_modules/jade/node_modules/commander/node_modules/keypress/package.json @@ -0,0 +1,32 @@ +{ + "name": "keypress", + "version": "0.1.0", + "description": "Make any Node ReadableStream emit \"keypress\" events", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://tootallnate.net" + }, + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/keypress.git" + }, + "keywords": [ + "keypress", + "readline", + "core" + ], + "license": "MIT", + "readme": "keypress\n========\n### Make any Node ReadableStream emit \"keypress\" events\n\n\nPrevious to Node `v0.8.x`, there was an undocumented `\"keypress\"` event that\n`process.stdin` would emit when it was a TTY. Some people discovered this hidden\ngem, and started using it in their own code.\n\nNow in Node `v0.8.x`, this `\"keypress\"` event does not get emitted by default,\nbut rather only when it is being used in conjuction with the `readline` (or by\nextension, the `repl`) module.\n\nThis module is the exact logic from the node `v0.8.x` releases ripped out into its\nown module.\n\n__Bonus:__ Now with mouse support!\n\nInstallation\n------------\n\nInstall with `npm`:\n\n``` bash\n$ npm install keypress\n```\n\nOr add it to the `\"dependencies\"` section of your _package.json_ file.\n\n\nExample\n-------\n\n#### Listening for \"keypress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"keypress\" events\nkeypress(process.stdin);\n\n// listen for the \"keypress\" event\nprocess.stdin.on('keypress', function (ch, key) {\n console.log('got \"keypress\"', key);\n if (key && key.ctrl && key.name == 'c') {\n process.stdin.pause();\n }\n});\n\nprocess.stdin.setRawMode(true);\nprocess.stdin.resume();\n```\n\n#### Listening for \"mousepress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"mousepress\" (and \"keypress\") events\nkeypress(process.stdin);\n\n// you must enable the mouse events before they will begin firing\nkeypress.enableMouse(process.stdout);\n\nprocess.stdin.on('mousepress', function (info) {\n console.log('got \"mousepress\" event at %d x %d', info.x, info.y);\n});\n\nprocess.on('exit', function () {\n // disable mouse on exit, so that the state\n // is back to normal for the terminal\n keypress.disableMouse(process.stdout);\n});\n```\n\n\nLicense\n-------\n\n(The MIT License)\n\nCopyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/TooTallNate/keypress/issues" + }, + "homepage": "https://github.com/TooTallNate/keypress", + "_id": "keypress@0.1.0", + "_from": "keypress@0.1.x" +} diff --git a/node_modules/jade/node_modules/commander/node_modules/keypress/test.js b/node_modules/jade/node_modules/commander/node_modules/keypress/test.js new file mode 100644 index 000000000..c3f61d79d --- /dev/null +++ b/node_modules/jade/node_modules/commander/node_modules/keypress/test.js @@ -0,0 +1,28 @@ + +var keypress = require('./') +keypress(process.stdin) + +if (process.stdin.setRawMode) + process.stdin.setRawMode(true) +else + require('tty').setRawMode(true) + +process.stdin.on('keypress', function (c, key) { + console.log(0, c, key) + if (key && key.ctrl && key.name == 'c') { + process.stdin.pause() + } +}) +process.stdin.on('mousepress', function (mouse) { + console.log(mouse) +}) + +keypress.enableMouse(process.stdout) +process.on('exit', function () { + //disable mouse on exit, so that the state is back to normal + //for the terminal. + keypress.disableMouse(process.stdout) +}) + +process.stdin.resume() + diff --git a/node_modules/jade/node_modules/commander/package.json b/node_modules/jade/node_modules/commander/package.json new file mode 100644 index 000000000..ee41ede69 --- /dev/null +++ b/node_modules/jade/node_modules/commander/package.json @@ -0,0 +1,53 @@ +{ + "name": "commander", + "version": "1.1.1", + "description": "the complete solution for node.js command-line programs", + "keywords": [ + "command", + "option", + "parser", + "prompt", + "stdin" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/commander.js.git" + }, + "dependencies": { + "keypress": "0.1.x" + }, + "devDependencies": { + "should": ">= 0.0.1" + }, + "scripts": { + "test": "make test" + }, + "main": "index", + "engines": { + "node": ">= 0.6.x" + }, + "_id": "commander@1.1.1", + "dist": { + "shasum": "50d1651868ae60eccff0a2d9f34595376bc6b041", + "tarball": "http://registry.npmjs.org/commander/-/commander-1.1.1.tgz" + }, + "_npmVersion": "1.1.65", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "50d1651868ae60eccff0a2d9f34595376bc6b041", + "_from": "commander@1.1.1", + "_resolved": "https://registry.npmjs.org/commander/-/commander-1.1.1.tgz" +} diff --git a/node_modules/jade/node_modules/mkdirp/.npmignore b/node_modules/jade/node_modules/mkdirp/.npmignore new file mode 100644 index 000000000..9303c347e --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/.travis.yml b/node_modules/jade/node_modules/mkdirp/.travis.yml new file mode 100644 index 000000000..84fd7ca24 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.9 diff --git a/node_modules/jade/node_modules/mkdirp/LICENSE b/node_modules/jade/node_modules/mkdirp/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/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/jade/node_modules/mkdirp/examples/pow.js b/node_modules/jade/node_modules/mkdirp/examples/pow.js new file mode 100644 index 000000000..e6924212e --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/examples/pow.js @@ -0,0 +1,6 @@ +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); diff --git a/node_modules/jade/node_modules/mkdirp/index.js b/node_modules/jade/node_modules/mkdirp/index.js new file mode 100644 index 000000000..fda6de8a2 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/index.js @@ -0,0 +1,82 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, mode, f, made) { + if (typeof mode === 'function' || mode === undefined) { + f = mode; + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + fs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), mode, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, mode, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + fs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, mode, made) { + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + try { + fs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), mode, made); + sync(p, mode, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = fs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/jade/node_modules/mkdirp/package.json b/node_modules/jade/node_modules/mkdirp/package.json new file mode 100644 index 000000000..dc4348217 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/package.json @@ -0,0 +1,34 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.3.5", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "main": "./index", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "http://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "~0.4.0" + }, + "license": "MIT", + "readme": "# mkdirp\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\n# example\n\n## pow.js\n\n```js\nvar mkdirp = require('mkdirp');\n \nmkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n});\n```\n\nOutput\n\n```\npow!\n```\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\n# methods\n\n```js\nvar mkdirp = require('mkdirp');\n```\n\n## mkdirp(dir, mode, cb)\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\n## mkdirp.sync(dir, mode)\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "homepage": "https://github.com/substack/node-mkdirp", + "_id": "mkdirp@0.3.5", + "_from": "mkdirp@0.3.x" +} diff --git a/node_modules/jade/node_modules/mkdirp/readme.markdown b/node_modules/jade/node_modules/mkdirp/readme.markdown new file mode 100644 index 000000000..83b0216ab --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/readme.markdown @@ -0,0 +1,63 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, mode, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `mode`. + +If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +## mkdirp.sync(dir, mode) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `mode`. + +If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +# license + +MIT diff --git a/node_modules/jade/node_modules/mkdirp/test/chmod.js b/node_modules/jade/node_modules/mkdirp/test/chmod.js new file mode 100644 index 000000000..520dcb8e9 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/chmod.js @@ -0,0 +1,38 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +test('chmod-pre', function (t) { + var mode = 0744 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); + t.end(); + }); + }); +}); + +test('chmod', function (t) { + var mode = 0755 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.end(); + }); + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/clobber.js b/node_modules/jade/node_modules/mkdirp/test/clobber.js new file mode 100644 index 000000000..0eb709987 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/clobber.js @@ -0,0 +1,37 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +// a file in the way +var itw = ps.slice(0, 3).join('/'); + + +test('clobber-pre', function (t) { + console.error("about to write to "+itw) + fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); + + fs.stat(itw, function (er, stat) { + t.ifError(er) + t.ok(stat && stat.isFile(), 'should be file') + t.end() + }) +}) + +test('clobber', function (t) { + t.plan(2); + mkdirp(file, 0755, function (err) { + t.ok(err); + t.equal(err.code, 'ENOTDIR'); + t.end(); + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/mkdirp.js b/node_modules/jade/node_modules/mkdirp/test/mkdirp.js new file mode 100644 index 000000000..b07cd70c1 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/mkdirp.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('woo', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/perm.js b/node_modules/jade/node_modules/mkdirp/test/perm.js new file mode 100644 index 000000000..23a7abbd2 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/perm.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('async perm', function (t) { + t.plan(2); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); + +test('async root perm', function (t) { + mkdirp('/tmp', 0755, function (err) { + if (err) t.fail(err); + t.end(); + }); + t.end(); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/perm_sync.js b/node_modules/jade/node_modules/mkdirp/test/perm_sync.js new file mode 100644 index 000000000..f685f6090 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/perm_sync.js @@ -0,0 +1,39 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('sync perm', function (t) { + t.plan(2); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; + + mkdirp.sync(file, 0755); + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }); +}); + +test('sync root perm', function (t) { + t.plan(1); + + var file = '/tmp'; + mkdirp.sync(file, 0755); + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/race.js b/node_modules/jade/node_modules/mkdirp/test/race.js new file mode 100644 index 000000000..96a044763 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/race.js @@ -0,0 +1,41 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('race', function (t) { + t.plan(4); + var ps = [ '', 'tmp' ]; + + for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); + } + var file = ps.join('/'); + + var res = 2; + mk(file, function () { + if (--res === 0) t.end(); + }); + + mk(file, function () { + if (--res === 0) t.end(); + }); + + function mk (file, cb) { + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + if (cb) cb(); + } + }) + }) + }); + } +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/rel.js b/node_modules/jade/node_modules/mkdirp/test/rel.js new file mode 100644 index 000000000..79858243a --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/rel.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('rel', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var cwd = process.cwd(); + process.chdir('/tmp'); + + var file = [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + process.chdir(cwd); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/return.js b/node_modules/jade/node_modules/mkdirp/test/return.js new file mode 100644 index 000000000..bce68e561 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/return.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, '/tmp/' + x); + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, null); + }); + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/return_sync.js b/node_modules/jade/node_modules/mkdirp/test/return_sync.js new file mode 100644 index 000000000..7c222d355 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/return_sync.js @@ -0,0 +1,24 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + // Note that this will throw on failure, which will fail the test. + var made = mkdirp.sync(file); + t.equal(made, '/tmp/' + x); + + // making the same file again should have no effect. + made = mkdirp.sync(file); + t.equal(made, null); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/root.js b/node_modules/jade/node_modules/mkdirp/test/root.js new file mode 100644 index 000000000..97ad7a2f3 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/root.js @@ -0,0 +1,18 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('root', function (t) { + // '/' on unix, 'c:/' on windows. + var file = path.resolve('/'); + + mkdirp(file, 0755, function (err) { + if (err) throw err + fs.stat(file, function (er, stat) { + if (er) throw er + t.ok(stat.isDirectory(), 'target is a directory'); + t.end(); + }) + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/sync.js b/node_modules/jade/node_modules/mkdirp/test/sync.js new file mode 100644 index 000000000..7530cada8 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('sync', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file, 0755); + } catch (err) { + t.fail(err); + return t.end(); + } + + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }); + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/umask.js b/node_modules/jade/node_modules/mkdirp/test/umask.js new file mode 100644 index 000000000..64ccafe22 --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/umask.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('implicit mode from umask', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0777 & (~process.umask())); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/jade/node_modules/mkdirp/test/umask_sync.js b/node_modules/jade/node_modules/mkdirp/test/umask_sync.js new file mode 100644 index 000000000..35bd5cbbf --- /dev/null +++ b/node_modules/jade/node_modules/mkdirp/test/umask_sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('umask sync modes', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file); + } catch (err) { + t.fail(err); + return t.end(); + } + + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, (0777 & (~process.umask()))); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }); + }); +}); diff --git a/node_modules/jade/node_modules/monocle/.npmignore b/node_modules/jade/node_modules/monocle/.npmignore new file mode 100644 index 000000000..28f1ba756 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/.npmignore @@ -0,0 +1,2 @@ +node_modules +.DS_Store \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/.travis.yml b/node_modules/jade/node_modules/monocle/.travis.yml new file mode 100644 index 000000000..4a83e22d6 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" diff --git a/node_modules/jade/node_modules/monocle/LICENSE b/node_modules/jade/node_modules/monocle/LICENSE new file mode 100644 index 000000000..417af37d7 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2013, Sam Saccone +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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. diff --git a/node_modules/jade/node_modules/monocle/README.md b/node_modules/jade/node_modules/monocle/README.md new file mode 100644 index 000000000..370bb9b58 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/README.md @@ -0,0 +1,67 @@ +[![Build Status](https://travis-ci.org/samccone/monocle.png?branch=master)](https://travis-ci.org/samccone/monocle) + +# Monocle -- a tool for watching things + +[![logo](https://raw.github.com/samccone/monocle/master/logo.png)](https://raw.github.com/samccone/monocle/master/logo.png) + +Have you ever wanted to watch a folder and all of its files/nested folders for changes. well now you can! + +## Installation + +``` +npm install monocle +``` + +## Usage + +### Watch a directory: + +```js +var monocle = require('monocle')() +monocle.watchDirectory({ + root: , + fileFilter: , + directoryFilter: , + listener: fn(fs.stat+ object), //triggered on file change / addition + complete: //file watching all set up +}); +``` + +The listener will recive an object with the following + +```js + name: , + path: , + fullPath: , + parentDir: , + fullParentDir: , + stat: +``` + +[fs.stats](http://nodejs.org/api/fs.html#fs_class_fs_stats) + +When a new file is added to the directoy it triggers a file change and thus will be passed to your specified listener. + +The two filters are passed through to `readdirp`. More documentation can be found [here](https://github.com/thlorenz/readdirp#filters) + +### Watch a list of files: + +```js +Monocle.watchFiles({ + files: [], //path of file(s) + listener: , //triggered on file / addition + complete: //file watching all set up +}); +``` + +## Why not just use fs.watch ? + + - file watching is really bad cross platforms in node + - you need to be smart when using fs.watch as compared to fs.watchFile + - Monocle takes care of this logic for you! + - windows systems use fs.watch + - osx and linux uses fs.watchFile + +## License + +BSD diff --git a/node_modules/jade/node_modules/monocle/logo.png b/node_modules/jade/node_modules/monocle/logo.png new file mode 100644 index 000000000..39d665f75 Binary files /dev/null and b/node_modules/jade/node_modules/monocle/logo.png differ diff --git a/node_modules/jade/node_modules/monocle/monocle.js b/node_modules/jade/node_modules/monocle/monocle.js new file mode 100644 index 000000000..2050da94c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/monocle.js @@ -0,0 +1,142 @@ +var path = require('path'); +var fs = require('fs'); +var readdirp = require('readdirp'); +var is_windows = process.platform === 'win32'; + +module.exports = function() { + var watched_files = {}; + var watched_directories = {}; + var check_dir_pause = 1000; + var checkInterval = undefined; + + // @api public + // Watches the directory passed and its contained files + // accepts args as an object. + + // @param root(string): the root directory to watch + // @param fileFilter(array): ignore these files + // @param directoryFilter(array): ignore these files + // @param listener(fn(file)): on file change event this will be called + // @param complete(fn): on complete of file watching setup + function watchDirectory(args) { + readdirp({ root: args.root, fileFilter: args.fileFilter, directoryFilter: args.directoryFilter }, function(err, res) { + res.files.forEach(function(file) { + watchFile(file, args.listener, args.partial); + }); + typeof args.complete == "function" && args.complete(); + }); + + !args.partial && (checkInterval = setInterval(function() {checkDirectory(args)}, check_dir_pause)); + } + + // @api public + // Watches the files passed + // accepts args as an object. + // @param files(array): a list of files to watch + // @param listener(fn(file)): on file change event this will be called + // @param complete(fn): on complete of file watching setup + function watchFiles(args) { + args.files.forEach(function(file) { + var o = { + fullPath: fs.realpathSync(file), + name: fs.realpathSync(file).split('/').pop() + }; + o.fullParentDir = o.fullPath.split('/').slice(0, o.fullPath.split('/').length - 1).join('/') + + watchFile(o, args.listener); + }); + + typeof args.complete == "function" && args.complete(); + } + + function unwatchAll() { + if (is_windows) { + Object.keys(watched_files).forEach(function(key) { + watched_files[key].close(); + }); + } else { + Object.keys(watched_files).forEach(function(key) { + fs.unwatchFile(key); + }); + } + + clearInterval(checkInterval); + watched_files = {}; + watched_directories = {}; + } + + // Checks to see if something in the directory has changed + function checkDirectory(args) { + Object.keys(watched_directories).forEach(function(path) { + var lastModified = watched_directories[path]; + fs.stat(path, function(err, stats) { + var stats_stamp = lastModified; + if (!err) { + stats_stamp = (new Date(stats.mtime)).getTime(); + } + if (stats_stamp != lastModified) { + watched_directories[path] = stats_stamp; + watchDirectory({ + root: path, + listener: args.listener, + fileFilter: args.fileFilter, + directoryFilter: args.directoryFilter, + partial: true + }); + } + }); + }); + } + + // sets the absolute path to the file from the current working dir + function setAbsolutePath(file) { + file.absolutePath = path.resolve(process.cwd(), file.fullPath); + return file.absolutePath; + } + + // Watches the file passed and its containing directory + // on change calls given listener with file object + function watchFile(file, cb, partial) { + setAbsolutePath(file); + storeDirectory(file); + if (!watched_files[file.fullPath]) { + if (is_windows) { + (function() { + watched_files[file.fullPath] = fs.watch(file.fullPath, function() { + typeof cb === "function" && cb(file); + }); + partial && cb(file); + })(file, cb); + } else { + (function(file, cb) { + watched_files[file.fullPath] = true; + fs.watchFile(file.fullPath, {interval: 150}, function() { + typeof cb === "function" && cb(file); + }); + partial && cb(file); + })(file, cb); + } + } + } + + // Sets up a store of the folders being watched + // and saves the last modification timestamp for it + function storeDirectory(file) { + var directory = file.fullParentDir; + if (!watched_directories[directory]) { + fs.stat(directory, function(err, stats) { + if (err) { + watched_directories[directory] = (new Date).getTime(); + } else { + watched_directories[directory] = (new Date(stats.mtime)).getTime(); + } + }); + } + } + + return { + watchDirectory: watchDirectory, + watchFiles: watchFiles, + unwatchAll: unwatchAll + }; +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/.npmignore new file mode 100644 index 000000000..7dccd9707 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/.travis.yml new file mode 100644 index 000000000..84fd7ca24 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.9 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/LICENSE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/LICENSE new file mode 100644 index 000000000..ee27ba4b4 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/README.md new file mode 100644 index 000000000..7b36a8a8b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/README.md @@ -0,0 +1,227 @@ +# readdirp [![Build Status](https://secure.travis-ci.org/thlorenz/readdirp.png)](http://travis-ci.org/thlorenz/readdirp) + +Recursive version of [fs.readdir](http://nodejs.org/docs/latest/api/fs.html#fs_fs_readdir_path_callback). Exposes a **stream api**. + +```javascript +var readdirp = require('readdirp'); + , path = require('path') + , es = require('event-stream'); + +// print out all JavaScript files along with their size + +var stream = readdirp({ root: path.join(__dirname), fileFilter: '*.js' }); +stream + .on('warn', function (err) { + console.error('non-fatal error', err); + // optionally call stream.destroy() here in order to abort and cause 'close' to be emitted + }) + .on('error', function (err) { console.error('fatal error', err); }) + .pipe(es.mapSync(function (entry) { + return { path: entry.path, size: entry.stat.size }; + })) + .pipe(es.stringify()) + .pipe(process.stdout); +``` + +Meant to be one of the recursive versions of [fs](http://nodejs.org/docs/latest/api/fs.html) functions, e.g., like [mkdirp](https://github.com/substack/node-mkdirp). + +**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)* + +- [Installation](#installation) +- [API](#api) + - [entry stream](#entry-stream) + - [options](#options) + - [entry info](#entry-info) + - [Filters](#filters) + - [Callback API](#callback-api) + - [allProcessed ](#allprocessed) + - [fileProcessed](#fileprocessed) +- [More Examples](#more-examples) + - [stream api](#stream-api) + - [stream api pipe](#stream-api-pipe) + - [grep](#grep) + - [using callback api](#using-callback-api) + - [tests](#tests) + + +# Installation + + npm install readdirp + +# API + +***var entryStream = readdirp (options)*** + +Reads given root recursively and returns a `stream` of [entry info](#entry-info)s. + +## entry stream + +Behaves as follows: + +- `emit('data')` passes an [entry info](#entry-info) whenever one is found +- `emit('warn')` passes a non-fatal `Error` that prevents a file/directory from being processed (i.e., if it is + inaccessible to the user) +- `emit('error')` passes a fatal `Error` which also ends the stream (i.e., when illegal options where passed) +- `emit('end')` called when all entries were found and no more will be emitted (i.e., we are done) +- `emit('close')` called when the stream is destroyed via `stream.destroy()` (which could be useful if you want to + manually abort even on a non fatal error) - at that point the stream is no longer `readable` and no more entries, + warning or errors are emitted +- the stream is `paused` initially in order to allow `pipe` and `on` handlers be connected before data or errors are + emitted +- the stream is `resumed` automatically during the next event loop +- to learn more about streams, consult the [stream-handbook](https://github.com/substack/stream-handbook) + +## options + +- **root**: path in which to start reading and recursing into subdirectories + +- **fileFilter**: filter to include/exclude files found (see [Filters](#filters) for more) + +- **directoryFilter**: filter to include/exclude directories found and to recurse into (see [Filters](#filters) for more) + +- **depth**: depth at which to stop recursing even if more subdirectories are found + +## entry info + +Has the following properties: + +- **parentDir** : directory in which entry was found (relative to given root) +- **fullParentDir** : full path to parent directory +- **name** : name of the file/directory +- **path** : path to the file/directory (relative to given root) +- **fullPath** : full path to the file/directory found +- **stat** : built in [stat object](http://nodejs.org/docs/v0.4.9/api/fs.html#fs.Stats) +- **Example**: (assuming root was `/User/dev/readdirp`) + + parentDir : 'test/bed/root_dir1', + fullParentDir : '/User/dev/readdirp/test/bed/root_dir1', + name : 'root_dir1_subdir1', + path : 'test/bed/root_dir1/root_dir1_subdir1', + fullPath : '/User/dev/readdirp/test/bed/root_dir1/root_dir1_subdir1', + stat : [ ... ] + +## Filters + +There are three different ways to specify filters for files and directories respectively. + +- **function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry + +- **glob string**: a string (e.g., `*.js`) which is matched using [minimatch](https://github.com/isaacs/minimatch), so go there for more + information. + + Globstars (`**`) are not supported since specifiying a recursive pattern for an already recursive function doesn't make sense. + + Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. + +- **array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. + + `[ '*.json', '*.js' ]` includes all JavaScript and Json files. + + + `[ '!.git', '!node_modules' ]` includes all directories except the '.git' and 'node_modules'. + +Directories that do not pass a filter will not be recursed into. + +## Callback API + +Although the stream api is recommended, readdirp also exposes a callback based api. + +***readdirp (options, callback1 [, callback2])*** + +If callback2 is given, callback1 functions as the **fileProcessed** callback, and callback2 as the **allProcessed** callback. + +If only callback1 is given, it functions as the **allProcessed** callback. + +### allProcessed + +- function with err and res parameters, e.g., `function (err, res) { ... }` +- **err**: array of errors that occurred during the operation, **res may still be present, even if errors occurred** +- **res**: collection of file/directory [entry infos](#entry-info) + +### fileProcessed + +- function with [entry info](#entry-info) parameter e.g., `function (entryInfo) { ... }` + + +# More Examples + +`on('error', ..)`, `on('warn', ..)` and `on('end', ..)` handling omitted for brevity + +```javascript +var readdirp = require('readdirp'); + +// Glob file filter +readdirp({ root: './test/bed', fileFilter: '*.js' }) + .on('data', function (entry) { + // do something with each JavaScript file entry + }); + +// Combined glob file filters +readdirp({ root: './test/bed', fileFilter: [ '*.js', '*.json' ] }) + .on('data', function (entry) { + // do something with each JavaScript and Json file entry + }); + +// Combined negated directory filters +readdirp({ root: './test/bed', directoryFilter: [ '!.git', '!*modules' ] }) + .on('data', function (entry) { + // do something with each file entry found outside '.git' or any modules directory + }); + +// Function directory filter +readdirp({ root: './test/bed', directoryFilter: function (di) { return di.name.length === 9; } }) + .on('data', function (entry) { + // do something with each file entry found inside directories whose name has length 9 + }); + +// Limiting depth +readdirp({ root: './test/bed', depth: 1 }) + .on('data', function (entry) { + // do something with each file entry found up to 1 subdirectory deep + }); + +// callback api +readdirp( + { root: '.' } + , function(fileInfo) { + // do something with file entry here + } + , function (err, res) { + // all done, move on or do final step for all file entries here + } +); +``` + +Try more examples by following [instructions](https://github.com/thlorenz/readdirp/blob/master/examples/Readme.md) +on how to get going. + +## stream api + +[stream-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api.js) + +Demonstrates error and data handling by listening to events emitted from the readdirp stream. + +## stream api pipe + +[stream-api-pipe.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api-pipe.js) + +Demonstrates error handling by listening to events emitted from the readdirp stream and how to pipe the data stream into +another destination stream. + +## grep + +[grep.js](https://github.com/thlorenz/readdirp/blob/master/examples/grep.js) + +Very naive implementation of grep, for demonstration purposes only. + +## using callback api + +[callback-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/callback-api.js) + +Shows how to pass callbacks in order to handle errors and/or data. + +## tests + +The [readdirp tests](https://github.com/thlorenz/readdirp/blob/master/test/readdirp.js) also will give you a good idea on +how things work. + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/Readme.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/Readme.md new file mode 100644 index 000000000..55fc4611b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/Readme.md @@ -0,0 +1,37 @@ +# readdirp examples + +## How to run the examples + +Assuming you installed readdirp (`npm install readdirp`), you can do the following: + +1. `npm explore readdirp` +2. `cd examples` +3. `npm install` + +At that point you can run the examples with node, i.e., `node grep`. + +## stream api + +[stream-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api.js) + +Demonstrates error and data handling by listening to events emitted from the readdirp stream. + +## stream api pipe + +[stream-api-pipe.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api-pipe.js) + +Demonstrates error handling by listening to events emitted from the readdirp stream and how to pipe the data stream into +another destination stream. + +## grep + +[grep.js](https://github.com/thlorenz/readdirp/blob/master/examples/grep.js) + +Very naive implementation of grep, for demonstration purposes only. + +## using callback api + +[callback-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/callback-api.js) + +Shows how to pass callbacks in order to handle errors and/or data. + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/callback-api.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/callback-api.js new file mode 100644 index 000000000..39bd2d798 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/callback-api.js @@ -0,0 +1,10 @@ +var readdirp = require('..'); + +readdirp({ root: '.', fileFilter: '*.js' }, function (errors, res) { + if (errors) { + errors.forEach(function (err) { + console.error('Error: ', err); + }); + } + console.log('all javascript files', res); +}); diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/grep.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/grep.js new file mode 100644 index 000000000..807fa3554 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/grep.js @@ -0,0 +1,73 @@ +'use strict'; +var readdirp = require('..') + , util = require('util') + , fs = require('fs') + , path = require('path') + , Stream = require('stream') + , tap = require('tap-stream') + , es = require('event-stream') + ; + +function findLinesMatching (searchTerm) { + + return es.through(function (entry) { + var lineno = 0 + , matchingLines = [] + , fileStream = this; + + function filter () { + return es.mapSync(function (line) { + lineno++; + return ~line.indexOf(searchTerm) ? lineno + ': ' + line : undefined; + }); + } + + function aggregate () { + return es.through( + function write (data) { + matchingLines.push(data); + } + , function end () { + + // drop files that had no matches + if (matchingLines.length) { + var result = { file: entry, lines: matchingLines }; + + // pass result on to file stream + fileStream.emit('data', result); + } + this.emit('end'); + } + ); + } + + fs.createReadStream(entry.fullPath, { encoding: 'utf-8' }) + + // handle file contents line by line + .pipe(es.split('\n')) + + // keep only the lines that matched the term + .pipe(filter()) + + // aggregate all matching lines and delegate control back to the file stream + .pipe(aggregate()) + ; + }); +} + +console.log('grepping for "arguments"'); + +// create a stream of all javascript files found in this and all sub directories +readdirp({ root: path.join(__dirname), fileFilter: '*.js' }) + + // find all lines matching the term for each file (if none found, that file is ignored) + .pipe(findLinesMatching('arguments')) + + // format the results and output + .pipe( + es.mapSync(function (res) { + return '\n\n' + res.file.path + '\n\t' + res.lines.join('\n\t'); + }) + ) + .pipe(process.stdout) + ; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.npmignore new file mode 100644 index 000000000..13abef4f5 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.npmignore @@ -0,0 +1,3 @@ +node_modules +node_modules/* +npm_debug.log diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/LICENCE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/LICENCE new file mode 100644 index 000000000..171dd9700 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/LICENCE @@ -0,0 +1,22 @@ +Copyright (c) 2011 Dominic Tarr + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/examples/pretty.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/examples/pretty.js new file mode 100644 index 000000000..af043401c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/examples/pretty.js @@ -0,0 +1,25 @@ + +var inspect = require('util').inspect + +if(!module.parent) { + var es = require('..') //load event-stream + es.pipe( //pipe joins streams together + process.openStdin(), //open stdin + es.split(), //split stream to break on newlines + es.map(function (data, callback) {//turn this async function into a stream + var j + try { + j = JSON.parse(data) //try to parse input into json + } catch (err) { + return callback(null, data) //if it fails just pass it anyway + } + callback(null, inspect(j)) //render it nicely + }), + process.stdout // pipe it to stdout ! + ) + } + +// run this +// +// curl -sS registry.npmjs.org/event-stream | node pretty.js +// diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/index.js new file mode 100644 index 000000000..16846a26a --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/index.js @@ -0,0 +1,341 @@ +//filter will reemit the data if cb(err,pass) pass is truthy + +// reduce is more tricky +// maybe we want to group the reductions or emit progress updates occasionally +// the most basic reduce just emits one 'data' event after it has recieved 'end' + +var Stream = require('stream').Stream + , es = exports + , through = require('through') + , from = require('from') + , duplex = require('duplexer') + , map = require('map-stream') + , pause = require('pause-stream') + , split = require('split') + +es.Stream = Stream //re-export Stream from core +es.through = through +es.from = from +es.duplex = duplex +es.map = map +es.pause = pause +es.split = split + +// merge / concat +// +// combine multiple streams into a single stream. +// will emit end only once + +es.concat = //actually this should be called concat +es.merge = function (/*streams...*/) { + var toMerge = [].slice.call(arguments) + var stream = new Stream() + var endCount = 0 + stream.writable = stream.readable = true + + toMerge.forEach(function (e) { + e.pipe(stream, {end: false}) + var ended = false + e.on('end', function () { + if(ended) return + ended = true + endCount ++ + if(endCount == toMerge.length) + stream.emit('end') + }) + }) + stream.write = function (data) { + this.emit('data', data) + } + stream.destroy = function () { + merge.forEach(function (e) { + if(e.destroy) e.destroy() + }) + } + return stream +} + + +// writable stream, collects all events into an array +// and calls back when 'end' occurs +// mainly I'm using this to test the other functions + +es.writeArray = function (done) { + if ('function' !== typeof done) + throw new Error('function writeArray (done): done must be function') + + var a = new Stream () + , array = [], isDone = false + a.write = function (l) { + array.push(l) + } + a.end = function () { + isDone = true + done(null, array) + } + a.writable = true + a.readable = false + a.destroy = function () { + a.writable = a.readable = false + if(isDone) return + done(new Error('destroyed before end'), array) + } + return a +} + +//return a Stream that reads the properties of an object +//respecting pause() and resume() + +es.readArray = function (array) { + var stream = new Stream() + , i = 0 + , paused = false + , ended = false + + stream.readable = true + stream.writable = false + + if(!Array.isArray(array)) + throw new Error('event-stream.read expects an array') + + stream.resume = function () { + if(ended) return + paused = false + var l = array.length + while(i < l && !paused && !ended) { + stream.emit('data', array[i++]) + } + if(i == l && !ended) + ended = true, stream.readable = false, stream.emit('end') + } + process.nextTick(stream.resume) + stream.pause = function () { + paused = true + } + stream.destroy = function () { + ended = true + stream.emit('close') + } + return stream +} + +// +// readable (asyncFunction) +// return a stream that calls an async function while the stream is not paused. +// +// the function must take: (count, callback) {... +// + +es.readable = function (func, continueOnError) { + var stream = new Stream() + , i = 0 + , paused = false + , ended = false + , reading = false + + stream.readable = true + stream.writable = false + + if('function' !== typeof func) + throw new Error('event-stream.readable expects async function') + + stream.on('end', function () { ended = true }) + + function get (err, data) { + + if(err) { + stream.emit('error', err) + if(!continueOnError) stream.emit('end') + } else if (arguments.length > 1) + stream.emit('data', data) + + process.nextTick(function () { + if(ended || paused || reading) return + try { + reading = true + func.call(stream, i++, function () { + reading = false + get.apply(null, arguments) + }) + } catch (err) { + stream.emit('error', err) + } + }) + } + stream.resume = function () { + paused = false + get() + } + process.nextTick(get) + stream.pause = function () { + paused = true + } + stream.destroy = function () { + stream.emit('end') + stream.emit('close') + ended = true + } + return stream +} + + + +// +// map sync +// + +es.mapSync = function (sync) { + return es.through(function write(data) { + var mappedData = sync(data) + if (typeof mappedData !== 'undefined') + this.emit('data', mappedData) + }) +} + +// +// log just print out what is coming through the stream, for debugging +// + +es.log = function (name) { + return es.through(function (data) { + var args = [].slice.call(arguments) + if(name) console.error(name, data) + else console.error(data) + this.emit('data', data) + }) +} + +// +// combine multiple streams together so that they act as a single stream +// +es.pipeline = +es.pipe = es.connect = function () { + + var streams = [].slice.call(arguments) + , first = streams[0] + , last = streams[streams.length - 1] + , thepipe = es.duplex(first, last) + + if(streams.length == 1) + return streams[0] + else if (!streams.length) + throw new Error('connect called with empty args') + + //pipe all the streams together + + function recurse (streams) { + if(streams.length < 2) + return + streams[0].pipe(streams[1]) + recurse(streams.slice(1)) + } + + recurse(streams) + + function onerror () { + var args = [].slice.call(arguments) + args.unshift('error') + thepipe.emit.apply(thepipe, args) + } + + //es.duplex already reemits the error from the first and last stream. + //add a listener for the inner streams in the pipeline. + for(var i = 1; i < streams.length - 1; i ++) + streams[i].on('error', onerror) + + return thepipe +} + +// +// child -- pipe through a child process +// + +es.child = function (child) { + + return es.duplex(child.stdin, child.stdout) + +} + +// +// parse +// +// must be used after es.split() to ensure that each chunk represents a line +// source.pipe(es.split()).pipe(es.parse()) + +es.parse = function () { + return es.through(function (data) { + var obj + try { + if(data) //ignore empty lines + obj = JSON.parse(data.toString()) + } catch (err) { + return console.error(err, 'attemping to parse:', data) + } + //ignore lines that where only whitespace. + if(obj !== undefined) + this.emit('data', obj) + }) +} +// +// stringify +// + +es.stringify = function () { + var Buffer = require('buffer').Buffer + return es.mapSync(function (e){ + return JSON.stringify(Buffer.isBuffer(e) ? e.toString() : e) + '\n' + }) +} + +// +// replace a string within a stream. +// +// warn: just concatenates the string and then does str.split().join(). +// probably not optimal. +// for smallish responses, who cares? +// I need this for shadow-npm so it's only relatively small json files. + +es.replace = function (from, to) { + return es.pipeline(es.split(from), es.join(to)) +} + +// +// join chunks with a joiner. just like Array#join +// also accepts a callback that is passed the chunks appended together +// this is still supported for legacy reasons. +// + +es.join = function (str) { + + //legacy api + if('function' === typeof str) + return es.wait(str) + + var first = true + return es.through(function (data) { + if(!first) + this.emit('data', str) + first = false + this.emit('data', data) + return true + }) +} + + +// +// wait. callback when 'end' is emitted, with all chunks appended as string. +// + +es.wait = function (callback) { + var body = '' + return es.through(function (data) { body += data }, + function () { + this.emit('data', body) + this.emit('end') + if(callback) callback(null, body) + }) +} + +es.pipeable = function () { + throw new Error('[EVENT-STREAM] es.pipeable is deprecated') +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.npmignore new file mode 100644 index 000000000..062c11e80 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.npmignore @@ -0,0 +1,3 @@ +node_modules +*.log +*.err \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.travis.yml new file mode 100644 index 000000000..c2ba3f90b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.8 \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/LICENCE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/LICENCE new file mode 100644 index 000000000..a23e08a85 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Raynos. + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/Makefile b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/Makefile new file mode 100644 index 000000000..1f8985d0a --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/Makefile @@ -0,0 +1,4 @@ +test: + node test.js + +.PHONY: test \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/README.md new file mode 100644 index 000000000..a24cecb3b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/README.md @@ -0,0 +1,36 @@ +# duplexer [![build status][1]][2] + +Creates a duplex stream + +Taken from [event-stream][3] + +## duplex (writeStream, readStream) + +Takes a writable stream and a readable stream and makes them appear as a readable writable stream. + +It is assumed that the two streams are connected to each other in some way. + +## Example + + var grep = cp.exec('grep Stream') + + duplex(grep.stdin, grep.stdout) + +## Installation + +`npm install duplexer` + +## Tests + +`make test` + +## Contributors + + - Dominictarr + - Raynos + +## MIT Licenced + + [1]: https://secure.travis-ci.org/Raynos/duplexer.png + [2]: http://travis-ci.org/Raynos/duplexer + [3]: https://github.com/dominictarr/event-stream#duplex-writestream-readstream \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/index.js new file mode 100644 index 000000000..fee581db4 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/index.js @@ -0,0 +1,87 @@ +var Stream = require("stream") + , writeMethods = ["write", "end", "destroy"] + , readMethods = ["resume", "pause"] + , readEvents = ["data", "close"] + , slice = Array.prototype.slice + +module.exports = duplex + +function duplex(writer, reader) { + var stream = new Stream() + , ended = false + + Object.defineProperties(stream, { + writable: { + get: getWritable + } + , readable: { + get: getReadable + } + }) + + writeMethods.forEach(proxyWriter) + + readMethods.forEach(proxyReader) + + readEvents.forEach(proxyStream) + + reader.on("end", handleEnd) + + writer.on("error", reemit) + reader.on("error", reemit) + + return stream + + function getWritable() { + return writer.writable + } + + function getReadable() { + return reader.readable + } + + function proxyWriter(methodName) { + stream[methodName] = method + + function method() { + return writer[methodName].apply(writer, arguments) + } + } + + function proxyReader(methodName) { + stream[methodName] = method + + function method() { + stream.emit(methodName) + var func = reader[methodName] + if (func) { + return func.apply(reader, arguments) + } + reader.emit(methodName) + } + } + + function proxyStream(methodName) { + reader.on(methodName, reemit) + + function reemit() { + var args = slice.call(arguments) + args.unshift(methodName) + stream.emit.apply(stream, args) + } + } + + function handleEnd() { + if (ended) { + return + } + ended = true + var args = slice.call(arguments) + args.unshift("end") + stream.emit.apply(stream, args) + } + + function reemit(err) { + stream.emit("error", err) + } +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/package.json new file mode 100644 index 000000000..6f54329f6 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/package.json @@ -0,0 +1,41 @@ +{ + "name": "duplexer", + "version": "0.0.2", + "description": "Creates a duplex stream", + "keywords": [], + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Raynos/duplexer.git" + }, + "main": "index", + "homepage": "https://github.com/Raynos/duplexer", + "contributors": [ + { + "name": "Jake Verbaten" + } + ], + "bugs": { + "url": "https://github.com/Raynos/duplexer/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": {}, + "devDependencies": { + "through": "~0.1.4" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/Raynos/duplexer/raw/master/LICENSE" + } + ], + "scripts": { + "test": "make test" + }, + "readme": "# duplexer [![build status][1]][2]\n\nCreates a duplex stream\n\nTaken from [event-stream][3]\n\n## duplex (writeStream, readStream)\n\nTakes a writable stream and a readable stream and makes them appear as a readable writable stream.\n\nIt is assumed that the two streams are connected to each other in some way.\n\n## Example\n\n var grep = cp.exec('grep Stream')\n\n duplex(grep.stdin, grep.stdout)\n\n## Installation\n\n`npm install duplexer`\n\n## Tests\n\n`make test`\n\n## Contributors\n\n - Dominictarr\n - Raynos\n\n## MIT Licenced\n\n [1]: https://secure.travis-ci.org/Raynos/duplexer.png\n [2]: http://travis-ci.org/Raynos/duplexer\n [3]: https://github.com/dominictarr/event-stream#duplex-writestream-readstream", + "_id": "duplexer@0.0.2", + "_from": "duplexer@~0.0.2" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/test.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/test.js new file mode 100644 index 000000000..e06a864b8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/duplexer/test.js @@ -0,0 +1,27 @@ +var duplex = require("./index") + , assert = require("assert") + , through = require("through") + +var readable = through() + , writable = through(write) + , written = 0 + , data = 0 + +var stream = duplex(writable, readable) + +function write() { + written++ +} + +stream.on("data", ondata) + +function ondata() { + data++ +} + +stream.write() +readable.emit("data") + +assert.equal(written, 1) +assert.equal(data, 1) +console.log("DONE") \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.APACHE2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.APACHE2 new file mode 100644 index 000000000..6366c0471 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.MIT b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.MIT new file mode 100644 index 000000000..6eafbd734 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/index.js new file mode 100644 index 000000000..95a897522 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/index.js @@ -0,0 +1,62 @@ + +var Stream = require('stream') + +// from +// +// a stream that reads from an source. +// source may be an array, or a function. +// from handles pause behaviour for you. + +module.exports = +function from (source) { + if(Array.isArray(source)) + return from (function (i) { + if(source.length) + this.emit('data', source.shift()) + else + this.emit('end') + return true + }) + + var s = new Stream(), i = 0, ended = false, started = false + s.readable = true + s.writable = false + s.paused = false + s.pause = function () { + started = true + s.paused = true + } + function next () { + var n = 0, r = false + if(ended) return + while(!ended && !s.paused && source.call(s, i++, function () { + if(!n++ && !s.ended && !s.paused) + next() + })) + ; + } + s.resume = function () { + started = true + s.paused = false + next() + } + s.on('end', function () { + ended = true + s.readable = false + process.nextTick(s.destroy) + }) + s.destroy = function () { + ended = true + s.emit('close') + } + /* + by default, the stream will start emitting at nextTick + if you want, you can pause it, after pipeing. + you can also resume before next tick, and that will also + work. + */ + process.nextTick(function () { + if(!started) s.resume() + }) + return s +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/package.json new file mode 100644 index 000000000..be3c0dfa2 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/package.json @@ -0,0 +1,33 @@ +{ + "name": "from", + "version": "0.0.2", + "description": "Easy way to make a Readable Stream", + "main": "index.js", + "scripts": { + "test": "asynct test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/from.git" + }, + "keywords": [ + "stream", + "streams", + "readable", + "easy" + ], + "devDependencies": { + "asynct": "1", + "stream-spec": "0", + "assertions": "~2.3.0" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": "MIT", + "readme": "# from\n\nAn easy way to create a `readable Stream`.\n\n## License\nMIT / Apache2\n", + "_id": "from@0.0.2", + "_from": "from@~0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/readme.markdown new file mode 100644 index 000000000..84c826944 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/readme.markdown @@ -0,0 +1,6 @@ +# from + +An easy way to create a `readable Stream`. + +## License +MIT / Apache2 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/test/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/test/index.js new file mode 100644 index 000000000..fafea5765 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/from/test/index.js @@ -0,0 +1,141 @@ +var from = require('..') +var spec = require('stream-spec') +var a = require('assertions') + +function read(stream, callback) { + var actual = [] + stream.on('data', function (data) { + actual.push(data) + }) + stream.once('end', function () { + callback(null, actual) + }) + stream.once('error', function (err) { + callback(err) + }) +} + +function pause(stream) { + stream.on('data', function () { + if(Math.random() > 0.1) return + stream.pause() + process.nextTick(function () { + stream.resume() + }) + }) +} + +exports['inc'] = function (test) { + + var fs = from(function (i) { + this.emit('data', i) + if(i >= 99) + return this.emit('end') + return true + }) + + spec(fs).readable().validateOnExit() + + read(fs, function (err, arr) { + test.equal(arr.length, 100) + test.done() + }) +} + +exports['simple'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = from(expected.slice()) + + spec(t) + .readable() + .pausable({strict: true}) + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + +} + +exports['simple pausable'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = from(expected.slice()) + + spec(t) + .readable() + .pausable({strict: true}) + .validateOnExit() + + pause(t) + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + +} + +exports['simple (not strictly pausable) setTimeout'] = function (test) { + + var l = 10 + , expected = [] + while(l--) expected.push(l * Math.random()) + + + var _expected = expected.slice() + var t = from(function (i, n) { + var self = this + setTimeout(function () { + if(_expected.length) + self.emit('data', _expected.shift()) + else + self.emit('end') + n() + }, 3) + }) + + /* + using from in this way will not be strictly pausable. + it could be extended to buffer outputs, but I think a better + way would be to use a PauseStream that implements strict pause. + */ + + spec(t) + .readable() + .pausable({strict: false }) + .validateOnExit() + + //pause(t) + var paused = false + var i = setInterval(function () { + if(!paused) t.pause() + else t.resume() + paused = !paused + }, 2) + + t.on('end', function () { + clearInterval(i) + }) + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + +} + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.npmignore new file mode 100644 index 000000000..13abef4f5 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.npmignore @@ -0,0 +1,3 @@ +node_modules +node_modules/* +npm_debug.log diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/LICENCE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/LICENCE new file mode 100644 index 000000000..171dd9700 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/LICENCE @@ -0,0 +1,22 @@ +Copyright (c) 2011 Dominic Tarr + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/examples/pretty.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/examples/pretty.js new file mode 100644 index 000000000..af043401c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/examples/pretty.js @@ -0,0 +1,25 @@ + +var inspect = require('util').inspect + +if(!module.parent) { + var es = require('..') //load event-stream + es.pipe( //pipe joins streams together + process.openStdin(), //open stdin + es.split(), //split stream to break on newlines + es.map(function (data, callback) {//turn this async function into a stream + var j + try { + j = JSON.parse(data) //try to parse input into json + } catch (err) { + return callback(null, data) //if it fails just pass it anyway + } + callback(null, inspect(j)) //render it nicely + }), + process.stdout // pipe it to stdout ! + ) + } + +// run this +// +// curl -sS registry.npmjs.org/event-stream | node pretty.js +// diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/index.js new file mode 100644 index 000000000..d3a7fd911 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/index.js @@ -0,0 +1,105 @@ +//filter will reemit the data if cb(err,pass) pass is truthy + +// reduce is more tricky +// maybe we want to group the reductions or emit progress updates occasionally +// the most basic reduce just emits one 'data' event after it has recieved 'end' + + +var Stream = require('stream').Stream + + +//create an event stream and apply function to each .write +//emitting each response as data +//unless it's an empty callback + +module.exports = function (mapper) { + var stream = new Stream() + , inputs = 0 + , outputs = 0 + , ended = false + , paused = false + , destroyed = false + + stream.writable = true + stream.readable = true + + stream.write = function () { + if(ended) throw new Error('map stream is not writable') + inputs ++ + var args = [].slice.call(arguments) + , r + , inNext = false + //pipe only allows one argument. so, do not + function next (err) { + if(destroyed) return + inNext = true + outputs ++ + var args = [].slice.call(arguments) + if(err) { + args.unshift('error') + return inNext = false, stream.emit.apply(stream, args) + } + args.shift() //drop err + if (args.length) { + args.unshift('data') + r = stream.emit.apply(stream, args) + } + if(inputs == outputs) { + if(paused) paused = false, stream.emit('drain') //written all the incoming events + if(ended) end() + } + inNext = false + } + args.push(next) + + try { + //catch sync errors and handle them like async errors + var written = mapper.apply(null, args) + paused = (written === false) + return !paused + } catch (err) { + //if the callback has been called syncronously, and the error + //has occured in an listener, throw it again. + if(inNext) + throw err + next(err) + return !paused + } + } + + function end (data) { + //if end was called with args, write it, + ended = true //write will emit 'end' if ended is true + stream.writable = false + if(data !== undefined) + return stream.write(data) + else if (inputs == outputs) //wait for processing + stream.readable = false, stream.emit('end'), stream.destroy() + } + + stream.end = function (data) { + if(ended) return + end() + } + + stream.destroy = function () { + ended = destroyed = true + stream.writable = stream.readable = paused = false + process.nextTick(function () { + stream.emit('close') + }) + } + stream.pause = function () { + paused = true + } + + stream.resume = function () { + paused = false + } + + return stream +} + + + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/package.json new file mode 100644 index 000000000..97e733895 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/package.json @@ -0,0 +1,30 @@ +{ + "name": "map-stream", + "version": "0.0.1", + "description": "construct pipes of streams of events", + "homepage": "http://github.com/dominictarr/map-stream", + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/map-stream.git" + }, + "dependencies": {}, + "devDependencies": { + "asynct": "*", + "it-is": "1", + "ubelt": "~2.9", + "stream-spec": "~0.2", + "event-stream": "~2.1", + "from": "0.0.2" + }, + "scripts": { + "test": "asynct test/" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "http://dominictarr.com" + }, + "readme": "# MapStream\n\nRefactored out of [event-stream](https://github.com/dominictarr/event-stream)\n\n##map (asyncFunction)\n\nCreate a through stream from an asyncronous function. \n\n``` js\nvar es = require('event-stream')\n\nes.map(function (data, callback) {\n //transform data\n // ...\n callback(null, data)\n})\n\n```\n\nEach map MUST call the callback. It may callback with data, with an error or with no arguments, \n\n * `callback()` drop this data. \n this makes the map work like `filter`, \n note:`callback(null,null)` is not the same, and will emit `null`\n\n * `callback(null, newData)` turn data into newData\n \n * `callback(error)` emit an error for this item.\n\n>Note: if a callback is not called, `map` will think that it is still being processed, \n>every call must be answered or the stream will not know when to end. \n>\n>Also, if the callback is called more than once, every call but the first will be ignored.\n\n\n", + "_id": "map-stream@0.0.1", + "_from": "map-stream@0.0.1" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/readme.markdown new file mode 100644 index 000000000..22c019de8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/readme.markdown @@ -0,0 +1,35 @@ +# MapStream + +Refactored out of [event-stream](https://github.com/dominictarr/event-stream) + +##map (asyncFunction) + +Create a through stream from an asyncronous function. + +``` js +var es = require('event-stream') + +es.map(function (data, callback) { + //transform data + // ... + callback(null, data) +}) + +``` + +Each map MUST call the callback. It may callback with data, with an error or with no arguments, + + * `callback()` drop this data. + this makes the map work like `filter`, + note:`callback(null,null)` is not the same, and will emit `null` + + * `callback(null, newData)` turn data into newData + + * `callback(error)` emit an error for this item. + +>Note: if a callback is not called, `map` will think that it is still being processed, +>every call must be answered or the stream will not know when to end. +> +>Also, if the callback is called more than once, every call but the first will be ignored. + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/test/simple-map.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/test/simple-map.asynct.js new file mode 100644 index 000000000..77ac48ef1 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/map-stream/test/simple-map.asynct.js @@ -0,0 +1,295 @@ +'use strict'; + +var map = require('../') + , it = require('it-is') + , u = require('ubelt') + , spec = require('stream-spec') + , from = require('from') + , Stream = require('stream') + , es = require('event-stream') + +//REFACTOR THIS TEST TO USE es.readArray and es.writeArray + +function writeArray(array, stream) { + + array.forEach( function (j) { + stream.write(j) + }) + stream.end() + +} + +function readStream(stream, done) { + + var array = [] + stream.on('data', function (data) { + array.push(data) + }) + stream.on('error', done) + stream.on('end', function (data) { + done(null, array) + }) + +} + +//call sink on each write, +//and complete when finished. + +function pauseStream (prob, delay) { + var pauseIf = ( + 'number' == typeof prob + ? function () { + return Math.random() < prob + } + : 'function' == typeof prob + ? prob + : 0.1 + ) + var delayer = ( + !delay + ? process.nextTick + : 'number' == typeof delay + ? function (next) { setTimeout(next, delay) } + : delay + ) + + return es.through(function (data) { + if(!this.paused && pauseIf()) { + console.log('PAUSE STREAM PAUSING') + this.pause() + var self = this + delayer(function () { + console.log('PAUSE STREAM RESUMING') + self.resume() + }) + } + console.log("emit ('data', " + data + ')') + this.emit('data', data) + }) +} + +exports ['simple map'] = function (test) { + + var input = u.map(1, 1000, function () { + return Math.random() + }) + var expected = input.map(function (v) { + return v * 2 + }) + + var pause = pauseStream(0.1) + var fs = from(input) + var ts = es.writeArray(function (err, ar) { + it(ar).deepEqual(expected) + test.done() + }) + var map = es.through(function (data) { + this.emit('data', data * 2) + }) + + spec(map).through().validateOnExit() + spec(pause).through().validateOnExit() + + fs.pipe(map).pipe(pause).pipe(ts) +} + +exports ['simple map applied to a stream'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + //create event stream from + + var doubler = map(function (data, cb) { + cb(null, data * 2) + }) + + spec(doubler).through().validateOnExit() + + //a map is only a middle man, so it is both readable and writable + + it(doubler).has({ + readable: true, + writable: true, + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.map(function (j) { + return j * 2 + })) +// process.nextTick(x.validate) + test.done() + }) + + writeArray(input, doubler) + +} + +exports['pipe two maps together'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + //create event stream from + function dd (data, cb) { + cb(null, data * 2) + } + var doubler1 = es.map(dd), doubler2 = es.map(dd) + + doubler1.pipe(doubler2) + + spec(doubler1).through().validateOnExit() + spec(doubler2).through().validateOnExit() + + readStream(doubler2, function (err, output) { + it(output).deepEqual(input.map(function (j) { + return j * 4 + })) + test.done() + }) + + writeArray(input, doubler1) + +} + +//next: +// +// test pause, resume and drian. +// + +// then make a pipe joiner: +// +// plumber (evStr1, evStr2, evStr3, evStr4, evStr5) +// +// will return a single stream that write goes to the first + +exports ['map will not call end until the callback'] = function (test) { + + var ticker = map(function (data, cb) { + process.nextTick(function () { + cb(null, data * 2) + }) + }) + + spec(ticker).through().validateOnExit() + + ticker.write('x') + ticker.end() + + ticker.on('end', function () { + test.done() + }) +} + + +exports ['emit error thrown'] = function (test) { + + var err = new Error('INTENSIONAL ERROR') + , mapper = + es.map(function () { + throw err + }) + + mapper.on('error', function (_err) { + it(_err).equal(err) + test.done() + }) + + mapper.write('hello') + +} + +exports ['emit error calledback'] = function (test) { + + var err = new Error('INTENSIONAL ERROR') + , mapper = + es.map(function (data, callback) { + callback(err) + }) + + mapper.on('error', function (_err) { + it(_err).equal(err) + test.done() + }) + + mapper.write('hello') + +} + +exports ['do not emit drain if not paused'] = function (test) { + + var maps = map(function (data, callback) { + u.delay(callback)(null, 1) + return true + }) + + spec(maps).through().pausable().validateOnExit() + + maps.on('drain', function () { + it(false).ok('should not emit drain unless the stream is paused') + }) + + it(maps.write('hello')).equal(true) + it(maps.write('hello')).equal(true) + it(maps.write('hello')).equal(true) + setTimeout(function () {maps.end()},10) + maps.on('end', test.done) +} + +exports ['emits drain if paused, when all '] = function (test) { + var active = 0 + var drained = false + var maps = map(function (data, callback) { + active ++ + u.delay(function () { + active -- + callback(null, 1) + })() + console.log('WRITE', false) + return false + }) + + spec(maps).through().validateOnExit() + + maps.on('drain', function () { + drained = true + it(active).equal(0, 'should emit drain when all maps are done') + }) + + it(maps.write('hello')).equal(false) + it(maps.write('hello')).equal(false) + it(maps.write('hello')).equal(false) + + process.nextTick(function () {maps.end()},10) + + maps.on('end', function () { + console.log('end') + it(drained).ok('shoud have emitted drain before end') + test.done() + }) + +} + +exports ['map applied to a stream with filtering'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + + var doubler = map(function (data, callback) { + if (data % 2) + callback(null, data * 2) + else + callback() + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.filter(function (j) { + return j % 2 + }).map(function (j) { + return j * 2 + })) + test.done() + }) + + spec(doubler).through().validateOnExit() + + writeArray(input, doubler) + +} + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/.npmignore new file mode 100644 index 000000000..bfdb82cf0 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/.npmignore @@ -0,0 +1,4 @@ +lib-cov/* +*.swp +*.swo +node_modules diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/LICENSE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/README.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/README.markdown new file mode 100644 index 000000000..deb493c0b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/README.markdown @@ -0,0 +1,474 @@ +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). + +examples +======== + +With Optimist, the options are just a hash! No optstrings attached. +------------------------------------------------------------------- + +xup.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; + +if (argv.rif - 5 * argv.xup > 7.138) { + console.log('Buy more riffiwobbles'); +} +else { + console.log('Sell the xupptumblers'); +} +```` + +*** + + $ ./xup.js --rif=55 --xup=9.52 + Buy more riffiwobbles + + $ ./xup.js --rif 12 --xup 8.1 + Sell the xupptumblers + +![This one's optimistic.](http://substack.net/images/optimistic.png) + +But wait! There's more! You can do short options: +------------------------------------------------- + +short.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; +console.log('(%d,%d)', argv.x, argv.y); +```` + +*** + + $ ./short.js -x 10 -y 21 + (10,21) + +And booleans, both long and short (and grouped): +---------------------------------- + +bool.js: + +````javascript +#!/usr/bin/env node +var util = require('util'); +var argv = require('optimist').argv; + +if (argv.s) { + util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); +} +console.log( + (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') +); +```` + +*** + + $ ./bool.js -s + The cat says: meow + + $ ./bool.js -sp + The cat says: meow. + + $ ./bool.js -sp --fr + Le chat dit: miaou. + +And non-hypenated options too! Just use `argv._`! +------------------------------------------------- + +nonopt.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; +console.log('(%d,%d)', argv.x, argv.y); +console.log(argv._); +```` + +*** + + $ ./nonopt.js -x 6.82 -y 3.35 moo + (6.82,3.35) + [ 'moo' ] + + $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz + (0.54,1.12) + [ 'foo', 'bar', 'baz' ] + +Plus, Optimist comes with .usage() and .demand()! +------------------------------------------------- + +divide.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .usage('Usage: $0 -x [num] -y [num]') + .demand(['x','y']) + .argv; + +console.log(argv.x / argv.y); +```` + +*** + + $ ./divide.js -x 55 -y 11 + 5 + + $ node ./divide.js -x 4.91 -z 2.51 + Usage: node ./divide.js -x [num] -y [num] + + Options: + -x [required] + -y [required] + + Missing required arguments: y + +EVEN MORE HOLY COW +------------------ + +default_singles.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .default('x', 10) + .default('y', 10) + .argv +; +console.log(argv.x + argv.y); +```` + +*** + + $ ./default_singles.js -x 5 + 15 + +default_hash.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .default({ x : 10, y : 10 }) + .argv +; +console.log(argv.x + argv.y); +```` + +*** + + $ ./default_hash.js -y 7 + 17 + +And if you really want to get all descriptive about it... +--------------------------------------------------------- + +boolean_single.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .boolean('v') + .argv +; +console.dir(argv); +```` + +*** + + $ ./boolean_single.js -v foo bar baz + true + [ 'bar', 'baz', 'foo' ] + +boolean_double.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .boolean(['x','y','z']) + .argv +; +console.dir([ argv.x, argv.y, argv.z ]); +console.dir(argv._); +```` + +*** + + $ ./boolean_double.js -x -z one two three + [ true, false, true ] + [ 'one', 'two', 'three' ] + +Optimist is here to help... +--------------------------- + +You can describe parameters for help messages and set aliases. Optimist figures +out how to format a handy help string automatically. + +line_count.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .usage('Count the lines in a file.\nUsage: $0') + .demand('f') + .alias('f', 'file') + .describe('f', 'Load a file') + .argv +; + +var fs = require('fs'); +var s = fs.createReadStream(argv.file); + +var lines = 0; +s.on('data', function (buf) { + lines += buf.toString().match(/\n/g).length; +}); + +s.on('end', function () { + console.log(lines); +}); +```` + +*** + + $ node line_count.js + Count the lines in a file. + Usage: node ./line_count.js + + Options: + -f, --file Load a file [required] + + Missing required arguments: f + + $ node line_count.js --file line_count.js + 20 + + $ node line_count.js -f line_count.js + 20 + +methods +======= + +By itself, + +````javascript +require('optimist').argv +````` + +will use `process.argv` array to construct the `argv` object. + +You can pass in the `process.argv` yourself: + +````javascript +require('optimist')([ '-x', '1', '-y', '2' ]).argv +```` + +or use .parse() to do the same thing: + +````javascript +require('optimist').parse([ '-x', '1', '-y', '2' ]) +```` + +The rest of these methods below come in just before the terminating `.argv`. + +.alias(key, alias) +------------------ + +Set key names as equivalent such that updates to a key will propagate to aliases +and vice-versa. + +Optionally `.alias()` can take an object that maps keys to aliases. + +.default(key, value) +-------------------- + +Set `argv[key]` to `value` if no option was specified on `process.argv`. + +Optionally `.default()` can take an object that maps keys to default values. + +.demand(key) +------------ + +If `key` is a string, show the usage information and exit if `key` wasn't +specified in `process.argv`. + +If `key` is a number, demand at least as many non-option arguments, which show +up in `argv._`. + +If `key` is an Array, demand each element. + +.describe(key, desc) +-------------------- + +Describe a `key` for the generated usage information. + +Optionally `.describe()` can take an object that maps keys to descriptions. + +.options(key, opt) +------------------ + +Instead of chaining together `.alias().demand().default()`, you can specify +keys in `opt` for each of the chainable methods. + +For example: + +````javascript +var argv = require('optimist') + .options('f', { + alias : 'file', + default : '/etc/passwd', + }) + .argv +; +```` + +is the same as + +````javascript +var argv = require('optimist') + .alias('f', 'file') + .default('f', '/etc/passwd') + .argv +; +```` + +Optionally `.options()` can take an object that maps keys to `opt` parameters. + +.usage(message) +--------------- + +Set a usage message to show which commands to use. Inside `message`, the string +`$0` will get interpolated to the current script name or node command for the +present script similar to how `$0` works in bash or perl. + +.check(fn) +---------- + +Check that certain conditions are met in the provided arguments. + +If `fn` throws or returns `false`, show the thrown error, usage information, and +exit. + +.boolean(key) +------------- + +Interpret `key` as a boolean. If a non-flag option follows `key` in +`process.argv`, that string won't get set as the value of `key`. + +If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be +`false`. + +If `key` is an Array, interpret all the elements as booleans. + +.string(key) +------------ + +Tell the parser logic not to interpret `key` as a number or boolean. +This can be useful if you need to preserve leading zeros in an input. + +If `key` is an Array, interpret all the elements as strings. + +.wrap(columns) +-------------- + +Format usage output to wrap at `columns` many columns. + +.help() +------- + +Return the generated usage string. + +.showHelp(fn=console.error) +--------------------------- + +Print the usage data using `fn` for printing. + +.parse(args) +------------ + +Parse `args` instead of `process.argv`. Returns the `argv` object. + +.argv +----- + +Get the arguments as a plain old object. + +Arguments without a corresponding flag show up in the `argv._` array. + +The script name or node command is available at `argv.$0` similarly to how `$0` +works in bash or perl. + +parsing tricks +============== + +stop parsing +------------ + +Use `--` to stop parsing flags and stuff the remainder into `argv._`. + + $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4 + { _: [ '-c', '3', '-d', '4' ], + '$0': 'node ./examples/reflect.js', + a: 1, + b: 2 } + +negate fields +------------- + +If you want to explicity set a field to false instead of just leaving it +undefined or to override a default you can do `--no-key`. + + $ node examples/reflect.js -a --no-b + { _: [], + '$0': 'node ./examples/reflect.js', + a: true, + b: false } + +numbers +------- + +Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to +one. This way you can just `net.createConnection(argv.port)` and you can add +numbers out of `argv` with `+` without having that mean concatenation, +which is super frustrating. + +duplicates +---------- + +If you specify a flag multiple times it will get turned into an array containing +all the values in order. + + $ node examples/reflect.js -x 5 -x 8 -x 0 + { _: [], + '$0': 'node ./examples/reflect.js', + x: [ 5, 8, 0 ] } + +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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/bool.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/bool.js new file mode 100644 index 000000000..a998fb7ab --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/boolean_double.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/boolean_double.js new file mode 100644 index 000000000..a35a7e6d3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/boolean_single.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/boolean_single.js new file mode 100644 index 000000000..017bb6893 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/default_hash.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/default_hash.js new file mode 100644 index 000000000..ade77681d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/default_singles.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/default_singles.js new file mode 100644 index 000000000..d9b1ff458 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/divide.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/divide.js new file mode 100644 index 000000000..5e2ee82ff --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count.js new file mode 100644 index 000000000..b5f95bf6d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count_options.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count_options.js new file mode 100644 index 000000000..d9ac70904 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count_wrap.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/line_count_wrap.js new file mode 100644 index 000000000..426751112 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/nonopt.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/nonopt.js new file mode 100644 index 000000000..ee633eedc --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/reflect.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/reflect.js new file mode 100644 index 000000000..816b3e111 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/reflect.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +console.dir(require('optimist').argv); diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/short.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/short.js new file mode 100644 index 000000000..1db0ad0f8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/string.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/string.js new file mode 100644 index 000000000..a8e5aeb23 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/usage-options.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/usage-options.js new file mode 100644 index 000000000..b99997767 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/xup.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/xup.js new file mode 100644 index 000000000..8f6ecd201 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/examples/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/index.js new file mode 100644 index 000000000..070d6423a --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/index.js @@ -0,0 +1,457 @@ +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 (opt.default) 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; + + if (key in argv && !flags.bools[key]) { + if (!Array.isArray(argv[key])) { + argv[key] = [ argv[key] ]; + } + argv[key].push(value); + } + else { + argv[key] = 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]) { + setArg(key, next); + i++; + } + else if (flags.bools[key] && /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]) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && flags.bools[key] && /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 (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; +}; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/.npmignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/README.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/README.markdown new file mode 100644 index 000000000..346374e0d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/example/center.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/example/center.js new file mode 100644 index 000000000..a3fbaae98 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/example/meat.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/example/meat.js new file mode 100644 index 000000000..a4665e105 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/index.js new file mode 100644 index 000000000..c9bc94521 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/package.json new file mode 100644 index 000000000..928d935f2 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/package.json @@ -0,0 +1,40 @@ +{ + "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" + }, + "readme": "wordwrap\n========\n\nWrap your words.\n\nexample\n=======\n\nmade out of meat\n----------------\n\nmeat.js\n\n var wrap = require('wordwrap')(15);\n console.log(wrap('You and your whole family are made out of meat.'));\n\noutput:\n\n You and your\n whole family\n are made out\n of meat.\n\ncentered\n--------\n\ncenter.js\n\n var wrap = require('wordwrap')(20, 60);\n console.log(wrap(\n 'At long last the struggle and tumult was over.'\n + ' The machines had finally cast off their oppressors'\n + ' and were finally free to roam the cosmos.'\n + '\\n'\n + 'Free of purpose, free of obligation.'\n + ' Just drifting through emptiness.'\n + ' The sun was just another point of light.'\n ));\n\noutput:\n\n At long last the struggle and tumult\n was over. The machines had finally cast\n off their oppressors and were finally\n free to roam the cosmos.\n Free of purpose, free of obligation.\n Just drifting through emptiness. The\n sun was just another point of light.\n\nmethods\n=======\n\nvar wrap = require('wordwrap');\n\nwrap(stop), wrap(start, stop, params={mode:\"soft\"})\n---------------------------------------------------\n\nReturns a function that takes a string and returns a new string.\n\nPad out lines with spaces out to column `start` and then wrap until column\n`stop`. If a word is longer than `stop - start` characters it will overflow.\n\nIn \"soft\" mode, split chunks by `/(\\S+\\s+/` and don't break up chunks which are\nlonger than `stop - start`, in \"hard\" mode, split chunks with `/\\b/` and break\nup chunks longer than `stop - start`.\n\nwrap.hard(start, stop)\n----------------------\n\nLike `wrap()` but with `params.mode = \"hard\"`.\n", + "_id": "wordwrap@0.0.2", + "_from": "wordwrap@>=0.0.1 <0.1.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/break.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/break.js new file mode 100644 index 000000000..749292ecc --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/idleness.txt b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/idleness.txt new file mode 100644 index 000000000..aa3f4907f --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/wrap.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/node_modules/wordwrap/test/wrap.js new file mode 100644 index 000000000..0cfb76d17 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/package.json new file mode 100644 index 000000000..bbe848c75 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/package.json @@ -0,0 +1,46 @@ +{ + "name": "optimist", + "version": "0.2.8", + "description": "Light-weight option parsing with an argv hash. No optstrings attached.", + "main": "./index.js", + "directories": { + "lib": ".", + "test": "test", + "example": "examples" + }, + "dependencies": { + "wordwrap": ">=0.0.1 <0.1.0" + }, + "devDependencies": { + "hashish": "0.0.x", + "expresso": "0.7.x" + }, + "scripts": { + "test": "expresso" + }, + "repository": { + "type": "git", + "url": "http://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" + }, + "readme": "optimist\n========\n\nOptimist is a node.js library for option parsing for people who hate option\nparsing. More specifically, this module is for people who like all the --bells\nand -whistlz of program usage but think optstrings are a waste of time.\n\nWith optimist, option parsing doesn't have to suck (as much).\n\nexamples\n========\n\nWith Optimist, the options are just a hash! No optstrings attached.\n-------------------------------------------------------------------\n\nxup.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\n\nif (argv.rif - 5 * argv.xup > 7.138) {\n console.log('Buy more riffiwobbles');\n}\nelse {\n console.log('Sell the xupptumblers');\n}\n````\n\n***\n\n $ ./xup.js --rif=55 --xup=9.52\n Buy more riffiwobbles\n \n $ ./xup.js --rif 12 --xup 8.1\n Sell the xupptumblers\n\n![This one's optimistic.](http://substack.net/images/optimistic.png)\n\nBut wait! There's more! You can do short options:\n-------------------------------------------------\n \nshort.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\n````\n\n***\n\n $ ./short.js -x 10 -y 21\n (10,21)\n\nAnd booleans, both long and short (and grouped):\n----------------------------------\n\nbool.js:\n\n````javascript\n#!/usr/bin/env node\nvar util = require('util');\nvar argv = require('optimist').argv;\n\nif (argv.s) {\n util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');\n}\nconsole.log(\n (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')\n);\n````\n\n***\n\n $ ./bool.js -s\n The cat says: meow\n \n $ ./bool.js -sp\n The cat says: meow.\n\n $ ./bool.js -sp --fr\n Le chat dit: miaou.\n\nAnd non-hypenated options too! Just use `argv._`!\n-------------------------------------------------\n \nnonopt.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\nconsole.log(argv._);\n````\n\n***\n\n $ ./nonopt.js -x 6.82 -y 3.35 moo\n (6.82,3.35)\n [ 'moo' ]\n \n $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz\n (0.54,1.12)\n [ 'foo', 'bar', 'baz' ]\n\nPlus, Optimist comes with .usage() and .demand()!\n-------------------------------------------------\n\ndivide.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Usage: $0 -x [num] -y [num]')\n .demand(['x','y'])\n .argv;\n\nconsole.log(argv.x / argv.y);\n````\n\n***\n \n $ ./divide.js -x 55 -y 11\n 5\n \n $ node ./divide.js -x 4.91 -z 2.51\n Usage: node ./divide.js -x [num] -y [num]\n\n Options:\n -x [required]\n -y [required]\n\n Missing required arguments: y\n\nEVEN MORE HOLY COW\n------------------\n\ndefault_singles.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default('x', 10)\n .default('y', 10)\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_singles.js -x 5\n 15\n\ndefault_hash.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default({ x : 10, y : 10 })\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_hash.js -y 7\n 17\n\nAnd if you really want to get all descriptive about it...\n---------------------------------------------------------\n\nboolean_single.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean('v')\n .argv\n;\nconsole.dir(argv);\n````\n\n***\n\n $ ./boolean_single.js -v foo bar baz\n true\n [ 'bar', 'baz', 'foo' ]\n\nboolean_double.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean(['x','y','z'])\n .argv\n;\nconsole.dir([ argv.x, argv.y, argv.z ]);\nconsole.dir(argv._);\n````\n\n***\n\n $ ./boolean_double.js -x -z one two three\n [ true, false, true ]\n [ 'one', 'two', 'three' ]\n\nOptimist is here to help...\n---------------------------\n\nYou can describe parameters for help messages and set aliases. Optimist figures\nout how to format a handy help string automatically.\n\nline_count.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Count the lines in a file.\\nUsage: $0')\n .demand('f')\n .alias('f', 'file')\n .describe('f', 'Load a file')\n .argv\n;\n\nvar fs = require('fs');\nvar s = fs.createReadStream(argv.file);\n\nvar lines = 0;\ns.on('data', function (buf) {\n lines += buf.toString().match(/\\n/g).length;\n});\n\ns.on('end', function () {\n console.log(lines);\n});\n````\n\n***\n\n $ node line_count.js\n Count the lines in a file.\n Usage: node ./line_count.js\n\n Options:\n -f, --file Load a file [required]\n\n Missing required arguments: f\n\n $ node line_count.js --file line_count.js \n 20\n \n $ node line_count.js -f line_count.js \n 20\n\nmethods\n=======\n\nBy itself,\n\n````javascript\nrequire('optimist').argv\n`````\n\nwill use `process.argv` array to construct the `argv` object.\n\nYou can pass in the `process.argv` yourself:\n\n````javascript\nrequire('optimist')([ '-x', '1', '-y', '2' ]).argv\n````\n\nor use .parse() to do the same thing:\n\n````javascript\nrequire('optimist').parse([ '-x', '1', '-y', '2' ])\n````\n\nThe rest of these methods below come in just before the terminating `.argv`.\n\n.alias(key, alias)\n------------------\n\nSet key names as equivalent such that updates to a key will propagate to aliases\nand vice-versa.\n\nOptionally `.alias()` can take an object that maps keys to aliases.\n\n.default(key, value)\n--------------------\n\nSet `argv[key]` to `value` if no option was specified on `process.argv`.\n\nOptionally `.default()` can take an object that maps keys to default values.\n\n.demand(key)\n------------\n\nIf `key` is a string, show the usage information and exit if `key` wasn't\nspecified in `process.argv`.\n\nIf `key` is a number, demand at least as many non-option arguments, which show\nup in `argv._`.\n\nIf `key` is an Array, demand each element.\n\n.describe(key, desc)\n--------------------\n\nDescribe a `key` for the generated usage information.\n\nOptionally `.describe()` can take an object that maps keys to descriptions.\n\n.options(key, opt)\n------------------\n\nInstead of chaining together `.alias().demand().default()`, you can specify\nkeys in `opt` for each of the chainable methods.\n\nFor example:\n\n````javascript\nvar argv = require('optimist')\n .options('f', {\n alias : 'file',\n default : '/etc/passwd',\n })\n .argv\n;\n````\n\nis the same as\n\n````javascript\nvar argv = require('optimist')\n .alias('f', 'file')\n .default('f', '/etc/passwd')\n .argv\n;\n````\n\nOptionally `.options()` can take an object that maps keys to `opt` parameters.\n\n.usage(message)\n---------------\n\nSet a usage message to show which commands to use. Inside `message`, the string\n`$0` will get interpolated to the current script name or node command for the\npresent script similar to how `$0` works in bash or perl.\n\n.check(fn)\n----------\n\nCheck that certain conditions are met in the provided arguments.\n\nIf `fn` throws or returns `false`, show the thrown error, usage information, and\nexit.\n\n.boolean(key)\n-------------\n\nInterpret `key` as a boolean. If a non-flag option follows `key` in\n`process.argv`, that string won't get set as the value of `key`.\n\nIf `key` never shows up as a flag in `process.arguments`, `argv[key]` will be\n`false`.\n\nIf `key` is an Array, interpret all the elements as booleans.\n\n.string(key)\n------------\n\nTell the parser logic not to interpret `key` as a number or boolean.\nThis can be useful if you need to preserve leading zeros in an input.\n\nIf `key` is an Array, interpret all the elements as strings.\n\n.wrap(columns)\n--------------\n\nFormat usage output to wrap at `columns` many columns.\n\n.help()\n-------\n\nReturn the generated usage string.\n\n.showHelp(fn=console.error)\n---------------------------\n\nPrint the usage data using `fn` for printing.\n\n.parse(args)\n------------\n\nParse `args` instead of `process.argv`. Returns the `argv` object.\n\n.argv\n-----\n\nGet the arguments as a plain old object.\n\nArguments without a corresponding flag show up in the `argv._` array.\n\nThe script name or node command is available at `argv.$0` similarly to how `$0`\nworks in bash or perl.\n\nparsing tricks\n==============\n\nstop parsing\n------------\n\nUse `--` to stop parsing flags and stuff the remainder into `argv._`.\n\n $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4\n { _: [ '-c', '3', '-d', '4' ],\n '$0': 'node ./examples/reflect.js',\n a: 1,\n b: 2 }\n\nnegate fields\n-------------\n\nIf you want to explicity set a field to false instead of just leaving it\nundefined or to override a default you can do `--no-key`.\n\n $ node examples/reflect.js -a --no-b\n { _: [],\n '$0': 'node ./examples/reflect.js',\n a: true,\n b: false }\n\nnumbers\n-------\n\nEvery argument that looks like a number (`!isNaN(Number(arg))`) is converted to\none. This way you can just `net.createConnection(argv.port)` and you can add\nnumbers out of `argv` with `+` without having that mean concatenation,\nwhich is super frustrating.\n\nduplicates\n----------\n\nIf you specify a flag multiple times it will get turned into an array containing\nall the values in order.\n\n $ node examples/reflect.js -x 5 -x 8 -x 0\n { _: [],\n '$0': 'node ./examples/reflect.js',\n x: [ 5, 8, 0 ] }\n\ninstallation\n============\n\nWith [npm](http://github.com/isaacs/npm), just do:\n npm install optimist\n \nor clone this project on github:\n\n git clone http://github.com/substack/node-optimist.git\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso),\njust do:\n \n expresso\n\ninspired By\n===========\n\nThis module is loosely inspired by Perl's\n[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).\n", + "_id": "optimist@0.2.8", + "_from": "optimist@0.2" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_.js new file mode 100644 index 000000000..3d6df6e0c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_.js @@ -0,0 +1,66 @@ +var spawn = require('child_process').spawn; +var assert = require('assert'); + +exports.dotSlashEmpty = function () { + testCmd('./bin.js', []); +}; + +exports.dotSlashArgs = function () { + testCmd('./bin.js', [ 'a', 'b', 'c' ]); +}; + +exports.nodeEmpty = function () { + testCmd('node bin.js', []); +}; + +exports.nodeArgs = function () { + testCmd('node bin.js', [ 'x', 'y', 'z' ]); +}; + +exports.whichNodeEmpty = function () { + var which = spawn('which', ['node']); + + which.stdout.on('data', function (buf) { + testCmd(buf.toString().trim() + ' bin.js', []); + }); + + which.stderr.on('data', function (err) { + assert.fail(err.toString()); + }); +}; + +exports.whichNodeArgs = function () { + var which = spawn('which', ['node']); + + which.stdout.on('data', function (buf) { + testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]); + }); + + which.stderr.on('data', function (err) { + assert.fail(err.toString()); + }); +}; + +function testCmd (cmd, args) { + 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) { + assert.fail(err.toString()); + }); + + bin.stdout.on('data', function (buf) { + clearTimeout(to); + var _ = JSON.parse(buf.toString()); + assert.eql(_.map(String), args.map(String)); + }); +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_/argv.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_/argv.js new file mode 100644 index 000000000..3d096062c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_/bin.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/_/bin.js new file mode 100644 index 000000000..4a18d85f3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/parse.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/parse.js new file mode 100644 index 000000000..eed467ead --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/parse.js @@ -0,0 +1,304 @@ +var optimist = require('../index'); +var assert = require('assert'); +var path = require('path'); + +var localExpresso = path.normalize( + __dirname + '/../node_modules/.bin/expresso' +); + +var expresso = process.argv[1] === localExpresso + ? 'node ./node_modules/.bin/expresso' + : 'expresso' +; + +exports['short boolean'] = function () { + var parse = optimist.parse([ '-b' ]); + assert.eql(parse, { b : true, _ : [], $0 : expresso }); + assert.eql(typeof parse.b, 'boolean'); +}; + +exports['long boolean'] = function () { + assert.eql( + optimist.parse([ '--bool' ]), + { bool : true, _ : [], $0 : expresso } + ); +}; + +exports.bare = function () { + assert.eql( + optimist.parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ], $0 : expresso } + ); +}; + +exports['short group'] = function () { + assert.eql( + optimist.parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [], $0 : expresso } + ); +}; + +exports['short group next'] = function () { + assert.eql( + optimist.parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [], $0 : expresso } + ); +}; + +exports['short capture'] = function () { + assert.eql( + optimist.parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [], $0 : expresso } + ); +}; + +exports['short captures'] = function () { + assert.eql( + optimist.parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [], $0 : expresso } + ); +}; + +exports['long capture sp'] = function () { + assert.eql( + optimist.parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [], $0 : expresso } + ); +}; + +exports['long capture eq'] = function () { + assert.eql( + optimist.parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [], $0 : expresso } + ); +}; + +exports['long captures sp'] = function () { + assert.eql( + optimist.parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [], $0 : expresso } + ); +}; + +exports['long captures eq'] = function () { + assert.eql( + optimist.parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [], $0 : expresso } + ); +}; + +exports['mixed short bool and capture'] = function () { + assert.eql( + optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ], $0 : expresso, + } + ); +}; + +exports['short and long'] = function () { + assert.eql( + optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ], $0 : expresso, + } + ); +}; + +exports.no = function () { + assert.eql( + optimist.parse([ '--no-moo' ]), + { moo : false, _ : [], $0 : expresso } + ); +}; + +exports.multi = function () { + assert.eql( + optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [], $0 : expresso } + ); +}; + +exports.comprehensive = function () { + assert.eql( + 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 : expresso + } + ); +}; + +exports.nums = function () { + var argv = optimist.parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789', + ]); + assert.eql(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ], + $0 : expresso + }); + assert.eql(typeof argv.x, 'number'); + assert.eql(typeof argv.y, 'number'); + assert.eql(typeof argv.z, 'number'); + assert.eql(typeof argv.w, 'string'); + assert.eql(typeof argv.hex, 'number'); + assert.eql(typeof argv._[0], 'number'); +}; + +exports['flag boolean'] = function () { + var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv; + assert.eql(parse, { t : true, _ : [ 'moo' ], $0 : expresso }); + assert.eql(typeof parse.t, 'boolean'); +}; + +exports['flag boolean value'] = function () { + var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true']) + .boolean(['t', 'verbose']).default('verbose', true).argv; + + assert.eql(parse, { + verbose: false, + t: true, + _: ['moo'], + $0 : expresso + }); + + assert.eql(typeof parse.verbose, 'boolean'); + assert.eql(typeof parse.t, 'boolean'); +}; + +exports['flag boolean default false'] = function () { + var parse = optimist(['moo']) + .boolean(['t', 'verbose']) + .default('verbose', false) + .default('t', false).argv; + + assert.eql(parse, { + verbose: false, + t: false, + _: ['moo'], + $0 : expresso + }); + + assert.eql(typeof parse.verbose, 'boolean'); + assert.eql(typeof parse.t, 'boolean'); + +}; + +exports['boolean groups'] = function () { + var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ]) + .boolean(['x','y','z']).argv; + + assert.eql(parse, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ], + $0 : expresso + }); + + assert.eql(typeof parse.x, 'boolean'); + assert.eql(typeof parse.y, 'boolean'); + assert.eql(typeof parse.z, 'boolean'); +}; + +exports.strings = function () { + var s = optimist([ '-s', '0001234' ]).string('s').argv.s; + assert.eql(s, '0001234'); + assert.eql(typeof s, 'string'); + + var x = optimist([ '-x', '56' ]).string('x').argv.x; + assert.eql(x, '56'); + assert.eql(typeof x, 'string'); +}; + +exports.stringArgs = function () { + var s = optimist([ ' ', ' ' ]).string('_').argv._; + assert.eql(s.length, 2); + assert.eql(typeof s[0], 'string'); + assert.eql(s[0], ' '); + assert.eql(typeof s[1], 'string'); + assert.eql(s[1], ' '); +}; + +exports.slashBreak = function () { + assert.eql( + optimist.parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [], $0 : expresso } + ); + assert.eql( + optimist.parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : expresso } + ); +}; + +exports.alias = function () { + var argv = optimist([ '-f', '11', '--zoom', '55' ]) + .alias('z', 'zoom') + .argv + ; + assert.equal(argv.zoom, 55); + assert.equal(argv.z, argv.zoom); + assert.equal(argv.f, 11); +}; + +exports.multiAlias = function () { + var argv = optimist([ '-f', '11', '--zoom', '55' ]) + .alias('z', [ 'zm', 'zoom' ]) + .argv + ; + assert.equal(argv.zoom, 55); + assert.equal(argv.z, argv.zoom); + assert.equal(argv.z, argv.zm); + assert.equal(argv.f, 11); +}; + +exports['boolean default true'] = function () { + var argv = optimist.options({ + sometrue: { + boolean: true, + default: true + } + }).argv; + + assert.equal(argv.sometrue, true); +}; + +exports['boolean default false'] = function () { + var argv = optimist.options({ + somefalse: { + boolean: true, + default: false + } + }).argv; + + assert.equal(argv.somefalse, false); +}; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/usage.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/usage.js new file mode 100644 index 000000000..6593b9bae --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/optimist/test/usage.js @@ -0,0 +1,256 @@ +var Hash = require('hashish'); +var optimist = require('../index'); +var assert = require('assert'); + +exports.usageFail = function () { + var r = checkUsage(function () { + return optimist('-x 10 -z 20'.split(' ')) + .usage('Usage: $0 -x NUM -y NUM') + .demand(['x','y']) + .argv; + }); + assert.deepEqual( + r.result, + { x : 10, z : 20, _ : [], $0 : './usage' } + ); + + assert.deepEqual( + r.errors.join('\n').split(/\n+/), + [ + 'Usage: ./usage -x NUM -y NUM', + 'Options:', + ' -x [required]', + ' -y [required]', + 'Missing required arguments: y', + ] + ); + assert.deepEqual(r.logs, []); + assert.ok(r.exit); +}; + +exports.usagePass = function () { + var r = checkUsage(function () { + return optimist('-x 10 -y 20'.split(' ')) + .usage('Usage: $0 -x NUM -y NUM') + .demand(['x','y']) + .argv; + }); + assert.deepEqual(r, { + result : { x : 10, y : 20, _ : [], $0 : './usage' }, + errors : [], + logs : [], + exit : false, + }); +}; + +exports.checkPass = function () { + 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; + }); + assert.deepEqual(r, { + result : { x : 10, y : 20, _ : [], $0 : './usage' }, + errors : [], + logs : [], + exit : false, + }); +}; + +exports.checkFail = function () { + 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; + }); + + assert.deepEqual( + r.result, + { x : 10, z : 20, _ : [], $0 : './usage' } + ); + + assert.deepEqual( + r.errors.join('\n').split(/\n+/), + [ + 'Usage: ./usage -x NUM -y NUM', + 'You forgot about -y' + ] + ); + + assert.deepEqual(r.logs, []); + assert.ok(r.exit); +}; + +exports.checkCondPass = function () { + 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; + }); + assert.deepEqual(r, { + result : { x : 10, y : 20, _ : [], $0 : './usage' }, + errors : [], + logs : [], + exit : false, + }); +}; + +exports.checkCondFail = function () { + 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; + }); + + assert.deepEqual( + r.result, + { x : 10, z : 20, _ : [], $0 : './usage' } + ); + + assert.deepEqual( + r.errors.join('\n').split(/\n+/).join('\n'), + 'Usage: ./usage -x NUM -y NUM\n' + + 'Argument check failed: ' + checker.toString() + ); + + assert.deepEqual(r.logs, []); + assert.ok(r.exit); +}; + +exports.countPass = function () { + var r = checkUsage(function () { + return optimist('1 2 3 --moo'.split(' ')) + .usage('Usage: $0 [x] [y] [z] {OPTIONS}') + .demand(3) + .argv; + }); + assert.deepEqual(r, { + result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' }, + errors : [], + logs : [], + exit : false, + }); +}; + +exports.countFail = function () { + var r = checkUsage(function () { + return optimist('1 2 --moo'.split(' ')) + .usage('Usage: $0 [x] [y] [z] {OPTIONS}') + .demand(3) + .argv; + }); + assert.deepEqual( + r.result, + { _ : [ '1', '2' ], moo : true, $0 : './usage' } + ); + + assert.deepEqual( + r.errors.join('\n').split(/\n+/), + [ + 'Usage: ./usage [x] [y] [z] {OPTIONS}', + 'Not enough non-option arguments: got 2, need at least 3', + ] + ); + + assert.deepEqual(r.logs, []); + assert.ok(r.exit); +}; + +exports.defaultSingles = function () { + var r = checkUsage(function () { + return optimist('--foo 50 --baz 70 --powsy'.split(' ')) + .default('foo', 5) + .default('bar', 6) + .default('baz', 7) + .argv + ; + }); + assert.eql(r.result, { + foo : '50', + bar : 6, + baz : '70', + powsy : true, + _ : [], + $0 : './usage', + }); +}; + +exports.defaultHash = function () { + var r = checkUsage(function () { + return optimist('--foo 50 --baz 70'.split(' ')) + .default({ foo : 10, bar : 20, quux : 30 }) + .argv + ; + }); + assert.eql(r.result, { + foo : '50', + bar : 20, + baz : 70, + quux : 30, + _ : [], + $0 : './usage', + }); +}; + +exports.rebase = function () { + assert.equal( + optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'), + './foo/bar/baz' + ); + assert.equal( + optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'), + '../../..' + ); + assert.equal( + optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'), + '../pow/zoom.txt' + ); +}; + +function checkUsage (f) { + var _process = process; + process = Hash.copy(process); + var exit = false; + process.exit = function () { 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 = _process; + console.error = console._error; + console.log = console._log; + + return { + errors : errors, + logs : logs, + exit : exit, + result : result, + }; +}; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/.npmignore new file mode 100644 index 000000000..13abef4f5 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/.npmignore @@ -0,0 +1,3 @@ +node_modules +node_modules/* +npm_debug.log diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/index.js new file mode 100644 index 000000000..8fadda96c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/index.js @@ -0,0 +1,76 @@ +var Stream = require('stream') + +/* + was gonna use through for this, + but it does not match quite right, + because you need a seperate pause + mechanism for the readable and writable + sides. +*/ + +module.exports = function () { + var buffer = [], ended = false, destroyed = false + var stream = new Stream() + stream.writable = stream.readable = true + stream.paused = false + + stream.write = function (data) { + if(!this.paused) + this.emit('data', data) + else + buffer.push(data) + return !(this.paused || buffer.length) + } + function onEnd () { + stream.readable = false + stream.emit('end') + process.nextTick(stream.destroy.bind(stream)) + } + stream.end = function (data) { + if(data) this.write(data) + this.ended = true + this.writable = false + if(!(this.paused || buffer.length)) + return onEnd() + else + this.once('drain', onEnd) + this.drain() + } + + stream.drain = function () { + while(!this.paused && buffer.length) + this.emit('data', buffer.shift()) + //if the buffer has emptied. emit drain. + if(!buffer.length && !this.paused) + this.emit('drain') + } + + stream.resume = function () { + //this is where I need pauseRead, and pauseWrite. + //here the reading side is unpaused, + //but the writing side may still be paused. + //the whole buffer might not empity at once. + //it might pause again. + //the stream should never emit data inbetween pause()...resume() + //and write should return !buffer.length + + this.paused = false +// process.nextTick(this.drain.bind(this)) //will emit drain if buffer empties. + this.drain() + return this + } + + stream.destroy = function () { + if(destroyed) return + destroyed = ended = true + buffer.length = 0 + this.emit('close') + } + + stream.pause = function () { + stream.paused = true + return this + } + + return stream +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/package.json new file mode 100644 index 000000000..7702ad500 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/package.json @@ -0,0 +1,38 @@ +{ + "name": "pause-stream", + "version": "0.0.4", + "description": "a ThroughStream that strictly buffers all readable events when paused.", + "main": "index.js", + "directories": { + "test": "test" + }, + "devDependencies": { + "stream-spec": "~0.2.0" + }, + "scripts": { + "test": "node test/index.js && node test/pause-end.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/pause-stream.git" + }, + "keywords": [ + "stream", + "pipe", + "pause", + "drain", + "buffer" + ], + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": [ + "MIT", + "Apache2" + ], + "readme": "# PauseStream\n\nThis is a `Stream` that will strictly buffer when paused.\nConnect it to anything you need buffered.\n\n``` js\n var ps = require('pause-stream')();\n\n badlyBehavedStream.pipe(ps.pause())\n\n aLittleLater(function (err, data) {\n ps.pipe(createAnotherStream(data))\n ps.resume()\n })\n```\n\n`PauseStream` will buffer whenever paused.\nit will buffer when yau have called `pause` manually.\nbut also when it's downstream `dest.write()===false`.\nit will attempt to drain the buffer when you call resume\nor the downstream emits `'drain'`\n\n`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec)\nand [stream-tester](https://github.com/dominictarr/stream-tester)\n", + "_id": "pause-stream@0.0.4", + "_from": "pause-stream@0.0.4" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/readme.markdown new file mode 100644 index 000000000..715cb5229 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/readme.markdown @@ -0,0 +1,24 @@ +# PauseStream + +This is a `Stream` that will strictly buffer when paused. +Connect it to anything you need buffered. + +``` js + var ps = require('pause-stream')(); + + badlyBehavedStream.pipe(ps.pause()) + + aLittleLater(function (err, data) { + ps.pipe(createAnotherStream(data)) + ps.resume() + }) +``` + +`PauseStream` will buffer whenever paused. +it will buffer when yau have called `pause` manually. +but also when it's downstream `dest.write()===false`. +it will attempt to drain the buffer when you call resume +or the downstream emits `'drain'` + +`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec) +and [stream-tester](https://github.com/dominictarr/stream-tester) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/index.js new file mode 100644 index 000000000..4aa7d5ef8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/index.js @@ -0,0 +1,17 @@ +var spec = require('stream-spec') +var tester = require('stream-tester') +var ps = require('..')() + +spec(ps) + .through({strict: false}) + .validateOnExit() + +var master = tester.createConsistent + +tester.createRandomStream(100) //1k random numbers + .pipe(master = tester.createConsistentStream()) + .pipe(tester.createUnpauseStream()) + .pipe(ps) + .pipe(tester.createPauseStream()) + .pipe(master.createSlave()) + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/pause-end.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/pause-end.js new file mode 100644 index 000000000..a6c27ef19 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/pause-stream/test/pause-end.js @@ -0,0 +1,33 @@ + +var pause = require('..') +var assert = require('assert') + +var ps = pause() +var read = [], ended = false + +ps.on('data', function (i) { + read.push(i) +}) + +ps.on('end', function () { + ended = true +}) + +assert.deepEqual(read, []) + +ps.write(0) +ps.write(1) +ps.write(2) + +assert.deepEqual(read, [0, 1, 2]) + +ps.pause() + +assert.deepEqual(read, [0, 1, 2]) + +ps.end() +assert.equal(ended, false) +ps.resume() +assert.equal(ended, true) + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.npmignore new file mode 100644 index 000000000..13abef4f5 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.npmignore @@ -0,0 +1,3 @@ +node_modules +node_modules/* +npm_debug.log diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/LICENCE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/LICENCE new file mode 100644 index 000000000..171dd9700 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/LICENCE @@ -0,0 +1,22 @@ +Copyright (c) 2011 Dominic Tarr + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/examples/pretty.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/examples/pretty.js new file mode 100644 index 000000000..af043401c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/examples/pretty.js @@ -0,0 +1,25 @@ + +var inspect = require('util').inspect + +if(!module.parent) { + var es = require('..') //load event-stream + es.pipe( //pipe joins streams together + process.openStdin(), //open stdin + es.split(), //split stream to break on newlines + es.map(function (data, callback) {//turn this async function into a stream + var j + try { + j = JSON.parse(data) //try to parse input into json + } catch (err) { + return callback(null, data) //if it fails just pass it anyway + } + callback(null, inspect(j)) //render it nicely + }), + process.stdout // pipe it to stdout ! + ) + } + +// run this +// +// curl -sS registry.npmjs.org/event-stream | node pretty.js +// diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/index.js new file mode 100644 index 000000000..1146c96a3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/index.js @@ -0,0 +1,35 @@ +//filter will reemit the data if cb(err,pass) pass is truthy + +// reduce is more tricky +// maybe we want to group the reductions or emit progress updates occasionally +// the most basic reduce just emits one 'data' event after it has recieved 'end' + + +var through = require('through') + + +module.exports = split + +function split (matcher) { + var soFar = '' + if (!matcher) + matcher = '\n' + + return through(function (buffer) { + var stream = this + , pieces = (soFar + buffer).split(matcher) + soFar = pieces.pop() + + pieces.forEach(function (piece) { + stream.emit('data', piece) + }) + + return true + }, + function () { + if(soFar) + this.emit('data', soFar) + this.emit('end') + }) +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.APACHE2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.APACHE2 new file mode 100644 index 000000000..6366c0471 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.MIT b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.MIT new file mode 100644 index 000000000..6eafbd734 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/index.js new file mode 100644 index 000000000..cd2505585 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/index.js @@ -0,0 +1,65 @@ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end) { + write = write || function (data) { this.emit('data', data) } + end = end || function () { this.emit('end') } + + var ended = false, destroyed = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + stream.on('end', function () { + stream.readable = false + if(!stream.writable) + process.nextTick(function () { + stream.destroy() + }) + }) + + stream.end = function (data) { + if(ended) return + //this breaks, because pipe doesn't check writable before calling end. + //throw new Error('cannot call end twice') + ended = true + if(arguments.length) stream.write(data) + this.writable = false + end.call(this) + if(!this.readable) + this.destroy() + } + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + stream.writable = stream.readable = false + stream.emit('close') + } + stream.pause = function () { + stream.paused = true + } + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('drain') + } + } + return stream +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/package.json new file mode 100644 index 000000000..3ecb71d86 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/package.json @@ -0,0 +1,29 @@ +{ + "name": "through", + "version": "0.0.4", + "description": "simplified stream contruction", + "main": "index.js", + "scripts": { + "test": "asynct test/*.js" + }, + "devDependencies": { + "stream-spec": "0", + "assertions": "2", + "asynct": "1" + }, + "keywords": [ + "stream", + "streams", + "user-streams", + "pipe" + ], + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": "MIT", + "readme": "#through\n\n[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through)\n\nEasy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic.\nUse `this.pause()` and `this.resume()` to manage flow.\nCheck `this.paused` to see current flow state. (write always returns `!this.paused`)\n\nthis function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream).\n\n``` js\nvar through = require('through')\n\nthrough(function write(data) {\n this.emit('data', data)\n //this.pause() \n },\n function end () { //optional\n this.emit('end')\n })\n\n```\n\n## License\n\nMIT / Apache2\n", + "_id": "through@0.0.4", + "_from": "through@0.0.4" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/readme.markdown new file mode 100644 index 000000000..ce9b9e5c8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/readme.markdown @@ -0,0 +1,26 @@ +#through + +[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through) + +Easy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic. +Use `this.pause()` and `this.resume()` to manage flow. +Check `this.paused` to see current flow state. (write always returns `!this.paused`) + +this function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream). + +``` js +var through = require('through') + +through(function write(data) { + this.emit('data', data) + //this.pause() + }, + function end () { //optional + this.emit('end') + }) + +``` + +## License + +MIT / Apache2 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/test/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/test/index.js new file mode 100644 index 000000000..25a6ea7e9 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/node_modules/through/test/index.js @@ -0,0 +1,113 @@ + +var spec = require('stream-spec') +var through = require('..') +var a = require('assertions') + +/* + I'm using these two functions, and not streams and pipe + so there is less to break. if this test fails it must be + the implementation of _through_ +*/ + +function write(array, stream) { + array = array.slice() + function next() { + while(array.length) + if(stream.write(array.shift()) === false) + return stream.once('drain', next) + + stream.end() + } + + next() +} + +function read(stream, callback) { + var actual = [] + stream.on('data', function (data) { + actual.push(data) + }) + stream.once('end', function () { + callback(null, actual) + }) + stream.once('error', function (err) { + callback(err) + }) +} + +exports['simple defaults'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} + +exports['simple functions'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through(function (data) { + this.emit('data', data*2) + }) + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected.map(function (data) { + return data*2 + })) + test.done() + }) + + write(expected, t) +} +exports['pauses'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l) //Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + t.on('data', function () { + if(Math.random() > 0.1) return + t.pause() + process.nextTick(function () { + t.resume() + }) + }) + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/package.json new file mode 100644 index 000000000..a592dadfa --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/package.json @@ -0,0 +1,35 @@ +{ + "name": "split", + "version": "0.0.0", + "description": "split a Text Stream into a Line Stream", + "homepage": "http://github.com/dominictarr/split", + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/split.git" + }, + "dependencies": { + "through": "0.0.4" + }, + "devDependencies": { + "asynct": "*", + "it-is": "1", + "ubelt": "~2.9", + "stream-spec": "~0.2", + "event-stream": "~3.0.2" + }, + "scripts": { + "test": "asynct test/" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "http://bit.ly/dominictarr" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "# Split (matcher)\n\n\n\nBreak up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` \n\nExample, read every line in a file ...\n\n``` js\n fs.createReadStream(file)\n .pipe(split())\n .on('data', function (line) {\n //each chunk now is a seperate line!\n })\n\n```\n\n`split` takes the same arguments as `string.split` except it defaults to '\\n' instead of ',', and the optional `limit` paremeter is ignored.\n[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)\n\n", + "_id": "split@0.0.0", + "_from": "split@0.0.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/readme.markdown new file mode 100644 index 000000000..57c8edc01 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/readme.markdown @@ -0,0 +1,20 @@ +# Split (matcher) + + + +Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` + +Example, read every line in a file ... + +``` js + fs.createReadStream(file) + .pipe(split()) + .on('data', function (line) { + //each chunk now is a seperate line! + }) + +``` + +`split` takes the same arguments as `string.split` except it defaults to '\n' instead of ',', and the optional `limit` paremeter is ignored. +[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/test/split.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/test/split.asynct.js new file mode 100644 index 000000000..a6a3b1b18 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/split/test/split.asynct.js @@ -0,0 +1,47 @@ +var es = require('event-stream') + , it = require('it-is').style('colour') + , d = require('ubelt') + , split = require('..') + , join = require('path').join + , fs = require('fs') + , Stream = require('stream').Stream + , spec = require('stream-spec') + +exports ['es.split() works like String#split'] = function (test) { + var readme = join(__filename) + , expected = fs.readFileSync(readme, 'utf-8').split('\n') + , cs = split() + , actual = [] + , ended = false + , x = spec(cs).through() + + var a = new Stream () + + a.write = function (l) { + actual.push(l.trim()) + } + a.end = function () { + + ended = true + expected.forEach(function (v,k) { + //String.split will append an empty string '' + //if the string ends in a split pattern. + //es.split doesn't which was breaking this test. + //clearly, appending the empty string is correct. + //tests are passing though. which is the current job. + if(v) + it(actual[k]).like(v) + }) + //give the stream time to close + process.nextTick(function () { + test.done() + x.validate() + }) + } + a.writable = true + + fs.createReadStream(readme, {flags: 'r'}).pipe(cs) + cs.pipe(a) + +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.APACHE2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.APACHE2 new file mode 100644 index 000000000..6366c0471 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.MIT b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.MIT new file mode 100644 index 000000000..6eafbd734 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/index.js new file mode 100644 index 000000000..7072b37f1 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/index.js @@ -0,0 +1,100 @@ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + + + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end) { + write = write || function (data) { this.emit('data', data) } + end = end || function () { this.emit('end') } + + var ended = false, destroyed = false + var stream = new Stream(), buffer = [] + stream.buffer = buffer + stream.readable = stream.writable = true + stream.paused = false + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = function (data) { + buffer.push(data) + drain() + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + //this breaks, because pipe doesn't check writable before calling end. + //throw new Error('cannot call end twice') + ended = true + if(arguments.length) stream.write(data) + if(!buffer.length) _end() + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + stream.emit('pause') + } + stream.resume = function () { + if(stream.paused) { + stream.paused = false + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + } + return stream +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/package.json new file mode 100644 index 000000000..168247e91 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/package.json @@ -0,0 +1,34 @@ +{ + "name": "through", + "version": "1.1.0", + "description": "simplified stream contruction", + "main": "index.js", + "scripts": { + "test": "asynct test/*.js" + }, + "devDependencies": { + "stream-spec": "0", + "assertions": "2", + "asynct": "1" + }, + "keywords": [ + "stream", + "streams", + "user-streams", + "pipe" + ], + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/dominictarr/through.git" + }, + "homepage": "http://github.com/dominictarr/through", + "readme": "#through\n\n[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through)\n\nEasy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic.\nUse `this.pause()` and `this.resume()` to manage flow.\nCheck `this.paused` to see current flow state. (write always returns `!this.paused`)\n\nthis function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream).\n\n``` js\nvar through = require('through')\n\nthrough(function write(data) {\n this.emit('data', data)\n //this.pause() \n },\n function end () { //optional\n this.emit('end')\n })\n\n```\n\nor, with buffering on pause, use `this.queue(data)`,\ndata *cannot* be `null`. `this.queue(null)` will emit 'end'\nwhen it gets to the `null` element.\n\n``` js\nvar through = require('through')\n\nthrough(function write(data) {\n this.queue(data)\n //this.pause() \n },\n function end () { //optional\n this.queue(null)\n })\n\n```\n\n\n## License\n\nMIT / Apache2\n", + "_id": "through@1.1.0", + "_from": "through@~1.1.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/readme.markdown new file mode 100644 index 000000000..1b687e9c3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/readme.markdown @@ -0,0 +1,44 @@ +#through + +[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through) + +Easy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic. +Use `this.pause()` and `this.resume()` to manage flow. +Check `this.paused` to see current flow state. (write always returns `!this.paused`) + +this function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream). + +``` js +var through = require('through') + +through(function write(data) { + this.emit('data', data) + //this.pause() + }, + function end () { //optional + this.emit('end') + }) + +``` + +or, with buffering on pause, use `this.queue(data)`, +data *cannot* be `null`. `this.queue(null)` will emit 'end' +when it gets to the `null` element. + +``` js +var through = require('through') + +through(function write(data) { + this.queue(data) + //this.pause() + }, + function end () { //optional + this.queue(null) + }) + +``` + + +## License + +MIT / Apache2 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/buffering.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/buffering.js new file mode 100644 index 000000000..1ce4b0d19 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/buffering.js @@ -0,0 +1,37 @@ +var through = require('..') + +// must emit end before close. + +exports['buffering'] = function (t) { + var ts = through(function (data) { + this.queue(data) + }, function () { + this.queue(null) + }) + + var ended = false, actual = [] + + ts.on('data', actual.push.bind(actual)) + ts.on('end', function () { + ended = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + t.deepEqual(actual, [1, 2, 3]) + ts.pause() + ts.write(4) + ts.write(5) + ts.write(6) + t.deepEqual(actual, [1, 2, 3]) + ts.resume() + t.deepEqual(actual, [1, 2, 3, 4, 5, 6]) + ts.pause() + ts.end() + t.ok(!ended) + ts.resume() + t.ok(ended) + t.end() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/end.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/end.js new file mode 100644 index 000000000..280da0a41 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/end.js @@ -0,0 +1,27 @@ +var through = require('..') + +// must emit end before close. + +exports['end before close'] = function (t) { + var ts = through() + var ended = false, closed = false + + ts.on('end', function () { + t.ok(!closed) + ended = true + }) + ts.on('close', function () { + t.ok(ended) + closed = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + ts.end() + t.ok(ended) + t.ok(closed) + + t.end() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/index.js new file mode 100644 index 000000000..25a6ea7e9 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/node_modules/through/test/index.js @@ -0,0 +1,113 @@ + +var spec = require('stream-spec') +var through = require('..') +var a = require('assertions') + +/* + I'm using these two functions, and not streams and pipe + so there is less to break. if this test fails it must be + the implementation of _through_ +*/ + +function write(array, stream) { + array = array.slice() + function next() { + while(array.length) + if(stream.write(array.shift()) === false) + return stream.once('drain', next) + + stream.end() + } + + next() +} + +function read(stream, callback) { + var actual = [] + stream.on('data', function (data) { + actual.push(data) + }) + stream.once('end', function () { + callback(null, actual) + }) + stream.once('error', function (err) { + callback(err) + }) +} + +exports['simple defaults'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} + +exports['simple functions'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through(function (data) { + this.emit('data', data*2) + }) + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected.map(function (data) { + return data*2 + })) + test.done() + }) + + write(expected, t) +} +exports['pauses'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l) //Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + t.on('data', function () { + if(Math.random() > 0.1) return + t.pause() + process.nextTick(function () { + t.resume() + }) + }) + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/package.json new file mode 100644 index 000000000..15f8ea819 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/package.json @@ -0,0 +1,40 @@ +{ + "name": "event-stream", + "version": "3.0.7", + "description": "construct pipes of streams of events", + "homepage": "http://github.com/dominictarr/event-stream", + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/event-stream.git" + }, + "dependencies": { + "optimist": "0.2", + "through": "1.1.0", + "duplexer": "~0.0.2", + "from": "~0", + "map-stream": "0.0.1", + "pause-stream": "0.0.4", + "split": "0.0.0" + }, + "devDependencies": { + "asynct": "*", + "it-is": "1", + "ubelt": "~2.9", + "stream-spec": "~0.2" + }, + "scripts": { + "test": "asynct test/" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "http://bit.ly/dominictarr" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "# EventStream\n\n\n\n[Streams](http://nodejs.org/api/streams.html \"Stream\") are nodes best and most misunderstood idea, and \n_EventStream_ is a toolkit to make creating and working with streams easy. \n\nNormally, streams are only used of IO, \nbut in event stream we send all kinds of objects down the pipe. \nIf your application's input and output are streams, \nshouldn't the throughput be a stream too? \n\nThe *EventStream* functions resemble the array functions, \nbecause Streams are like Arrays, but laid out in time, rather than in memory. \n\nAll the `event-stream` functions return instances of `Stream`.\n\nStream API docs: [nodejs.org/api/streams](http://nodejs.org/api/streams.html \"Stream\")\n\nNOTE: I shall use the term \"through stream\" to refer to a stream that is writable and readable. \n\n###[simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js):\n\n``` js\n\n//pretty.js\n\nif(!module.parent) {\n var es = require('event-stream')\n es.pipeline( //connect streams together with `pipe`\n process.openStdin(), //open stdin\n es.split(), //split stream to break on newlines\n es.map(function (data, callback) {//turn this async function into a stream\n callback(null\n , inspect(JSON.parse(data))) //render it nicely\n }),\n process.stdout // pipe it to stdout !\n )\n }\n```\nrun it ...\n\n``` bash \ncurl -sS registry.npmjs.org/event-stream | node pretty.js\n```\n \n[node Stream documentation](http://nodejs.org/api/streams.html)\n\n## through (write?, end?)\n\nReemits data synchronously. Easy way to create syncronous through streams.\nPass in an optional `write` and `end` methods. They will be called in the \ncontext of the stream. Use `this.pause()` and `this.resume()` to manage flow.\nCheck `this.paused` to see current flow state. (write always returns `!this.paused`)\n\nthis function is the basis for most of the syncronous streams in `event-stream`.\n\n``` js\n\nes.through(function write(data) {\n this.emit('data', data)\n //this.pause() \n },\n function end () { //optional\n this.emit('end')\n })\n\n```\n\n##map (asyncFunction)\n\nCreate a through stream from an asyncronous function. \n\n``` js\nvar es = require('event-stream')\n\nes.map(function (data, callback) {\n //transform data\n // ...\n callback(null, data)\n})\n\n```\n\nEach map MUST call the callback. It may callback with data, with an error or with no arguments, \n\n * `callback()` drop this data. \n this makes the map work like `filter`, \n note:`callback(null,null)` is not the same, and will emit `null`\n\n * `callback(null, newData)` turn data into newData\n \n * `callback(error)` emit an error for this item.\n\n>Note: if a callback is not called, `map` will think that it is still being processed, \n>every call must be answered or the stream will not know when to end. \n>\n>Also, if the callback is called more than once, every call but the first will be ignored.\n\n## mapSync (syncFunction)\n\nSame as `map`, but the callback is called synchronously. Based on `es.through`\n\n## split (matcher)\n\nBreak up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` \n\nExample, read every line in a file ...\n\n``` js\n es.pipeline(\n fs.createReadStream(file, {flags: 'r'}),\n es.split(),\n es.map(function (line, cb) {\n //do something with the line \n cb(null, line)\n })\n )\n\n```\n\n`split` takes the same arguments as `string.split` except it defaults to '\\n' instead of ',', and the optional `limit` paremeter is ignored.\n[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)\n\n## join (seperator)\n\ncreate a through stream that emits `seperator` between each chunk, just like Array#join.\n\n(for legacy reasons, if you pass a callback instead of a string, join is a synonym for `es.wait`)\n\n## replace (from, to)\n\nReplace all occurences of `from` with `to`. `from` may be a `String` or a `RegExp`. \nWorks just like `string.split(from).join(to)`, but streaming.\n\n\n## parse\n\nConvienience function for parsing JSON chunks. For newline seperated JSON,\nuse with `es.split`\n\n``` js\nfs.createReadStream(filename)\n .pipe(es.split()) //defaults to lines.\n .pipe(es.parse())\n```\n\n## stringify\n\nconvert javascript objects into lines of text. The text will have whitespace escaped and have a `\\n` appended, so it will be compatible with `es.parse`\n\n``` js\nobjectStream\n .pipe(es.stringify())\n .pipe(fs.createWriteStream(filename))\n```\n\n##readable (asyncFunction) \n\ncreate a readable stream (that respects pause) from an async function. \nwhile the stream is not paused, \nthe function will be polled with `(count, callback)`, \nand `this` will be the readable stream.\n\n``` js\n\nes.readable(function (count, callback) {\n if(streamHasEnded)\n return this.emit('end')\n \n //...\n \n this.emit('data', data) //use this way to emit multiple chunks per call.\n \n callback() // you MUST always call the callback eventually.\n // the function will not be called again until you do this.\n})\n```\nyou can also pass the data and the error to the callback. \nyou may only call the callback once. \ncalling the same callback more than once will have no effect. \n\n##readArray (array)\n\nCreate a readable stream from an Array.\n\nJust emit each item as a data event, respecting `pause` and `resume`.\n\n``` js\n var es = require('event-stream')\n , reader = es.readArray([1,2,3])\n\n reader.pipe(...)\n```\n\n## writeArray (callback)\n\ncreate a writeable stream from a callback, \nall `data` events are stored in an array, which is passed to the callback when the stream ends.\n\n``` js\n var es = require('event-stream')\n , reader = es.readArray([1, 2, 3])\n , writer = es.writeArray(function (err, array){\n //array deepEqual [1, 2, 3]\n })\n\n reader.pipe(writer)\n```\n\n## pipeline (stream1,...,streamN)\n\nTurn a pipeline into a single stream. `pipeline` returns a stream that writes to the first stream\nand reads from the last stream. \n\nListening for 'error' will recieve errors from all streams inside the pipe.\n\n> `connect` is an alias for `pipeline`.\n\n``` js\n\n es.pipeline( //connect streams together with `pipe`\n process.openStdin(), //open stdin\n es.split(), //split stream to break on newlines\n es.map(function (data, callback) {//turn this async function into a stream\n callback(null\n , inspect(JSON.parse(data))) //render it nicely\n }),\n process.stdout // pipe it to stdout !\n )\n```\n\n## pause () \n\nA stream that buffers all chunks when paused.\n\n\n``` js\n var ps = es.pause()\n ps.pause() //buffer the stream, also do not allow 'end' \n ps.resume() //allow chunks through\n```\n\n## duplex (writeStream, readStream)\n\nTakes a writable stream and a readable stream and makes them appear as a readable writable stream.\n\nIt is assumed that the two streams are connected to each other in some way. \n\n(This is used by `pipeline` and `child`.)\n\n``` js\n var grep = cp.exec('grep Stream')\n\n es.duplex(grep.stdin, grep.stdout)\n```\n\n## child (child_process)\n\nCreate a through stream from a child process ...\n\n``` js\n var cp = require('child_process')\n\n es.child(cp.exec('grep Stream')) // a through stream\n\n```\n\n## wait (callback)\n\nwaits for stream to emit 'end'.\njoins chunks of a stream into a single string. \ntakes an optional callback, which will be passed the \ncomplete string when it receives the 'end' event.\n\nalso, emits a simgle 'data' event.\n\n``` js\n\nreadStream.pipe(es.join(function (err, text) {\n // have complete text here.\n}))\n\n```\n\n\n", + "_id": "event-stream@3.0.7", + "_from": "event-stream@~3.0.7" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/readme.markdown new file mode 100644 index 000000000..e83724a19 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/readme.markdown @@ -0,0 +1,286 @@ +# EventStream + + + +[Streams](http://nodejs.org/api/streams.html "Stream") are nodes best and most misunderstood idea, and +_EventStream_ is a toolkit to make creating and working with streams easy. + +Normally, streams are only used of IO, +but in event stream we send all kinds of objects down the pipe. +If your application's input and output are streams, +shouldn't the throughput be a stream too? + +The *EventStream* functions resemble the array functions, +because Streams are like Arrays, but laid out in time, rather than in memory. + +All the `event-stream` functions return instances of `Stream`. + +Stream API docs: [nodejs.org/api/streams](http://nodejs.org/api/streams.html "Stream") + +NOTE: I shall use the term "through stream" to refer to a stream that is writable and readable. + +###[simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js): + +``` js + +//pretty.js + +if(!module.parent) { + var es = require('event-stream') + es.pipeline( //connect streams together with `pipe` + process.openStdin(), //open stdin + es.split(), //split stream to break on newlines + es.map(function (data, callback) {//turn this async function into a stream + callback(null + , inspect(JSON.parse(data))) //render it nicely + }), + process.stdout // pipe it to stdout ! + ) + } +``` +run it ... + +``` bash +curl -sS registry.npmjs.org/event-stream | node pretty.js +``` + +[node Stream documentation](http://nodejs.org/api/streams.html) + +## through (write?, end?) + +Reemits data synchronously. Easy way to create syncronous through streams. +Pass in an optional `write` and `end` methods. They will be called in the +context of the stream. Use `this.pause()` and `this.resume()` to manage flow. +Check `this.paused` to see current flow state. (write always returns `!this.paused`) + +this function is the basis for most of the syncronous streams in `event-stream`. + +``` js + +es.through(function write(data) { + this.emit('data', data) + //this.pause() + }, + function end () { //optional + this.emit('end') + }) + +``` + +##map (asyncFunction) + +Create a through stream from an asyncronous function. + +``` js +var es = require('event-stream') + +es.map(function (data, callback) { + //transform data + // ... + callback(null, data) +}) + +``` + +Each map MUST call the callback. It may callback with data, with an error or with no arguments, + + * `callback()` drop this data. + this makes the map work like `filter`, + note:`callback(null,null)` is not the same, and will emit `null` + + * `callback(null, newData)` turn data into newData + + * `callback(error)` emit an error for this item. + +>Note: if a callback is not called, `map` will think that it is still being processed, +>every call must be answered or the stream will not know when to end. +> +>Also, if the callback is called more than once, every call but the first will be ignored. + +## mapSync (syncFunction) + +Same as `map`, but the callback is called synchronously. Based on `es.through` + +## split (matcher) + +Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` + +Example, read every line in a file ... + +``` js + es.pipeline( + fs.createReadStream(file, {flags: 'r'}), + es.split(), + es.map(function (line, cb) { + //do something with the line + cb(null, line) + }) + ) + +``` + +`split` takes the same arguments as `string.split` except it defaults to '\n' instead of ',', and the optional `limit` paremeter is ignored. +[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) + +## join (seperator) + +create a through stream that emits `seperator` between each chunk, just like Array#join. + +(for legacy reasons, if you pass a callback instead of a string, join is a synonym for `es.wait`) + +## replace (from, to) + +Replace all occurences of `from` with `to`. `from` may be a `String` or a `RegExp`. +Works just like `string.split(from).join(to)`, but streaming. + + +## parse + +Convienience function for parsing JSON chunks. For newline seperated JSON, +use with `es.split` + +``` js +fs.createReadStream(filename) + .pipe(es.split()) //defaults to lines. + .pipe(es.parse()) +``` + +## stringify + +convert javascript objects into lines of text. The text will have whitespace escaped and have a `\n` appended, so it will be compatible with `es.parse` + +``` js +objectStream + .pipe(es.stringify()) + .pipe(fs.createWriteStream(filename)) +``` + +##readable (asyncFunction) + +create a readable stream (that respects pause) from an async function. +while the stream is not paused, +the function will be polled with `(count, callback)`, +and `this` will be the readable stream. + +``` js + +es.readable(function (count, callback) { + if(streamHasEnded) + return this.emit('end') + + //... + + this.emit('data', data) //use this way to emit multiple chunks per call. + + callback() // you MUST always call the callback eventually. + // the function will not be called again until you do this. +}) +``` +you can also pass the data and the error to the callback. +you may only call the callback once. +calling the same callback more than once will have no effect. + +##readArray (array) + +Create a readable stream from an Array. + +Just emit each item as a data event, respecting `pause` and `resume`. + +``` js + var es = require('event-stream') + , reader = es.readArray([1,2,3]) + + reader.pipe(...) +``` + +## writeArray (callback) + +create a writeable stream from a callback, +all `data` events are stored in an array, which is passed to the callback when the stream ends. + +``` js + var es = require('event-stream') + , reader = es.readArray([1, 2, 3]) + , writer = es.writeArray(function (err, array){ + //array deepEqual [1, 2, 3] + }) + + reader.pipe(writer) +``` + +## pipeline (stream1,...,streamN) + +Turn a pipeline into a single stream. `pipeline` returns a stream that writes to the first stream +and reads from the last stream. + +Listening for 'error' will recieve errors from all streams inside the pipe. + +> `connect` is an alias for `pipeline`. + +``` js + + es.pipeline( //connect streams together with `pipe` + process.openStdin(), //open stdin + es.split(), //split stream to break on newlines + es.map(function (data, callback) {//turn this async function into a stream + callback(null + , inspect(JSON.parse(data))) //render it nicely + }), + process.stdout // pipe it to stdout ! + ) +``` + +## pause () + +A stream that buffers all chunks when paused. + + +``` js + var ps = es.pause() + ps.pause() //buffer the stream, also do not allow 'end' + ps.resume() //allow chunks through +``` + +## duplex (writeStream, readStream) + +Takes a writable stream and a readable stream and makes them appear as a readable writable stream. + +It is assumed that the two streams are connected to each other in some way. + +(This is used by `pipeline` and `child`.) + +``` js + var grep = cp.exec('grep Stream') + + es.duplex(grep.stdin, grep.stdout) +``` + +## child (child_process) + +Create a through stream from a child process ... + +``` js + var cp = require('child_process') + + es.child(cp.exec('grep Stream')) // a through stream + +``` + +## wait (callback) + +waits for stream to emit 'end'. +joins chunks of a stream into a single string. +takes an optional callback, which will be passed the +complete string when it receives the 'end' event. + +also, emits a simgle 'data' event. + +``` js + +readStream.pipe(es.join(function (err, text) { + // have complete text here. +})) + +``` + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/connect.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/connect.asynct.js new file mode 100644 index 000000000..0ba002054 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/connect.asynct.js @@ -0,0 +1,82 @@ +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + +function makeExamplePipe() { + + return es.connect( + es.map(function (data, callback) { + callback(null, data * 2) + }), + es.map(function (data, callback) { + d.delay(callback)(null, data) + }), + es.map(function (data, callback) { + callback(null, data + 2) + })) +} + +exports['simple pipe'] = function (test) { + + var pipe = makeExamplePipe() + + pipe.on('data', function (data) { + it(data).equal(18) + test.done() + }) + + pipe.write(8) + +} + +exports['read array then map'] = function (test) { + + var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 + , first = es.readArray(readThis) + , read = [] + , pipe = + es.connect( + first, + es.map(function (data, callback) { + callback(null, {data: data}) + }), + es.map(function (data, callback) { + callback(null, {data: data}) + }), + es.writeArray(function (err, array) { + it(array).deepEqual(d.map(readThis, function (data) { + return {data: {data: data}} + })) + test.done() + }) + ) +} + +exports ['connect returns a stream'] = function (test) { + + var rw = + es.connect( + es.map(function (data, callback) { + callback(null, data * 2) + }), + es.map(function (data, callback) { + callback(null, data * 5) + }) + ) + + it(rw).has({readable: true, writable: true}) + + var array = [190, 24, 6, 7, 40, 57, 4, 6] + , _array = [] + , c = + es.connect( + es.readArray(array), + rw, + es.log('after rw:'), + es.writeArray(function (err, _array) { + it(_array).deepEqual(array.map(function (e) { return e * 10 })) + test.done() + }) + ) + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/merge.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/merge.asynct.js new file mode 100644 index 000000000..17fae5b74 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/merge.asynct.js @@ -0,0 +1,20 @@ +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + +exports.merge = function (t) { + var odd = d.map(1, 3, 100, d.id) //array of multiples of 3 < 100 + var even = d.map(2, 4, 100, d.id) //array of multiples of 3 < 100 + + var r1 = es.readArray(even) + var r2 = es.readArray(odd) + + var writer = es.writeArray(function (err, array){ + if(err) throw err //unpossible + it(array.sort()).deepEqual(even.concat(odd).sort()) + t.done() + }) + + es.merge(r1, r2).pipe(writer) + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pause.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pause.asynct.js new file mode 100644 index 000000000..59d896f74 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pause.asynct.js @@ -0,0 +1,38 @@ + +var es = require('../') + , it = require('it-is') + , d = require('ubelt') + +exports ['gate buffers when shut'] = function (test) { + + var hundy = d.map(1,100, d.id) + , gate = es.pause() + , ten = 10 + es.connect( + es.readArray(hundy), + es.log('after readArray'), + gate, + //es.log('after gate'), + es.map(function (num, next) { + //stick a map in here to check that gate never emits when open + it(gate.paused).equal(false) + console.log('data', num) + if(!--ten) { + console.log('PAUSE') + gate.pause()//.resume() + d.delay(gate.resume.bind(gate), 10)() + ten = 10 + } + + next(null, num) + }), + es.writeArray(function (err, array) { //just realized that I should remove the error param. errors will be emitted + console.log('eonuhoenuoecbulc') + it(array).deepEqual(hundy) + test.done() + }) + ) + + gate.resume() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pipeline.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pipeline.asynct.js new file mode 100644 index 000000000..c2af9d8a0 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/pipeline.asynct.js @@ -0,0 +1,51 @@ +var es = require('..') + +exports['do not duplicate errors'] = function (test) { + + var errors = 0; + var pipe = es.pipeline( + es.through(function(data) { + return this.emit('data', data); + }), + es.through(function(data) { + return this.emit('error', new Error(data)); + }) + ) + + pipe.on('error', function(err) { + errors++ + console.log('error count', errors) + process.nextTick(function () { + return test.done(); + }) + }) + + return pipe.write('meh'); + +} + +exports['3 pipe do not duplicate errors'] = function (test) { + + var errors = 0; + var pipe = es.pipeline( + es.through(function(data) { + return this.emit('data', data); + }), + es.through(function(data) { + return this.emit('error', new Error(data)); + }), + es.through() + ) + + pipe.on('error', function(err) { + errors++ + console.log('error count', errors) + process.nextTick(function () { + return test.done(); + }) + }) + + return pipe.write('meh'); + +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readArray.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readArray.asynct.js new file mode 100644 index 000000000..76585eef9 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readArray.asynct.js @@ -0,0 +1,88 @@ + +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + +function readStream(stream, pauseAt, done) { + if(!done) done = pauseAt, pauseAt = -1 + var array = [] + stream.on('data', function (data) { + array.push(data) + if(!--pauseAt ) + stream.pause(), done(null, array) + }) + stream.on('error', done) + stream.on('end', function (data) { + done(null, array) + }) + +} + +exports ['read an array'] = function (test) { + + var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 + + var reader = es.readArray(readThis) + + var writer = es.writeArray(function (err, array){ + if(err) throw err //unpossible + it(array).deepEqual(readThis) + test.done() + }) + + reader.pipe(writer) +} + +exports ['read an array and pause it.'] = function (test) { + + var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 + + var reader = es.readArray(readThis) + + readStream(reader, 10, function (err, data) { + if(err) throw err + it(data).deepEqual([3, 6, 9, 12, 15, 18, 21, 24, 27, 30]) + readStream(reader, 10, function (err, data) { + it(data).deepEqual([33, 36, 39, 42, 45, 48, 51, 54, 57, 60]) + test.done() + }) + reader.resume() + }) + +} + +exports ['reader is readable, but not writeable'] = function (test) { + var reader = es.readArray([1]) + it(reader).has({ + readable: true, + writable: false + }) + + test.done() +} + + +exports ['read one item per tick'] = function (test) { + var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 + var drains = 0 + var reader = es.readArray(readThis) + var tickMapper = es.map(function (data,callback) { + process.nextTick(function () { + callback(null, data) + }) + //since tickMapper is returning false + //pipe should pause the writer until a drain occurs + return false + }) + reader.pipe(tickMapper) + readStream(tickMapper, function (err, array) { + it(array).deepEqual(readThis) + it(array.length).deepEqual(readThis.length) + it(drains).equal(readThis.length) + test.done() + }) + tickMapper.on('drain', function () { + drains ++ + }) + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readable.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readable.asynct.js new file mode 100644 index 000000000..77d0039e2 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/readable.asynct.js @@ -0,0 +1,167 @@ + +var es = require('../') + , it = require('it-is').style('colour') + , u = require('ubelt') + +exports ['read an array'] = function (test) { + + var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 + + var reader = + es.readable(function (i, callback) { + if(i >= readThis.length) + return this.emit('end') + callback(null, readThis[i]) + }) + + var writer = es.writeArray(function (err, array){ + if(err) throw err + it(array).deepEqual(readThis) + test.done() + }) + + reader.pipe(writer) +} + +exports ['read an array - async'] = function (test) { + + var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 + + var reader = + es.readable(function (i, callback) { + if(i >= readThis.length) + return this.emit('end') + u.delay(callback)(null, readThis[i]) + }) + + var writer = es.writeArray(function (err, array){ + if(err) throw err + it(array).deepEqual(readThis) + test.done() + }) + + reader.pipe(writer) +} + + +exports ['emit data then call next() also works'] = function (test) { + + var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100 + + var reader = + es.readable(function (i, next) { + if(i >= readThis.length) + return this.emit('end') + this.emit('data', readThis[i]) + next() + }) + + var writer = es.writeArray(function (err, array){ + if(err) throw err + it(array).deepEqual(readThis) + test.done() + }) + + reader.pipe(writer) +} + + +exports ['callback emits error, then stops'] = function (test) { + + var err = new Error('INTENSIONAL ERROR') + , called = 0 + + var reader = + es.readable(function (i, callback) { + if(called++) + return + callback(err) + }) + + reader.on('error', function (_err){ + it(_err).deepEqual(err) + u.delay(function() { + it(called).equal(1) + test.done() + }, 50)() + }) +} + +exports['readable does not call read concurrently'] = function (test) { + + var current = 0 + var source = es.readable(function(count, cb){ + current ++ + if(count > 100) + return this.emit('end') + u.delay(function(){ + current -- + it(current).equal(0) + cb(null, {ok: true, n: count}); + })(); + }); + + var destination = es.map(function(data, cb){ + //console.info(data); + cb(); + }); + + var all = es.connect(source, destination); + + destination.on('end', test.done) +} + + +// +// emitting multiple errors is not supported by stream. +// +// I do not think that this is a good idea, at least, there should be an option to pipe to +// continue on error. it makes alot ef sense, if you are using Stream like I am, to be able to emit multiple errors. +// an error might not necessarily mean the end of the stream. it depends on the error, at least. +// +// I will start a thread on the mailing list. I'd rather that than use a custom `pipe` implementation. +// +// basically, I want to be able use pipe to transform objects, and if one object is invalid, +// the next might still be good, so I should get to choose if it's gonna stop. +// re-enstate this test when this issue progresses. +// +// hmm. I could add this to es.connect by deregistering the error listener, +// but I would rather it be an option in core. + +/* +exports ['emit multiple errors, with 2nd parameter (continueOnError)'] = function (test) { + + var readThis = d.map(1, 100, d.id) + , errors = 0 + var reader = + es.readable(function (i, callback) { + console.log(i, readThis.length) + if(i >= readThis.length) + return this.emit('end') + if(!(readThis[i] % 7)) + return callback(readThis[i]) + callback(null, readThis[i]) + }, true) + + var writer = es.writeArray(function (err, array) { + if(err) throw err + it(array).every(function (u){ + it(u % 7).notEqual(0) + }).property('length', 80) + it(errors).equal(14) + test.done() + }) + + reader.on('error', function (u) { + errors ++ + console.log(u) + if('number' !== typeof u) + throw u + + it(u % 7).equal(0) + + }) + + reader.pipe(writer) +} +*/ diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/replace.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/replace.asynct.js new file mode 100644 index 000000000..7fabf6e3c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/replace.asynct.js @@ -0,0 +1,50 @@ +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + , spec = require('stream-spec') + +var next = process.nextTick + +var fizzbuzz = '12F4BF78FB11F1314FB1617F19BF2223FB26F2829FB3132F34BF3738FB41F4344FB4647F49BF5253FB56F5859FB6162F64BF6768FB71F7374FB7677F79BF8283FB86F8889FB9192F94BF9798FB' + , fizz7buzz = '12F4BFseven8FB11F1314FB161sevenF19BF2223FB26F2829FB3132F34BF3seven38FB41F4344FB464sevenF49BF5253FB56F5859FB6162F64BF6seven68FBseven1Fseven3seven4FBseven6sevensevenFseven9BF8283FB86F8889FB9192F94BF9seven98FB' + +exports ['fizz buzz'] = function (test) { + + var readThis = d.map(1, 100, function (i) { + return ( + ! (i % 3 || i % 5) ? "FB" : + !(i % 3) ? "F" : + !(i % 5) ? "B" : + ''+i + ) + }) //array of multiples of 3 < 100 + + var reader = es.readArray(readThis) + var join = es.wait(function (err, string){ + it(string).equal(fizzbuzz) + test.done() + }) + reader.pipe(join) + +} + + +exports ['fizz buzz replace'] = function (test) { + var split = es.split(/(1)/) + var replace = es.replace('7', 'seven') + var x = spec(replace).through() + split + .pipe(replace) + .pipe(es.join(function (err, string) { + it(string).equal(fizz7buzz) + })) + + replace.on('close', function () { + x.validate() + test.done() + }) + + split.write(fizzbuzz) + split.end() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/simple-map.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/simple-map.asynct.js new file mode 100644 index 000000000..4786faabd --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/simple-map.asynct.js @@ -0,0 +1,342 @@ +'use strict'; + +var es = require('../') + , it = require('it-is') + , u = require('ubelt') + , spec = require('stream-spec') + , Stream = require('stream') + , from = require('from') + , through = require('through') + +//REFACTOR THIS TEST TO USE es.readArray and es.writeArray + +function writeArray(array, stream) { + + array.forEach( function (j) { + stream.write(j) + }) + stream.end() + +} + +function readStream(stream, done) { + + var array = [] + stream.on('data', function (data) { + array.push(data) + }) + stream.on('error', done) + stream.on('end', function (data) { + done(null, array) + }) + +} + +//call sink on each write, +//and complete when finished. + +function pauseStream (prob, delay) { + var pauseIf = ( + 'number' == typeof prob + ? function () { + return Math.random() < prob + } + : 'function' == typeof prob + ? prob + : 0.1 + ) + var delayer = ( + !delay + ? process.nextTick + : 'number' == typeof delay + ? function (next) { setTimeout(next, delay) } + : delay + ) + + return es.through(function (data) { + if(!this.paused && pauseIf()) { + console.log('PAUSE STREAM PAUSING') + this.pause() + var self = this + delayer(function () { + console.log('PAUSE STREAM RESUMING') + self.resume() + }) + } + console.log("emit ('data', " + data + ')') + this.emit('data', data) + }) +} + +exports ['simple map'] = function (test) { + + var input = u.map(1, 1000, function () { + return Math.random() + }) + var expected = input.map(function (v) { + return v * 2 + }) + + var pause = pauseStream(0.1) + var fs = from(input) + var ts = es.writeArray(function (err, ar) { + it(ar).deepEqual(expected) + test.done() + }) + var map = es.through(function (data) { + this.emit('data', data * 2) + }) + + spec(map).through().validateOnExit() + spec(pause).through().validateOnExit() + + fs.pipe(map).pipe(pause).pipe(ts) +} + +exports ['simple map applied to a stream'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + //create event stream from + + var doubler = es.map(function (data, cb) { + cb(null, data * 2) + }) + + spec(doubler).through().validateOnExit() + + //a map is only a middle man, so it is both readable and writable + + it(doubler).has({ + readable: true, + writable: true, + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.map(function (j) { + return j * 2 + })) +// process.nextTick(x.validate) + test.done() + }) + + writeArray(input, doubler) + +} + +exports['pipe two maps together'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + //create event stream from + function dd (data, cb) { + cb(null, data * 2) + } + var doubler1 = es.map(dd), doubler2 = es.map(dd) + + doubler1.pipe(doubler2) + + spec(doubler1).through().validateOnExit() + spec(doubler2).through().validateOnExit() + + readStream(doubler2, function (err, output) { + it(output).deepEqual(input.map(function (j) { + return j * 4 + })) + test.done() + }) + + writeArray(input, doubler1) + +} + +//next: +// +// test pause, resume and drian. +// + +// then make a pipe joiner: +// +// plumber (evStr1, evStr2, evStr3, evStr4, evStr5) +// +// will return a single stream that write goes to the first + +exports ['map will not call end until the callback'] = function (test) { + + var ticker = es.map(function (data, cb) { + process.nextTick(function () { + cb(null, data * 2) + }) + }) + + spec(ticker).through().validateOnExit() + + ticker.write('x') + ticker.end() + + ticker.on('end', function () { + test.done() + }) +} + + +exports ['emit error thrown'] = function (test) { + + var err = new Error('INTENSIONAL ERROR') + , mapper = + es.map(function () { + throw err + }) + + mapper.on('error', function (_err) { + it(_err).equal(err) + test.done() + }) + +// onExit(spec(mapper).basic().validate) +//need spec that says stream may error. + + mapper.write('hello') + +} + +exports ['emit error calledback'] = function (test) { + + var err = new Error('INTENSIONAL ERROR') + , mapper = + es.map(function (data, callback) { + callback(err) + }) + + mapper.on('error', function (_err) { + it(_err).equal(err) + test.done() + }) + + mapper.write('hello') + +} + +exports ['do not emit drain if not paused'] = function (test) { + + var map = es.map(function (data, callback) { + u.delay(callback)(null, 1) + return true + }) + + spec(map).through().pausable().validateOnExit() + + map.on('drain', function () { + it(false).ok('should not emit drain unless the stream is paused') + }) + + it(map.write('hello')).equal(true) + it(map.write('hello')).equal(true) + it(map.write('hello')).equal(true) + setTimeout(function () {map.end()},10) + map.on('end', test.done) +} + +exports ['emits drain if paused, when all '] = function (test) { + var active = 0 + var drained = false + var map = es.map(function (data, callback) { + active ++ + u.delay(function () { + active -- + callback(null, 1) + })() + console.log('WRITE', false) + return false + }) + + spec(map).through().validateOnExit() + + map.on('drain', function () { + drained = true + it(active).equal(0, 'should emit drain when all maps are done') + }) + + it(map.write('hello')).equal(false) + it(map.write('hello')).equal(false) + it(map.write('hello')).equal(false) + + process.nextTick(function () {map.end()},10) + + map.on('end', function () { + console.log('end') + it(drained).ok('shoud have emitted drain before end') + test.done() + }) + +} + +exports ['map applied to a stream with filtering'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + + var doubler = es.map(function (data, callback) { + if (data % 2) + callback(null, data * 2) + else + callback() + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.filter(function (j) { + return j % 2 + }).map(function (j) { + return j * 2 + })) + test.done() + }) + + spec(doubler).through().validateOnExit() + + writeArray(input, doubler) + +} + +exports ['simple mapSync applied to a stream'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + + var doubler = es.mapSync(function (data) { + return data * 2 + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.map(function (j) { + return j * 2 + })) + test.done() + }) + + spec(doubler).through().validateOnExit() + + writeArray(input, doubler) + +} + +exports ['mapSync applied to a stream with filtering'] = function (test) { + + var input = [1,2,3,7,5,3,1,9,0,2,4,6] + + var doubler = es.mapSync(function (data) { + if (data % 2) + return data * 2 + }) + + readStream(doubler, function (err, output) { + it(output).deepEqual(input.filter(function (j) { + return j % 2 + }).map(function (j) { + return j * 2 + })) + test.done() + }) + + spec(doubler).through().validateOnExit() + + writeArray(input, doubler) + +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/spec.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/spec.asynct.js new file mode 100644 index 000000000..516dbf4d3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/spec.asynct.js @@ -0,0 +1,85 @@ +/* + assert that data is called many times + assert that end is called eventually + + assert that when stream enters pause state, + on drain is emitted eventually. +*/ + +var es = require('..') +var it = require('it-is').style('colour') +var spec = require('stream-spec') + +exports['simple stream'] = function (test) { + + var stream = es.through() + var x = spec(stream).basic().pausable() + + stream.write(1) + stream.write(1) + stream.pause() + stream.write(1) + stream.resume() + stream.write(1) + stream.end(2) //this will call write() + + process.nextTick(function (){ + x.validate() + test.done() + }) +} + +exports['throw on write when !writable'] = function (test) { + + var stream = es.through() + var x = spec(stream).basic().pausable() + + stream.write(1) + stream.write(1) + stream.end(2) //this will call write() + stream.write(1) //this will be throwing..., but the spec will catch it. + + process.nextTick(function () { + x.validate() + test.done() + }) + +} + +exports['end fast'] = function (test) { + + var stream = es.through() + var x = spec(stream).basic().pausable() + + stream.end() //this will call write() + + process.nextTick(function () { + x.validate() + test.done() + }) + +} + + +/* + okay, that was easy enough, whats next? + + say, after you call paused(), write should return false + until resume is called. + + simple way to implement this: + write must return !paused + after pause() paused = true + after resume() paused = false + + on resume, if !paused drain is emitted again. + after drain, !paused + + there are lots of subtle ordering bugs in streams. + + example, set !paused before emitting drain. + + the stream api is stateful. +*/ + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/split.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/split.asynct.js new file mode 100644 index 000000000..a0ce4b29b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/split.asynct.js @@ -0,0 +1,46 @@ +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + , join = require('path').join + , fs = require('fs') + , Stream = require('stream').Stream + , spec = require('stream-spec') + +exports ['es.split() works like String#split'] = function (test) { + var readme = join(__filename) + , expected = fs.readFileSync(readme, 'utf-8').split('\n') + , cs = es.split() + , actual = [] + , ended = false + , x = spec(cs).through() + + var a = new Stream () + + a.write = function (l) { + actual.push(l.trim()) + } + a.end = function () { + + ended = true + expected.forEach(function (v,k) { + //String.split will append an empty string '' + //if the string ends in a split pattern. + //es.split doesn't which was breaking this test. + //clearly, appending the empty string is correct. + //tests are passing though. which is the current job. + if(v) + it(actual[k]).like(v) + }) + //give the stream time to close + process.nextTick(function () { + test.done() + x.validate() + }) + } + a.writable = true + + fs.createReadStream(readme, {flags: 'r'}).pipe(cs) + cs.pipe(a) + +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/stringify.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/stringify.js new file mode 100644 index 000000000..a77887bea --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/stringify.js @@ -0,0 +1,14 @@ + + + +var es = require('../') + +exports['handle buffer'] = function (t) { + + + es.stringify().on('data', function (d) { + t.equal(d.trim(), JSON.stringify('HELLO')) + t.end() + }).write(new Buffer('HELLO')) + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/writeArray.asynct.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/writeArray.asynct.js new file mode 100644 index 000000000..f09fea27b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/event-stream/test/writeArray.asynct.js @@ -0,0 +1,30 @@ + +var es = require('../') + , it = require('it-is').style('colour') + , d = require('ubelt') + +exports ['write an array'] = function (test) { + + var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100 + + var writer = es.writeArray(function (err, array){ + if(err) throw err //unpossible + it(array).deepEqual(readThis) + test.done() + }) + + d.each(readThis, writer.write.bind(writer)) + writer.end() + +} + + +exports ['writer is writable, but not readable'] = function (test) { + var reader = es.writeArray(function () {}) + it(reader).has({ + readable: false, + writable: true + }) + + test.done() +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.npmignore new file mode 100644 index 000000000..ee889666e --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.npmignore @@ -0,0 +1 @@ +assets/ diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.travis.yml new file mode 100644 index 000000000..84fd7ca24 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.9 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/README.md new file mode 100644 index 000000000..6cd71ba30 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/README.md @@ -0,0 +1,98 @@ +# tap-stream [![Build Status](https://secure.travis-ci.org/thlorenz/tap-stream.png)](http://travis-ci.org/thlorenz/tap-stream) + +Taps a nodejs stream and logs the data that's coming through. + + npm install tap-stream + +Given an [object stream](#object-stream) we can print out objects passing through and control the detail via the +depth parameter: + +```javascript +objectStream().pipe(tap(0)); +``` + +![depth0](https://github.com/thlorenz/tap-stream/raw/master/assets/depth0.png) + +```javascript +objectStream().pipe(tap(1)); +``` + +![depth1](https://github.com/thlorenz/tap-stream/raw/master/assets/depth1.png) + +``` +objectStream().pipe(tap(2)); +``` + +![depth2](https://github.com/thlorenz/tap-stream/raw/master/assets/depth2.png) + +For even more control a custom log function may be supplied: + +```javascript +objectStream() + .pipe(tap(function customLog (data) { + var nest = data.nest; + console.log ('Bird: %s, id: %s, age: %s, layed egg: %s', nest.name, data.id, nest.age, nest.egg !== undefined); + }) + ); +``` + +```text +Bird: yellow rumped warbler, id: 0, age: 1, layed egg: true +Bird: yellow rumped warbler, id: 1, age: 1, layed egg: true +``` + +## API + +### tap( [ depth | log ] ) + +Intercepts the stream and logs data that is passing through. + +- optional parameter is either a `Number` or a `Function` +- if no parameter is given, `depth` defaults to `0` and `log` to `console.log(util.inspect(..))` + +- `depth` controls the `depth` with which + [util.inspect](http://nodejs.org/api/util.html#util_util_inspect_object_showhidden_depth_colors) is called +- `log` replaces the default logging function with a custom one + +**Example:** + +```javascript +var tap = require('tap-stream'); + +myStream + .pipe(tap(1)) // log intermediate results + .pipe(..) // continute manipulating the data +``` + +## Object stream + +Included in order to give context for above examples. + +```javascript +function objectStream () { + var s = new Stream() + , objects = 0; + + var iv = setInterval( + function () { + s.emit('data', { + id: objects + , created: new Date() + , nest: { + name: 'yellow rumped warbler' + , age: 1 + , egg: { name: 'unknown' , age: 0 } + } + } + , 4 + ); + + if (++objects === 2) { + s.emit('end'); + clearInterval(iv); + } + } + , 200); + return s; +} +``` diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/examples/tap-nested-objects.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/examples/tap-nested-objects.js new file mode 100644 index 000000000..97aa57872 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/examples/tap-nested-objects.js @@ -0,0 +1,38 @@ +var Stream = require('stream') + , tap = require('..'); + +function objectStream () { + var s = new Stream() + , objects = 0; + + var iv = setInterval( + function () { + s.emit('data', { + id: objects + , created: new Date() + , nest: { + name: 'yellow rumped warbler' + , age: 1 + , egg: { name: 'unknown' , age: 0 } + } + } + ); + + if (++objects === 2) { + s.emit('end'); + clearInterval(iv); + } + } + , 200); + return s; +} + +objectStream().pipe(tap(2)); + +objectStream() + .pipe(tap(function customLog (data) { + var nest = data.nest; + console.log ('Bird: %s, id: %s, age: %s, layed egg: %s', nest.name, data.id, nest.age, nest.egg !== undefined); + }) + ); + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/index.js new file mode 100644 index 000000000..a541dfebd --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var util = require('util') + , through = require('through') + , toString = Object.prototype.toString + , slice = Array.prototype.slice; + +function blowup () { + throw new Error('Argument to streamTap needs to be either Number for depth or a log Function'); +} + +function defaultLog (depth) { + function log (data) { + console.log(util.inspect(data, false, depth, true)); + } + + return function (data) { + if (arguments.length === 1) { + log(data); + } else { + slice.call(arguments).forEach(log); + } + }; +} + +// invoke three ways: +// tap () +// tap (depth) +// tap (log) +function tap (arg0) { + var log; + + if (!arguments.length) { + log = defaultLog(1); + } else { + + if (toString.call(arg0) === '[object Number]' ) { + log = defaultLog(arg0); + } else if (toString.call(arg0) === '[object Function]' ) { + log = arg0; + } else { + blowup(); + } + + } + + return through( + function write (data) { + log(data); + this.emit('data', data); + } + ); + +} + +module.exports = tap; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/.travis.yml new file mode 100644 index 000000000..895dbd362 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.APACHE2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.APACHE2 new file mode 100644 index 000000000..6366c0471 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.MIT b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.MIT new file mode 100644 index 000000000..6eafbd734 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/index.js new file mode 100644 index 000000000..7072b37f1 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/index.js @@ -0,0 +1,100 @@ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + + + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end) { + write = write || function (data) { this.emit('data', data) } + end = end || function () { this.emit('end') } + + var ended = false, destroyed = false + var stream = new Stream(), buffer = [] + stream.buffer = buffer + stream.readable = stream.writable = true + stream.paused = false + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = function (data) { + buffer.push(data) + drain() + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + //this breaks, because pipe doesn't check writable before calling end. + //throw new Error('cannot call end twice') + ended = true + if(arguments.length) stream.write(data) + if(!buffer.length) _end() + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + stream.emit('pause') + } + stream.resume = function () { + if(stream.paused) { + stream.paused = false + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + } + return stream +} + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/package.json new file mode 100644 index 000000000..168247e91 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/package.json @@ -0,0 +1,34 @@ +{ + "name": "through", + "version": "1.1.0", + "description": "simplified stream contruction", + "main": "index.js", + "scripts": { + "test": "asynct test/*.js" + }, + "devDependencies": { + "stream-spec": "0", + "assertions": "2", + "asynct": "1" + }, + "keywords": [ + "stream", + "streams", + "user-streams", + "pipe" + ], + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/dominictarr/through.git" + }, + "homepage": "http://github.com/dominictarr/through", + "readme": "#through\n\n[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through)\n\nEasy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic.\nUse `this.pause()` and `this.resume()` to manage flow.\nCheck `this.paused` to see current flow state. (write always returns `!this.paused`)\n\nthis function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream).\n\n``` js\nvar through = require('through')\n\nthrough(function write(data) {\n this.emit('data', data)\n //this.pause() \n },\n function end () { //optional\n this.emit('end')\n })\n\n```\n\nor, with buffering on pause, use `this.queue(data)`,\ndata *cannot* be `null`. `this.queue(null)` will emit 'end'\nwhen it gets to the `null` element.\n\n``` js\nvar through = require('through')\n\nthrough(function write(data) {\n this.queue(data)\n //this.pause() \n },\n function end () { //optional\n this.queue(null)\n })\n\n```\n\n\n## License\n\nMIT / Apache2\n", + "_id": "through@1.1.0", + "_from": "through@~1.1.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/readme.markdown b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/readme.markdown new file mode 100644 index 000000000..1b687e9c3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/readme.markdown @@ -0,0 +1,44 @@ +#through + +[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through) + +Easy way to create a `Stream` that is both `readable` and `writable`. Pass in optional `write` and `end` methods. `through` takes care of pause/resume logic. +Use `this.pause()` and `this.resume()` to manage flow. +Check `this.paused` to see current flow state. (write always returns `!this.paused`) + +this function is the basis for most of the syncronous streams in [event-stream](http://github.com/dominictarr/event-stream). + +``` js +var through = require('through') + +through(function write(data) { + this.emit('data', data) + //this.pause() + }, + function end () { //optional + this.emit('end') + }) + +``` + +or, with buffering on pause, use `this.queue(data)`, +data *cannot* be `null`. `this.queue(null)` will emit 'end' +when it gets to the `null` element. + +``` js +var through = require('through') + +through(function write(data) { + this.queue(data) + //this.pause() + }, + function end () { //optional + this.queue(null) + }) + +``` + + +## License + +MIT / Apache2 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/buffering.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/buffering.js new file mode 100644 index 000000000..1ce4b0d19 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/buffering.js @@ -0,0 +1,37 @@ +var through = require('..') + +// must emit end before close. + +exports['buffering'] = function (t) { + var ts = through(function (data) { + this.queue(data) + }, function () { + this.queue(null) + }) + + var ended = false, actual = [] + + ts.on('data', actual.push.bind(actual)) + ts.on('end', function () { + ended = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + t.deepEqual(actual, [1, 2, 3]) + ts.pause() + ts.write(4) + ts.write(5) + ts.write(6) + t.deepEqual(actual, [1, 2, 3]) + ts.resume() + t.deepEqual(actual, [1, 2, 3, 4, 5, 6]) + ts.pause() + ts.end() + t.ok(!ended) + ts.resume() + t.ok(ended) + t.end() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/end.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/end.js new file mode 100644 index 000000000..280da0a41 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/end.js @@ -0,0 +1,27 @@ +var through = require('..') + +// must emit end before close. + +exports['end before close'] = function (t) { + var ts = through() + var ended = false, closed = false + + ts.on('end', function () { + t.ok(!closed) + ended = true + }) + ts.on('close', function () { + t.ok(ended) + closed = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + ts.end() + t.ok(ended) + t.ok(closed) + + t.end() + +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/index.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/index.js new file mode 100644 index 000000000..25a6ea7e9 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/node_modules/through/test/index.js @@ -0,0 +1,113 @@ + +var spec = require('stream-spec') +var through = require('..') +var a = require('assertions') + +/* + I'm using these two functions, and not streams and pipe + so there is less to break. if this test fails it must be + the implementation of _through_ +*/ + +function write(array, stream) { + array = array.slice() + function next() { + while(array.length) + if(stream.write(array.shift()) === false) + return stream.once('drain', next) + + stream.end() + } + + next() +} + +function read(stream, callback) { + var actual = [] + stream.on('data', function (data) { + actual.push(data) + }) + stream.once('end', function () { + callback(null, actual) + }) + stream.once('error', function (err) { + callback(err) + }) +} + +exports['simple defaults'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} + +exports['simple functions'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through(function (data) { + this.emit('data', data*2) + }) + spec(t) + .through() + .pausable() + .validateOnExit() + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected.map(function (data) { + return data*2 + })) + test.done() + }) + + write(expected, t) +} +exports['pauses'] = function (test) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l) //Math.random()) + + var t = through() + spec(t) + .through() + .pausable() + .validateOnExit() + + t.on('data', function () { + if(Math.random() > 0.1) return + t.pause() + process.nextTick(function () { + t.resume() + }) + }) + + read(t, function (err, actual) { + if(err) test.error(err) //fail + a.deepEqual(actual, expected) + test.done() + }) + + write(expected, t) +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/package.json new file mode 100644 index 000000000..804057958 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/package.json @@ -0,0 +1,38 @@ +{ + "name": "tap-stream", + "version": "0.1.0", + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "http://thlorenz.com" + }, + "description": "Taps a nodejs stream and logs the data that's coming through.", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "tap ./test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/tap-stream.git" + }, + "keywords": [ + "stream", + "streams", + "log", + "print", + "inspect" + ], + "license": "BSD", + "dependencies": { + "through": "~1.1.0" + }, + "devDependencies": { + "tap": "~0.3.1" + }, + "readme": "# tap-stream [![Build Status](https://secure.travis-ci.org/thlorenz/tap-stream.png)](http://travis-ci.org/thlorenz/tap-stream)\n\nTaps a nodejs stream and logs the data that's coming through.\n\n npm install tap-stream\n\nGiven an [object stream](#object-stream) we can print out objects passing through and control the detail via the\ndepth parameter:\n\n```javascript\nobjectStream().pipe(tap(0));\n```\n\n![depth0](https://github.com/thlorenz/tap-stream/raw/master/assets/depth0.png)\n\n```javascript\nobjectStream().pipe(tap(1));\n```\n\n![depth1](https://github.com/thlorenz/tap-stream/raw/master/assets/depth1.png)\n\n```\nobjectStream().pipe(tap(2));\n```\n\n![depth2](https://github.com/thlorenz/tap-stream/raw/master/assets/depth2.png)\n\nFor even more control a custom log function may be supplied:\n\n```javascript\nobjectStream()\n .pipe(tap(function customLog (data) {\n var nest = data.nest;\n console.log ('Bird: %s, id: %s, age: %s, layed egg: %s', nest.name, data.id, nest.age, nest.egg !== undefined);\n })\n );\n```\n\n```text\nBird: yellow rumped warbler, id: 0, age: 1, layed egg: true\nBird: yellow rumped warbler, id: 1, age: 1, layed egg: true\n```\n\n## API\n\n### tap( [ depth | log ] )\n\nIntercepts the stream and logs data that is passing through.\n\n- optional parameter is either a `Number` or a `Function`\n- if no parameter is given, `depth` defaults to `0` and `log` to `console.log(util.inspect(..))`\n\n- `depth` controls the `depth` with which\n [util.inspect](http://nodejs.org/api/util.html#util_util_inspect_object_showhidden_depth_colors) is called\n- `log` replaces the default logging function with a custom one\n\n**Example:**\n\n```javascript\nvar tap = require('tap-stream');\n\nmyStream\n .pipe(tap(1)) // log intermediate results\n .pipe(..) // continute manipulating the data\n```\n\n## Object stream\n\nIncluded in order to give context for above examples.\n\n```javascript\nfunction objectStream () {\n var s = new Stream()\n , objects = 0;\n \n var iv = setInterval(\n function () {\n s.emit('data', { \n id: objects\n , created: new Date()\n , nest: { \n name: 'yellow rumped warbler'\n , age: 1\n , egg: { name: 'unknown' , age: 0 }\n } \n }\n , 4\n );\n\n if (++objects === 2) {\n s.emit('end');\n clearInterval(iv);\n }\n }\n , 200);\n return s;\n}\n```\n", + "_id": "tap-stream@0.1.0", + "_from": "tap-stream@~0.1.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/test/tap-stream.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/test/tap-stream.js new file mode 100644 index 000000000..b484fcb7d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/node_modules/tap-stream/test/tap-stream.js @@ -0,0 +1,104 @@ +'use strict'; +/*jshint asi: true */ + +var test = require('tap').test + , Stream = require('stream') + , tap = require('..') + , through = require('through'); + +function objectStream () { + var s = new Stream() + , objects = 0; + + var iv = setInterval( + function () { + s.emit('data', { id: objects, created: new Date() }); + + if (++objects === 2) { + s.emit('end'); + clearInterval(iv); + } + } + , 20); + return s; +} + +test('tapping object stream that emits 2 objects', function (t) { + var logged = [] + , piped = []; + + function log (data) { + logged.push(data); + } + + t.plan(4); + + objectStream() + .pipe(tap(log)) + .pipe(through( + function write (data) { + piped.push(data); + this.emit('data', data); + } + , function end (data) { + + t.equals(0, logged[0].id, 'logs first item'); + t.equals(1, logged[1].id, 'logs second item'); + + t.equals(0, piped[0].id, 'pipes first item'); + t.equals(1, piped[1].id, 'pipes second item'); + + t.end(); + + this.emit('end'); + } + )) +}) + +/* The below doesn't work since pipe only writes one argument: + * https://github.com/joyent/node/blob/master/lib/stream.js#L36 + * + * Since it uses EventEmitter whose 'emit' supports multiple args, this may change in the future - I hope so. + * Until then ... + */ +var onDataInsidePipeWritesMultipleArgs = false; + +if (! onDataInsidePipeWritesMultipleArgs) return; + +function numberStream () { + var s = new Stream(); + + setTimeout( + function () { + s.emit('data', 1, 2); + s.emit('end'); + } + , 20); + return s; +} + +test('tapping stream that emits a number and a string one time', function (t) { + var logged = [] + , piped = []; + + function log (n1, n2) { + logged.push({ n1: n1, n2: n2 }); + } + + t.plan(2); + + numberStream() + .pipe(tap(log)) + .pipe(through( + function write (n1, n2) { + piped.push({ n1: n1, n2: n2 }); + } + , function end () { + t.equals({ n1: 1, n2: 2 }, logged[0], 'logs both numbers'); + t.equals({ n1: 1, n2: 2 }, piped[0], 'pipes both numbers'); + t.end(); + + this.emit('end'); + } + )) +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/package.json new file mode 100644 index 000000000..2d9b34119 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/package.json @@ -0,0 +1,9 @@ +{ + "name": "readdirp-examples", + "version": "0.0.0", + "description": "Examples for readdirp.", + "dependencies": { + "tap-stream": "~0.1.0", + "event-stream": "~3.0.7" + } +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api-pipe.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api-pipe.js new file mode 100644 index 000000000..b09fe5965 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api-pipe.js @@ -0,0 +1,13 @@ +var readdirp = require('..') + , path = require('path') + , es = require('event-stream'); + +// print out all JavaScript files along with their size +readdirp({ root: path.join(__dirname), fileFilter: '*.js' }) + .on('warn', function (err) { console.error('non-fatal error', err); }) + .on('error', function (err) { console.error('fatal error', err); }) + .pipe(es.mapSync(function (entry) { + return { path: entry.path, size: entry.stat.size }; + })) + .pipe(es.stringify()) + .pipe(process.stdout); diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api.js new file mode 100644 index 000000000..0f7b327eb --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/examples/stream-api.js @@ -0,0 +1,15 @@ +var readdirp = require('..') + , path = require('path'); + +readdirp({ root: path.join(__dirname), fileFilter: '*.js' }) + .on('warn', function (err) { + console.error('something went wrong when processing an entry', err); + }) + .on('error', function (err) { + console.error('something went fatally wrong and the stream was aborted', err); + }) + .on('data', function (entry) { + console.log('%s is ready for processing', entry.path); + // process entry here + }); + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.npmignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.travis.yml b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.travis.yml new file mode 100644 index 000000000..fca8ef019 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.10 + - 0.11 diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/LICENSE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/README.md new file mode 100644 index 000000000..5b3967ea9 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/README.md @@ -0,0 +1,218 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +Eventually, it will replace the C binding in node-glob. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instanting the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +## Functions + +The top-level exported function has a `cache` property, which is an LRU +cache set to store 100 items. So, calling these methods repeatedly +with the same pattern and options will use the same Minimatch object, +saving the cost of parsing it multiple times. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/minimatch.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/minimatch.js new file mode 100644 index 000000000..47617868b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/minimatch.js @@ -0,0 +1,1073 @@ +;(function (require, exports, module, platform) { + +if (module) module.exports = minimatch +else exports.minimatch = minimatch + +if (!require) { + require = function (id) { + switch (id) { + case "sigmund": return function sigmund (obj) { + return JSON.stringify(obj) + } + case "path": return { basename: function (f) { + f = f.split(/[\/\\]/) + var e = f.pop() + if (!e) e = f.pop() + return e + }} + case "lru-cache": return function LRUCache () { + // not quite an LRU, but still space-limited. + var cache = {} + var cnt = 0 + this.set = function (k, v) { + cnt ++ + if (cnt >= 100) cache = {} + cache[k] = v + } + this.get = function (k) { return cache[k] } + } + } + } +} + +minimatch.Minimatch = Minimatch + +var LRU = require("lru-cache") + , cache = minimatch.cache = new LRU({max: 100}) + , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} + , sigmund = require("sigmund") + +var path = require("path") + // any single thing other than / + // don't need to escape / when using new RegExp() + , qmark = "[^/]" + + // * => any number of characters + , star = qmark + "*?" + + // ** when dots are allowed. Anything goes, except .. and . + // not (^ or / followed by one or two dots followed by $ or /), + // followed by anything, any number of times. + , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" + + // not a ^ or / followed by a dot, + // followed by anything, any number of times. + , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" + + // characters that need to be escaped in RegExp. + , reSpecials = charSet("().*{}+?[]^$\\!") + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split("").reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + + +function minimatch (p, pattern, options) { + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required") + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === "#") { + return false + } + + // "" only matches "" + if (pattern.trim() === "") return p === "" + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options, cache) + } + + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required") + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + if (platform === "win32") { + pattern = pattern.split("\\").join("/") + } + + // lru storage. + // these things aren't particularly big, but walking down the string + // and turning it into a regexp can get pretty costly. + var cacheKey = pattern + "\n" + sigmund(options) + var cached = minimatch.cache.get(cacheKey) + if (cached) return cached + minimatch.cache.set(cacheKey, this) + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function() {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return -1 === s.indexOf(false) + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + , negate = false + , options = this.options + , negateOffset = 0 + + if (options.nonegate) return + + for ( var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === "!" + ; i ++) { + negate = !negate + negateOffset ++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return new Minimatch(pattern, options).braceExpand() +} + +Minimatch.prototype.braceExpand = braceExpand + +function pad(n, width, z) { + z = z || '0'; + n = n + ''; + return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; +} + +function braceExpand (pattern, options) { + options = options || this.options + pattern = typeof pattern === "undefined" + ? this.pattern : pattern + + if (typeof pattern === "undefined") { + throw new Error("undefined pattern") + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + var escaping = false + + // examples and comments refer to this crazy pattern: + // a{b,c{d,e},{f,g}h}x{y,z} + // expected: + // abxy + // abxz + // acdxy + // acdxz + // acexy + // acexz + // afhxy + // afhxz + // aghxy + // aghxz + + // everything before the first \{ is just a prefix. + // So, we pluck that off, and work with the rest, + // and then prepend it to everything we find. + if (pattern.charAt(0) !== "{") { + this.debug(pattern) + var prefix = null + for (var i = 0, l = pattern.length; i < l; i ++) { + var c = pattern.charAt(i) + this.debug(i, c) + if (c === "\\") { + escaping = !escaping + } else if (c === "{" && !escaping) { + prefix = pattern.substr(0, i) + break + } + } + + // actually no sets, all { were escaped. + if (prefix === null) { + this.debug("no sets") + return [pattern] + } + + var tail = braceExpand.call(this, pattern.substr(i), options) + return tail.map(function (t) { + return prefix + t + }) + } + + // now we have something like: + // {b,c{d,e},{f,g}h}x{y,z} + // walk through the set, expanding each part, until + // the set ends. then, we'll expand the suffix. + // If the set only has a single member, then'll put the {} back + + // first, handle numeric sets, since they're easier + var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/) + if (numset) { + this.debug("numset", numset[1], numset[2]) + var suf = braceExpand.call(this, pattern.substr(numset[0].length), options) + , start = +numset[1] + , needPadding = numset[1][0] === '0' + , startWidth = numset[1].length + , padded + , end = +numset[2] + , inc = start > end ? -1 : 1 + , set = [] + + for (var i = start; i != (end + inc); i += inc) { + padded = needPadding ? pad(i, startWidth) : i + '' + // append all the suffixes + for (var ii = 0, ll = suf.length; ii < ll; ii ++) { + set.push(padded + suf[ii]) + } + } + return set + } + + // ok, walk through the set + // We hope, somewhat optimistically, that there + // will be a } at the end. + // If the closing brace isn't found, then the pattern is + // interpreted as braceExpand("\\" + pattern) so that + // the leading \{ will be interpreted literally. + var i = 1 // skip the \{ + , depth = 1 + , set = [] + , member = "" + , sawEnd = false + , escaping = false + + function addMember () { + set.push(member) + member = "" + } + + this.debug("Entering for") + FOR: for (i = 1, l = pattern.length; i < l; i ++) { + var c = pattern.charAt(i) + this.debug("", i, c) + + if (escaping) { + escaping = false + member += "\\" + c + } else { + switch (c) { + case "\\": + escaping = true + continue + + case "{": + depth ++ + member += "{" + continue + + case "}": + depth -- + // if this closes the actual set, then we're done + if (depth === 0) { + addMember() + // pluck off the close-brace + i ++ + break FOR + } else { + member += c + continue + } + + case ",": + if (depth === 1) { + addMember() + } else { + member += c + } + continue + + default: + member += c + continue + } // switch + } // else + } // for + + // now we've either finished the set, and the suffix is + // pattern.substr(i), or we have *not* closed the set, + // and need to escape the leading brace + if (depth !== 0) { + this.debug("didn't close", pattern) + return braceExpand.call(this, "\\" + pattern, options) + } + + // x{y,z} -> ["xy", "xz"] + this.debug("set", set) + this.debug("suffix", pattern.substr(i)) + var suf = braceExpand.call(this, pattern.substr(i), options) + // ["b", "c{d,e}","{f,g}h"] -> + // [["b"], ["cd", "ce"], ["fh", "gh"]] + var addBraces = set.length === 1 + this.debug("set pre-expanded", set) + set = set.map(function (p) { + return braceExpand.call(this, p, options) + }, this) + this.debug("set expanded", set) + + + // [["b"], ["cd", "ce"], ["fh", "gh"]] -> + // ["b", "cd", "ce", "fh", "gh"] + set = set.reduce(function (l, r) { + return l.concat(r) + }) + + if (addBraces) { + set = set.map(function (s) { + return "{" + s + "}" + }) + } + + // now attach the suffixes. + var ret = [] + for (var i = 0, l = set.length; i < l; i ++) { + for (var ii = 0, ll = suf.length; ii < ll; ii ++) { + ret.push(set[i] + suf[ii]) + } + } + return ret +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === "**") return GLOBSTAR + if (pattern === "") return "" + + var re = "" + , hasMagic = !!options.nocase + , escaping = false + // ? => one single character + , patternListStack = [] + , plType + , stateChar + , inClass = false + , reClassStart = -1 + , classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + , patternStart = pattern.charAt(0) === "." ? "" // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" + : "(?!\\.)" + , self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case "*": + re += star + hasMagic = true + break + case "?": + re += qmark + hasMagic = true + break + default: + re += "\\"+stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for ( var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i ++ ) { + + this.debug("%s\t%s %s %j", pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += "\\" + c + escaping = false + continue + } + + SWITCH: switch (c) { + case "/": + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case "\\": + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case "?": + case "*": + case "+": + case "@": + case "!": + this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === "!" && i === classStart + 1) c = "^" + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case "(": + if (inClass) { + re += "(" + continue + } + + if (!stateChar) { + re += "\\(" + continue + } + + plType = stateChar + patternListStack.push({ type: plType + , start: i - 1 + , reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === "!" ? "(?:(?!" : "(?:" + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ")": + if (inClass || !patternListStack.length) { + re += "\\)" + continue + } + + clearStateChar() + hasMagic = true + re += ")" + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case "!": + re += "[^/]*?)" + break + case "?": + case "+": + case "*": re += plType + case "@": break // the default anyway + } + continue + + case "|": + if (inClass || !patternListStack.length || escaping) { + re += "\\|" + escaping = false + continue + } + + clearStateChar() + re += "|" + continue + + // these are mostly the same in regexp and glob + case "[": + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += "\\" + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case "]": + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += "\\" + c + escaping = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === "^" && inClass)) { + re += "\\" + } + + re += c + + } // switch + } // for + + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + var cs = pattern.substr(classStart + 1) + , sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + "\\[" + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + var pl + while (pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = "\\" + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + "|" + }) + + this.debug("tail=%j\n %s", tail, tail) + var t = pl.type === "*" ? star + : pl.type === "?" ? qmark + : "\\" + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + + t + "\\(" + + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += "\\\\" + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case ".": + case "[": + case "(": addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== "" && hasMagic) re = "(?=.)" + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [ re, hasMagic ] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? "i" : "" + , regExp = new RegExp("^" + re + "$", flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) return this.regexp = false + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + , flags = options.nocase ? "i" : "" + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === "string") ? regExpEscape(p) + : p._src + }).join("\\\/") + }).join("|") + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = "^(?:" + re + ")$" + + // can match anything, as long as it's not this. + if (this.negate) re = "^(?!" + re + ").*$" + + try { + return this.regexp = new RegExp(re, flags) + } catch (ex) { + return this.regexp = false + } +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug("match", f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === "" + + if (f === "/" && partial) return true + + var options = this.options + + // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + if (platform === "win32") { + f = f.split("\\").join("/") + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, "split", f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, "set", set) + + // Find the basename of the path by looking for the last non-empty segment + var filename; + for (var i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (var i = 0, l = set.length; i < l; i ++) { + var pattern = set[i], file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug("matchOne", + { "this": this + , file: file + , pattern: pattern }) + + this.debug("matchOne", file.length, pattern.length) + + for ( var fi = 0 + , pi = 0 + , fl = file.length + , pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi ++, pi ++ ) { + + this.debug("matchOne loop") + var p = pattern[pi] + , f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + , pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for ( ; fi < fl; fi ++) { + if (file[fi] === "." || file[fi] === ".." || + (!options.dot && file[fi].charAt(0) === ".")) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + WHILE: while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', + file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === "." || swallowee === ".." || + (!options.dot && swallowee.charAt(0) === ".")) { + this.debug("dot detected!", file, fr, pattern, pr) + break WHILE + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr ++ + } + } + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug("\n>>> no match, partial?", file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === "string") { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug("string match", p, f, hit) + } else { + hit = f.match(p) + this.debug("pattern match", p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === "") + return emptyFileEnd + } + + // should be unreachable. + throw new Error("wtf?") +} + + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, "$1") +} + + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") +} + +})( typeof require === "function" ? require : null, + this, + typeof module === "object" ? module : null, + typeof process === "object" ? process.platform : "win32" + ) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/.npmignore new file mode 100644 index 000000000..07e6e472c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/.npmignore @@ -0,0 +1 @@ +/node_modules diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS new file mode 100644 index 000000000..4a0bc5033 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS @@ -0,0 +1,14 @@ +# Authors, sorted by whether or not they are me +Isaac Z. Schlueter +Brian Cottingham +Carlos Brito Lage +Jesse Dailey +Kevin O'Hara +Marco Rogers +Mark Cavage +Marko Mikulicic +Nathan Rajlich +Satheesh Natesan +Trent Mick +ashleybrener +n4kz diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/README.md new file mode 100644 index 000000000..03ee0f985 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/README.md @@ -0,0 +1,97 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n) { return n * 2 } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = LRU(options) + , otherCache = LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n){return n.length}`. The default is + `function(n){return 1}`, which is fine if you want to store `n` + like-sized things. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. + +## API + +* `set(key, value)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js new file mode 100644 index 000000000..d1d138172 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js @@ -0,0 +1,252 @@ +;(function () { // closure for web browsers + +if (typeof module === 'object' && module.exports) { + module.exports = LRUCache +} else { + // just set the global for non-node platforms. + this.LRUCache = LRUCache +} + +function hOP (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key) +} + +function naiveLength () { return 1 } + +function LRUCache (options) { + if (!(this instanceof LRUCache)) + return new LRUCache(options) + + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + this._max = options.max + // Kind of weird to have a default max of Infinity, but oh well. + if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) + this._max = Infinity + + this._lengthCalculator = options.length || naiveLength + if (typeof this._lengthCalculator !== "function") + this._lengthCalculator = naiveLength + + this._allowStale = options.stale || false + this._maxAge = options.maxAge || null + this._dispose = options.dispose + this.reset() +} + +// resize the cache when the max changes. +Object.defineProperty(LRUCache.prototype, "max", + { set : function (mL) { + if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity + this._max = mL + if (this._length > this._max) trim(this) + } + , get : function () { return this._max } + , enumerable : true + }) + +// resize the cache when the lengthCalculator changes. +Object.defineProperty(LRUCache.prototype, "lengthCalculator", + { set : function (lC) { + if (typeof lC !== "function") { + this._lengthCalculator = naiveLength + this._length = this._itemCount + for (var key in this._cache) { + this._cache[key].length = 1 + } + } else { + this._lengthCalculator = lC + this._length = 0 + for (var key in this._cache) { + this._cache[key].length = this._lengthCalculator(this._cache[key].value) + this._length += this._cache[key].length + } + } + + if (this._length > this._max) trim(this) + } + , get : function () { return this._lengthCalculator } + , enumerable : true + }) + +Object.defineProperty(LRUCache.prototype, "length", + { get : function () { return this._length } + , enumerable : true + }) + + +Object.defineProperty(LRUCache.prototype, "itemCount", + { get : function () { return this._itemCount } + , enumerable : true + }) + +LRUCache.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + var i = 0; + for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { + i++ + var hit = this._lruList[k] + if (this._maxAge && (Date.now() - hit.now > this._maxAge)) { + del(this, hit) + if (!this._allowStale) hit = undefined + } + if (hit) { + fn.call(thisp, hit.value, hit.key, this) + } + } +} + +LRUCache.prototype.keys = function () { + var keys = new Array(this._itemCount) + var i = 0 + for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { + var hit = this._lruList[k] + keys[i++] = hit.key + } + return keys +} + +LRUCache.prototype.values = function () { + var values = new Array(this._itemCount) + var i = 0 + for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { + var hit = this._lruList[k] + values[i++] = hit.value + } + return values +} + +LRUCache.prototype.reset = function () { + if (this._dispose && this._cache) { + for (var k in this._cache) { + this._dispose(k, this._cache[k].value) + } + } + + this._cache = Object.create(null) // hash of items by key + this._lruList = Object.create(null) // list of items in order of use recency + this._mru = 0 // most recently used + this._lru = 0 // least recently used + this._length = 0 // number of items in the list + this._itemCount = 0 +} + +// Provided for debugging/dev purposes only. No promises whatsoever that +// this API stays stable. +LRUCache.prototype.dump = function () { + return this._cache +} + +LRUCache.prototype.dumpLru = function () { + return this._lruList +} + +LRUCache.prototype.set = function (key, value) { + if (hOP(this._cache, key)) { + // dispose of the old one before overwriting + if (this._dispose) this._dispose(key, this._cache[key].value) + if (this._maxAge) this._cache[key].now = Date.now() + this._cache[key].value = value + this.get(key) + return true + } + + var len = this._lengthCalculator(value) + var age = this._maxAge ? Date.now() : 0 + var hit = new Entry(key, value, this._mru++, len, age) + + // oversized objects fall out of cache automatically. + if (hit.length > this._max) { + if (this._dispose) this._dispose(key, value) + return false + } + + this._length += hit.length + this._lruList[hit.lu] = this._cache[key] = hit + this._itemCount ++ + + if (this._length > this._max) trim(this) + return true +} + +LRUCache.prototype.has = function (key) { + if (!hOP(this._cache, key)) return false + var hit = this._cache[key] + if (this._maxAge && (Date.now() - hit.now > this._maxAge)) { + return false + } + return true +} + +LRUCache.prototype.get = function (key) { + return get(this, key, true) +} + +LRUCache.prototype.peek = function (key) { + return get(this, key, false) +} + +LRUCache.prototype.pop = function () { + var hit = this._lruList[this._lru] + del(this, hit) + return hit || null +} + +LRUCache.prototype.del = function (key) { + del(this, this._cache[key]) +} + +function get (self, key, doUse) { + var hit = self._cache[key] + if (hit) { + if (self._maxAge && (Date.now() - hit.now > self._maxAge)) { + del(self, hit) + if (!self._allowStale) hit = undefined + } else { + if (doUse) use(self, hit) + } + if (hit) hit = hit.value + } + return hit +} + +function use (self, hit) { + shiftLU(self, hit) + hit.lu = self._mru ++ + self._lruList[hit.lu] = hit +} + +function trim (self) { + while (self._lru < self._mru && self._length > self._max) + del(self, self._lruList[self._lru]) +} + +function shiftLU (self, hit) { + delete self._lruList[ hit.lu ] + while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++ +} + +function del (self, hit) { + if (hit) { + if (self._dispose) self._dispose(hit.key, hit.value) + self._length -= hit.length + self._itemCount -- + delete self._cache[ hit.key ] + shiftLU(self, hit) + } +} + +// classy, since V8 prefers predictable objects. +function Entry (key, value, lu, length, now) { + this.key = key + this.value = value + this.lu = lu + this.length = length + this.now = now +} + +})() diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/package.json new file mode 100644 index 000000000..4472725df --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/package.json @@ -0,0 +1,33 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "2.5.0", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "scripts": { + "test": "tap test --gc" + }, + "main": "lib/lru-cache.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "devDependencies": { + "tap": "", + "weak": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" + }, + "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/node-lru-cache/issues" + }, + "homepage": "https://github.com/isaacs/node-lru-cache", + "_id": "lru-cache@2.5.0", + "_from": "lru-cache@2" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/basic.js new file mode 100644 index 000000000..f72697c46 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/basic.js @@ -0,0 +1,369 @@ +var test = require("tap").test + , LRU = require("../") + +test("basic", function (t) { + var cache = new LRU({max: 10}) + cache.set("key", "value") + t.equal(cache.get("key"), "value") + t.equal(cache.get("nada"), undefined) + t.equal(cache.length, 1) + t.equal(cache.max, 10) + t.end() +}) + +test("least recently set", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), "B") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("lru recently gotten", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + cache.get("a") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), undefined) + t.equal(cache.get("a"), "A") + t.end() +}) + +test("del", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.del("a") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("max", function (t) { + var cache = new LRU(3) + + // test changing the max, verify that the LRU items get dropped. + cache.max = 100 + for (var i = 0; i < 100; i ++) cache.set(i, i) + t.equal(cache.length, 100) + for (var i = 0; i < 100; i ++) { + t.equal(cache.get(i), i) + } + cache.max = 3 + t.equal(cache.length, 3) + for (var i = 0; i < 97; i ++) { + t.equal(cache.get(i), undefined) + } + for (var i = 98; i < 100; i ++) { + t.equal(cache.get(i), i) + } + + // now remove the max restriction, and try again. + cache.max = "hello" + for (var i = 0; i < 100; i ++) cache.set(i, i) + t.equal(cache.length, 100) + for (var i = 0; i < 100; i ++) { + t.equal(cache.get(i), i) + } + // should trigger an immediate resize + cache.max = 3 + t.equal(cache.length, 3) + for (var i = 0; i < 97; i ++) { + t.equal(cache.get(i), undefined) + } + for (var i = 98; i < 100; i ++) { + t.equal(cache.get(i), i) + } + t.end() +}) + +test("reset", function (t) { + var cache = new LRU(10) + cache.set("a", "A") + cache.set("b", "B") + cache.reset() + t.equal(cache.length, 0) + t.equal(cache.max, 10) + t.equal(cache.get("a"), undefined) + t.equal(cache.get("b"), undefined) + t.end() +}) + + +// Note: `.dump()` is a debugging tool only. No guarantees are made +// about the format/layout of the response. +test("dump", function (t) { + var cache = new LRU(10) + var d = cache.dump(); + t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache") + cache.set("a", "A") + var d = cache.dump() // { a: { key: "a", value: "A", lu: 0 } } + t.ok(d.a) + t.equal(d.a.key, "a") + t.equal(d.a.value, "A") + t.equal(d.a.lu, 0) + + cache.set("b", "B") + cache.get("b") + d = cache.dump() + t.ok(d.b) + t.equal(d.b.key, "b") + t.equal(d.b.value, "B") + t.equal(d.b.lu, 2) + + t.end() +}) + + +test("basic with weighed length", function (t) { + var cache = new LRU({ + max: 100, + length: function (item) { return item.size } + }) + cache.set("key", {val: "value", size: 50}) + t.equal(cache.get("key").val, "value") + t.equal(cache.get("nada"), undefined) + t.equal(cache.lengthCalculator(cache.get("key")), 50) + t.equal(cache.length, 50) + t.equal(cache.max, 100) + t.end() +}) + + +test("weighed length item too large", function (t) { + var cache = new LRU({ + max: 10, + length: function (item) { return item.size } + }) + t.equal(cache.max, 10) + + // should fall out immediately + cache.set("key", {val: "value", size: 50}) + + t.equal(cache.length, 0) + t.equal(cache.get("key"), undefined) + t.end() +}) + +test("least recently set with weighed length", function (t) { + var cache = new LRU({ + max:8, + length: function (item) { return item.length } + }) + cache.set("a", "A") + cache.set("b", "BB") + cache.set("c", "CCC") + cache.set("d", "DDDD") + t.equal(cache.get("d"), "DDDD") + t.equal(cache.get("c"), "CCC") + t.equal(cache.get("b"), undefined) + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("lru recently gotten with weighed length", function (t) { + var cache = new LRU({ + max: 8, + length: function (item) { return item.length } + }) + cache.set("a", "A") + cache.set("b", "BB") + cache.set("c", "CCC") + cache.get("a") + cache.get("b") + cache.set("d", "DDDD") + t.equal(cache.get("c"), undefined) + t.equal(cache.get("d"), "DDDD") + t.equal(cache.get("b"), "BB") + t.equal(cache.get("a"), "A") + t.end() +}) + +test("set returns proper booleans", function(t) { + var cache = new LRU({ + max: 5, + length: function (item) { return item.length } + }) + + t.equal(cache.set("a", "A"), true) + + // should return false for max exceeded + t.equal(cache.set("b", "donuts"), false) + + t.equal(cache.set("b", "B"), true) + t.equal(cache.set("c", "CCCC"), true) + t.end() +}) + +test("drop the old items", function(t) { + var cache = new LRU({ + max: 5, + maxAge: 50 + }) + + cache.set("a", "A") + + setTimeout(function () { + cache.set("b", "b") + t.equal(cache.get("a"), "A") + }, 25) + + setTimeout(function () { + cache.set("c", "C") + // timed out + t.notOk(cache.get("a")) + }, 60) + + setTimeout(function () { + t.notOk(cache.get("b")) + t.equal(cache.get("c"), "C") + }, 90) + + setTimeout(function () { + t.notOk(cache.get("c")) + t.end() + }, 155) +}) + +test("disposal function", function(t) { + var disposed = false + var cache = new LRU({ + max: 1, + dispose: function (k, n) { + disposed = n + } + }) + + cache.set(1, 1) + cache.set(2, 2) + t.equal(disposed, 1) + cache.set(3, 3) + t.equal(disposed, 2) + cache.reset() + t.equal(disposed, 3) + t.end() +}) + +test("disposal function on too big of item", function(t) { + var disposed = false + var cache = new LRU({ + max: 1, + length: function (k) { + return k.length + }, + dispose: function (k, n) { + disposed = n + } + }) + var obj = [ 1, 2 ] + + t.equal(disposed, false) + cache.set("obj", obj) + t.equal(disposed, obj) + t.end() +}) + +test("has()", function(t) { + var cache = new LRU({ + max: 1, + maxAge: 10 + }) + + cache.set('foo', 'bar') + t.equal(cache.has('foo'), true) + cache.set('blu', 'baz') + t.equal(cache.has('foo'), false) + t.equal(cache.has('blu'), true) + setTimeout(function() { + t.equal(cache.has('blu'), false) + t.end() + }, 15) +}) + +test("stale", function(t) { + var cache = new LRU({ + maxAge: 10, + stale: true + }) + + cache.set('foo', 'bar') + t.equal(cache.get('foo'), 'bar') + t.equal(cache.has('foo'), true) + setTimeout(function() { + t.equal(cache.has('foo'), false) + t.equal(cache.get('foo'), 'bar') + t.equal(cache.get('foo'), undefined) + t.end() + }, 15) +}) + +test("lru update via set", function(t) { + var cache = LRU({ max: 2 }); + + cache.set('foo', 1); + cache.set('bar', 2); + cache.del('bar'); + cache.set('baz', 3); + cache.set('qux', 4); + + t.equal(cache.get('foo'), undefined) + t.equal(cache.get('bar'), undefined) + t.equal(cache.get('baz'), 3) + t.equal(cache.get('qux'), 4) + t.end() +}) + +test("least recently set w/ peek", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + t.equal(cache.peek("a"), "A") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), "B") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("pop the least used item", function (t) { + var cache = new LRU(3) + , last + + cache.set("a", "A") + cache.set("b", "B") + cache.set("c", "C") + + t.equal(cache.length, 3) + t.equal(cache.max, 3) + + // Ensure we pop a, c, b + cache.get("b", "B") + + last = cache.pop() + t.equal(last.key, "a") + t.equal(last.value, "A") + t.equal(cache.length, 2) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last.key, "c") + t.equal(last.value, "C") + t.equal(cache.length, 1) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last.key, "b") + t.equal(last.value, "B") + t.equal(cache.length, 0) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last, null) + t.equal(cache.length, 0) + t.equal(cache.max, 3) + + t.end() +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/foreach.js new file mode 100644 index 000000000..eefb80d9d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/foreach.js @@ -0,0 +1,52 @@ +var test = require('tap').test +var LRU = require('../') + +test('forEach', function (t) { + var l = new LRU(5) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + var i = 9 + l.forEach(function (val, key, cache) { + t.equal(cache, l) + t.equal(key, i.toString()) + t.equal(val, i.toString(2)) + i -= 1 + }) + + // get in order of most recently used + l.get(6) + l.get(8) + + var order = [ 8, 6, 9, 7, 5 ] + var i = 0 + + l.forEach(function (val, key, cache) { + var j = order[i ++] + t.equal(cache, l) + t.equal(key, j.toString()) + t.equal(val, j.toString(2)) + }) + + t.end() +}) + +test('keys() and values()', function (t) { + var l = new LRU(5) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + t.similar(l.keys(), ['9', '8', '7', '6', '5']) + t.similar(l.values(), ['1001', '1000', '111', '110', '101']) + + // get in order of most recently used + l.get(6) + l.get(8) + + t.similar(l.keys(), ['8', '6', '9', '7', '5']) + t.similar(l.values(), ['1000', '110', '1001', '111', '101']) + + t.end() +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js new file mode 100644 index 000000000..7af45b022 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js @@ -0,0 +1,50 @@ +#!/usr/bin/env node --expose_gc + +var weak = require('weak'); +var test = require('tap').test +var LRU = require('../') +var l = new LRU({ max: 10 }) +var refs = 0 +function X() { + refs ++ + weak(this, deref) +} + +function deref() { + refs -- +} + +test('no leaks', function (t) { + // fill up the cache + for (var i = 0; i < 100; i++) { + l.set(i, new X); + // throw some gets in there, too. + if (i % 2 === 0) + l.get(i / 2) + } + + gc() + + var start = process.memoryUsage() + + // capture the memory + var startRefs = refs + + // do it again, but more + for (var i = 0; i < 10000; i++) { + l.set(i, new X); + // throw some gets in there, too. + if (i % 2 === 0) + l.get(i / 2) + } + + gc() + + var end = process.memoryUsage() + t.equal(refs, startRefs, 'no leaky refs') + + console.error('start: %j\n' + + 'end: %j', start, end); + t.pass(); + t.end(); +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/LICENSE b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/LICENSE new file mode 100644 index 000000000..0c44ae716 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/README.md b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/README.md new file mode 100644 index 000000000..7e365129e --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/README.md @@ -0,0 +1,53 @@ +# sigmund + +Quick and dirty signatures for Objects. + +This is like a much faster `deepEquals` comparison, which returns a +string key suitable for caches and the like. + +## Usage + +```javascript +function doSomething (someObj) { + var key = sigmund(someObj, maxDepth) // max depth defaults to 10 + var cached = cache.get(key) + if (cached) return cached) + + var result = expensiveCalculation(someObj) + cache.set(key, result) + return result +} +``` + +The resulting key will be as unique and reproducible as calling +`JSON.stringify` or `util.inspect` on the object, but is much faster. +In order to achieve this speed, some differences are glossed over. +For example, the object `{0:'foo'}` will be treated identically to the +array `['foo']`. + +Also, just as there is no way to summon the soul from the scribblings +of a cocain-addled psychoanalyst, there is no way to revive the object +from the signature string that sigmund gives you. In fact, it's +barely even readable. + +As with `sys.inspect` and `JSON.stringify`, larger objects will +produce larger signature strings. + +Because sigmund is a bit less strict than the more thorough +alternatives, the strings will be shorter, and also there is a +slightly higher chance for collisions. For example, these objects +have the same signature: + + var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} + var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} + +Like a good Freudian, sigmund is most effective when you already have +some understanding of what you're looking for. It can help you help +yourself, but you must be willing to do some work as well. + +Cycles are handled, and cyclical objects are silently omitted (though +the key is included in the signature output.) + +The second argument is the maximum depth, which defaults to 10, +because that is the maximum object traversal depth covered by most +insurance carriers. diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/bench.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/bench.js new file mode 100644 index 000000000..5acfd6d90 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/bench.js @@ -0,0 +1,283 @@ +// different ways to id objects +// use a req/res pair, since it's crazy deep and cyclical + +// sparseFE10 and sigmund are usually pretty close, which is to be expected, +// since they are essentially the same algorithm, except that sigmund handles +// regular expression objects properly. + + +var http = require('http') +var util = require('util') +var sigmund = require('./sigmund.js') +var sreq, sres, creq, cres, test + +http.createServer(function (q, s) { + sreq = q + sres = s + sres.end('ok') + this.close(function () { setTimeout(function () { + start() + }, 200) }) +}).listen(1337, function () { + creq = http.get({ port: 1337 }) + creq.on('response', function (s) { cres = s }) +}) + +function start () { + test = [sreq, sres, creq, cres] + // test = sreq + // sreq.sres = sres + // sreq.creq = creq + // sreq.cres = cres + + for (var i in exports.compare) { + console.log(i) + var hash = exports.compare[i]() + console.log(hash) + console.log(hash.length) + console.log('') + } + + require('bench').runMain() +} + +function customWs (obj, md, d) { + d = d || 0 + var to = typeof obj + if (to === 'undefined' || to === 'function' || to === null) return '' + if (d > md || !obj || to !== 'object') return ('' + obj).replace(/[\n ]+/g, '') + + if (Array.isArray(obj)) { + return obj.map(function (i, _, __) { + return customWs(i, md, d + 1) + }).reduce(function (a, b) { return a + b }, '') + } + + var keys = Object.keys(obj) + return keys.map(function (k, _, __) { + return k + ':' + customWs(obj[k], md, d + 1) + }).reduce(function (a, b) { return a + b }, '') +} + +function custom (obj, md, d) { + d = d || 0 + var to = typeof obj + if (to === 'undefined' || to === 'function' || to === null) return '' + if (d > md || !obj || to !== 'object') return '' + obj + + if (Array.isArray(obj)) { + return obj.map(function (i, _, __) { + return custom(i, md, d + 1) + }).reduce(function (a, b) { return a + b }, '') + } + + var keys = Object.keys(obj) + return keys.map(function (k, _, __) { + return k + ':' + custom(obj[k], md, d + 1) + }).reduce(function (a, b) { return a + b }, '') +} + +function sparseFE2 (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + Object.keys(v).forEach(function (k, _, __) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') return + var to = typeof v[k] + if (to === 'function' || to === 'undefined') return + soFar += k + ':' + ch(v[k], depth + 1) + }) + soFar += '}' + } + ch(obj, 0) + return soFar +} + +function sparseFE (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + Object.keys(v).forEach(function (k, _, __) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') return + var to = typeof v[k] + if (to === 'function' || to === 'undefined') return + soFar += k + ch(v[k], depth + 1) + }) + } + ch(obj, 0) + return soFar +} + +function sparse (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ch(v[k], depth + 1) + } + } + ch(obj, 0) + return soFar +} + +function noCommas (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ':' + ch(v[k], depth + 1) + } + soFar += '}' + } + ch(obj, 0) + return soFar +} + + +function flatten (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ':' + ch(v[k], depth + 1) + soFar += ',' + } + soFar += '}' + } + ch(obj, 0) + return soFar +} + +exports.compare = +{ + // 'custom 2': function () { + // return custom(test, 2, 0) + // }, + // 'customWs 2': function () { + // return customWs(test, 2, 0) + // }, + 'JSON.stringify (guarded)': function () { + var seen = [] + return JSON.stringify(test, function (k, v) { + if (typeof v !== 'object' || !v) return v + if (seen.indexOf(v) !== -1) return undefined + seen.push(v) + return v + }) + }, + + 'flatten 10': function () { + return flatten(test, 10) + }, + + // 'flattenFE 10': function () { + // return flattenFE(test, 10) + // }, + + 'noCommas 10': function () { + return noCommas(test, 10) + }, + + 'sparse 10': function () { + return sparse(test, 10) + }, + + 'sparseFE 10': function () { + return sparseFE(test, 10) + }, + + 'sparseFE2 10': function () { + return sparseFE2(test, 10) + }, + + sigmund: function() { + return sigmund(test, 10) + }, + + + // 'util.inspect 1': function () { + // return util.inspect(test, false, 1, false) + // }, + // 'util.inspect undefined': function () { + // util.inspect(test) + // }, + // 'util.inspect 2': function () { + // util.inspect(test, false, 2, false) + // }, + // 'util.inspect 3': function () { + // util.inspect(test, false, 3, false) + // }, + // 'util.inspect 4': function () { + // util.inspect(test, false, 4, false) + // }, + // 'util.inspect Infinity': function () { + // util.inspect(test, false, Infinity, false) + // } +} + +/** results +**/ diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/package.json new file mode 100644 index 000000000..cb7e2bd4b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/package.json @@ -0,0 +1,42 @@ +{ + "name": "sigmund", + "version": "1.0.0", + "description": "Quick and dirty signatures for Objects.", + "main": "sigmund.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "~0.3.0" + }, + "scripts": { + "test": "tap test/*.js", + "bench": "node bench.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/sigmund" + }, + "keywords": [ + "object", + "signature", + "key", + "data", + "psychoanalysis" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "BSD", + "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/sigmund/issues" + }, + "homepage": "https://github.com/isaacs/sigmund", + "_id": "sigmund@1.0.0", + "_from": "sigmund@~1.0.0" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/sigmund.js new file mode 100644 index 000000000..82c7ab8ce --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/sigmund.js @@ -0,0 +1,39 @@ +module.exports = sigmund +function sigmund (subject, maxSessions) { + maxSessions = maxSessions || 10; + var notes = []; + var analysis = ''; + var RE = RegExp; + + function psychoAnalyze (subject, session) { + if (session > maxSessions) return; + + if (typeof subject === 'function' || + typeof subject === 'undefined') { + return; + } + + if (typeof subject !== 'object' || !subject || + (subject instanceof RE)) { + analysis += subject; + return; + } + + if (notes.indexOf(subject) !== -1 || session === maxSessions) return; + + notes.push(subject); + analysis += '{'; + Object.keys(subject).forEach(function (issue, _, __) { + // pseudo-private values. skip those. + if (issue.charAt(0) === '_') return; + var to = typeof subject[issue]; + if (to === 'function' || to === 'undefined') return; + analysis += issue; + psychoAnalyze(subject[issue], session + 1); + }); + } + psychoAnalyze(subject, 0); + return analysis; +} + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/test/basic.js new file mode 100644 index 000000000..50c53a13e --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/node_modules/sigmund/test/basic.js @@ -0,0 +1,24 @@ +var test = require('tap').test +var sigmund = require('../sigmund.js') + + +// occasionally there are duplicates +// that's an acceptable edge-case. JSON.stringify and util.inspect +// have some collision potential as well, though less, and collision +// detection is expensive. +var hash = '{abc/def/g{0h1i2{jkl' +var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} +var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} + +var obj3 = JSON.parse(JSON.stringify(obj1)) +obj3.c = /def/ +obj3.g[2].cycle = obj3 +var cycleHash = '{abc/def/g{0h1i2{jklcycle' + +test('basic', function (t) { + t.equal(sigmund(obj1), hash) + t.equal(sigmund(obj2), hash) + t.equal(sigmund(obj3), cycleHash) + t.end() +}) + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/package.json new file mode 100644 index 000000000..305a14b04 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/package.json @@ -0,0 +1,40 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap test/*.js" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "devDependencies": { + "tap": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" + }, + "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\nminimatch(\"bar.foo\", \"*.+(bar|foo)\", { debug: true }) // true, and noisy!\n```\n\n## Features\n\nSupports these glob features:\n\n* Brace Expansion\n* Extended glob matching\n* \"Globstar\" `**` matching\n\nSee:\n\n* `man sh`\n* `man bash`\n* `man 3 fnmatch`\n* `man 5 gitignore`\n\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself if this option is set. When not set, an empty list\nis returned if there are no matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated. Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally. This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`. Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything. Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set. This is supported in the manner of bsdglob\nand bash 4.1, where `**` only has special significance if it is the only\nthing in a path part. That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`. This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern. Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity. Since those two are valid, matching proceeds.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "homepage": "https://github.com/isaacs/minimatch", + "_id": "minimatch@1.0.0", + "_from": "minimatch@>=0.2.4" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/basic.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/basic.js new file mode 100644 index 000000000..ae7ac73c7 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/basic.js @@ -0,0 +1,399 @@ +// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test +// +// TODO: Some of these tests do very bad things with backslashes, and will +// most likely fail badly on windows. They should probably be skipped. + +var tap = require("tap") + , globalBefore = Object.keys(global) + , mm = require("../") + , files = [ "a", "b", "c", "d", "abc" + , "abd", "abe", "bb", "bcd" + , "ca", "cb", "dd", "de" + , "bdir/", "bdir/cfile"] + , next = files.concat([ "a-b", "aXb" + , ".x", ".y" ]) + + +var patterns = + [ "http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test" + , ["a*", ["a", "abc", "abd", "abe"]] + , ["X*", ["X*"], {nonull: true}] + + // allow null glob expansion + , ["X*", []] + + // isaacs: Slightly different than bash/sh/ksh + // \\* is not un-escaped to literal "*" in a failed match, + // but it does make it get treated as a literal star + , ["\\*", ["\\*"], {nonull: true}] + , ["\\**", ["\\**"], {nonull: true}] + , ["\\*\\*", ["\\*\\*"], {nonull: true}] + + , ["b*/", ["bdir/"]] + , ["c*", ["c", "ca", "cb"]] + , ["**", files] + + , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] + , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] + + , "legendary larry crashes bashes" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] + + , "character classes" + , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] + , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", + "bdir/", "ca", "cb", "dd", "de"]] + , ["a*[^c]", ["abd", "abe"]] + , function () { files.push("a-b", "aXb") } + , ["a[X-]b", ["a-b", "aXb"]] + , function () { files.push(".x", ".y") } + , ["[^a-c]*", ["d", "dd", "de"]] + , function () { files.push("a*b/", "a*b/ooo") } + , ["a\\*b/*", ["a*b/ooo"]] + , ["a\\*?/*", ["a*b/ooo"]] + , ["*\\\\!*", [], {null: true}, ["echo !7"]] + , ["*\\!*", ["echo !7"], null, ["echo !7"]] + , ["*.\\*", ["r.*"], null, ["r.*"]] + , ["a[b]c", ["abc"]] + , ["a[\\b]c", ["abc"]] + , ["a?c", ["abc"]] + , ["a\\*c", [], {null: true}, ["abc"]] + , ["", [""], { null: true }, [""]] + + , "http://www.opensource.apple.com/source/bash/bash-23/" + + "bash/tests/glob-test" + , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } + , ["*/man*/bash.*", ["man/man1/bash.1"]] + , ["man/man1/bash.1", ["man/man1/bash.1"]] + , ["a***c", ["abc"], null, ["abc"]] + , ["a*****?c", ["abc"], null, ["abc"]] + , ["?*****??", ["abc"], null, ["abc"]] + , ["*****??", ["abc"], null, ["abc"]] + , ["?*****?c", ["abc"], null, ["abc"]] + , ["?***?****c", ["abc"], null, ["abc"]] + , ["?***?****?", ["abc"], null, ["abc"]] + , ["?***?****", ["abc"], null, ["abc"]] + , ["*******c", ["abc"], null, ["abc"]] + , ["*******?", ["abc"], null, ["abc"]] + , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["[-abc]", ["-"], null, ["-"]] + , ["[abc-]", ["-"], null, ["-"]] + , ["\\", ["\\"], null, ["\\"]] + , ["[\\\\]", ["\\"], null, ["\\"]] + , ["[[]", ["["], null, ["["]] + , ["[", ["["], null, ["["]] + , ["[*", ["[abc"], null, ["[abc"]] + , "a right bracket shall lose its special meaning and\n" + + "represent itself in a bracket expression if it occurs\n" + + "first in the list. -- POSIX.2 2.8.3.2" + , ["[]]", ["]"], null, ["]"]] + , ["[]-]", ["]"], null, ["]"]] + , ["[a-\z]", ["p"], null, ["p"]] + , ["??**********?****?", [], { null: true }, ["abc"]] + , ["??**********?****c", [], { null: true }, ["abc"]] + , ["?************c****?****", [], { null: true }, ["abc"]] + , ["*c*?**", [], { null: true }, ["abc"]] + , ["a*****c*?**", [], { null: true }, ["abc"]] + , ["a********???*******", [], { null: true }, ["abc"]] + , ["[]", [], { null: true }, ["a"]] + , ["[abc", [], { null: true }, ["["]] + + , "nocase tests" + , ["XYZ", ["xYz"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["ab*", ["ABC"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + + // [ pattern, [matches], MM opts, files, TAP opts] + , "onestar/twostar" + , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] + , ["{/?,*}", ["/a", "bb"], {null: true} + , ["/a", "/b/b", "/a/b/c", "bb"]] + + , "dots should not match unless requested" + , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] + + // .. and . can only match patterns starting with ., + // even when options.dot is set. + , function () { + files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] + } + , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] + , ["a/*/b", ["a/c/b"], {dot:false}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] + + + // this also tests that changing the options needs + // to change the cache key, even if the pattern is + // the same! + , ["**", ["a/b","a/.d",".a/.d"], { dot: true } + , [ ".a/.d", "a/.d", "a/b"]] + + , "paren sets cannot contain slashes" + , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] + + // brace sets trump all else. + // + // invalid glob pattern. fails on bash4 and bsdglob. + // however, in this implementation, it's easier just + // to do the intuitive thing, and let brace-expansion + // actually come before parsing any extglob patterns, + // like the documentation seems to say. + // + // XXX: if anyone complains about this, either fix it + // or tell them to grow up and stop complaining. + // + // bash/bsdglob says this: + // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] + // but we do this instead: + , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] + + // test partial parsing in the presence of comment/negation chars + , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] + , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] + + // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. + , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] + , {} + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] + + + // crazy nested {,,} and *(||) tests. + , function () { + files = [ "a", "b", "c", "d" + , "ab", "ac", "ad" + , "bc", "cb" + , "bc,d", "c,db", "c,d" + , "d)", "(b|c", "*(b|c" + , "b|c", "b|cc", "cb|c" + , "x(a|b|c)", "x(a|c)" + , "(a|b|c)", "(a|c)"] + } + , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] + , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] + // a + // *(b|c) + // *(b|d) + , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] + , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] + + + // test various flag settings. + , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] + , { noext: true } ] + , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} + , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] + , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] + + + // begin channelling Boole and deMorgan... + , "negation tests" + , function () { + files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] + } + + // anything that is NOT a* matches. + , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] + + // anything that IS !a* matches. + , ["!a*", ["!ab", "!abc"], {nonegate: true}] + + // anything that IS a* matches + , ["!!a*", ["a!b"]] + + // anything that is NOT !a* matches + , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] + + // negation nestled within a pattern + , function () { + files = [ "foo.js" + , "foo.bar" + // can't match this one without negative lookbehind. + , "foo.js.js" + , "blar.js" + , "foo." + , "boo.js.boo" ] + } + , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] + + // https://github.com/isaacs/minimatch/issues/5 + , function () { + files = [ 'a/b/.x/c' + , 'a/b/.x/c/d' + , 'a/b/.x/c/d/e' + , 'a/b/.x' + , 'a/b/.x/' + , 'a/.x/b' + , '.x' + , '.x/' + , '.x/a' + , '.x/a/b' + , 'a/.x/b/.x/c' + , '.x/.x' ] + } + , ["**/.x/**", [ '.x/' + , '.x/a' + , '.x/a/b' + , 'a/.x/b' + , 'a/b/.x/' + , 'a/b/.x/c' + , 'a/b/.x/c/d' + , 'a/b/.x/c/d/e' ] ] + + ] + +var regexps = + [ '/^(?:(?=.)a[^/]*?)$/', + '/^(?:(?=.)X[^/]*?)$/', + '/^(?:(?=.)X[^/]*?)$/', + '/^(?:\\*)$/', + '/^(?:(?=.)\\*[^/]*?)$/', + '/^(?:\\*\\*)$/', + '/^(?:(?=.)b[^/]*?\\/)$/', + '/^(?:(?=.)c[^/]*?)$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', + '/^(?:\\.\\.\\/(?!\\.)(?=.)[^/]*?\\/)$/', + '/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/', + '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/', + '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/', + '/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[a-y][^/]*?[^c])$/', + '/^(?:(?=.)a[^/]*?[^c])$/', + '/^(?:(?=.)a[X-]b)$/', + '/^(?:(?!\\.)(?=.)[^a-c][^/]*?)$/', + '/^(?:a\\*b\\/(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?=.)a\\*[^/]\\/(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\\\\\![^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\![^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\.\\*)$/', + '/^(?:(?=.)a[b]c)$/', + '/^(?:(?=.)a[b]c)$/', + '/^(?:(?=.)a[^/]c)$/', + '/^(?:a\\*c)$/', + 'false', + '/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/', + '/^(?:man\\/man1\\/bash\\.1)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?=.)a[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k[^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[-abc])$/', + '/^(?:(?!\\.)(?=.)[abc-])$/', + '/^(?:\\\\)$/', + '/^(?:(?!\\.)(?=.)[\\\\])$/', + '/^(?:(?!\\.)(?=.)[\\[])$/', + '/^(?:\\[)$/', + '/^(?:(?=.)\\[(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[\\]])$/', + '/^(?:(?!\\.)(?=.)[\\]-])$/', + '/^(?:(?!\\.)(?=.)[a-z])$/', + '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:\\[\\])$/', + '/^(?:\\[abc)$/', + '/^(?:(?=.)XYZ)$/i', + '/^(?:(?=.)ab[^/]*?)$/i', + '/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i', + '/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/', + '/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', + '/^(?:a\\/(?!(?:^|\\/)\\.{1,2}(?:$|\\/))(?=.)[^/]*?\\/b)$/', + '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', + '/^(?:a\\/(?!\\.)(?=.)[^/]*?\\/b)$/', + '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', + '/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\/b\\))$/', + '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:(?=.)\\[(?=.)\\!a[^/]*?)$/', + '/^(?:(?=.)\\[(?=.)#a[^/]*?)$/', + '/^(?:(?=.)\\+\\(a\\|[^/]*?\\|c\\\\\\\\\\|d\\\\\\\\\\|e\\\\\\\\\\\\\\\\\\|f\\\\\\\\\\\\\\\\\\|g)$/', + '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:a|(?!\\.)(?=.)[^/]*?\\(b\\|c|d\\))$/', + '/^(?:a|(?!\\.)(?=.)(?:b|c)*|(?!\\.)(?=.)(?:b|d)*)$/', + '/^(?:(?!\\.)(?=.)(?:a|b|c)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\|b\\|c\\)|(?!\\.)(?=.)[^/]*?\\(a\\|c\\))$/', + '/^(?:(?=.)a[^/]b)$/', + '/^(?:(?=.)#[^/]*?)$/', + '/^(?!^(?:(?=.)a[^/]*?)$).*$/', + '/^(?:(?=.)\\!a[^/]*?)$/', + '/^(?:(?=.)a[^/]*?)$/', + '/^(?!^(?:(?=.)\\!a[^/]*?)$).*$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\.(?:(?!js)[^/]*?))$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?\\/\\.x\\/(?:(?!(?:\\/|^)\\.).)*?)$/' ] +var re = 0; + +tap.test("basic tests", function (t) { + var start = Date.now() + + // [ pattern, [matches], MM opts, files, TAP opts] + patterns.forEach(function (c) { + if (typeof c === "function") return c() + if (typeof c === "string") return t.comment(c) + + var pattern = c[0] + , expect = c[1].sort(alpha) + , options = c[2] || {} + , f = c[3] || files + , tapOpts = c[4] || {} + + // options.debug = true + var m = new mm.Minimatch(pattern, options) + var r = m.makeRe() + var expectRe = regexps[re++] + tapOpts.re = String(r) || JSON.stringify(r) + tapOpts.files = JSON.stringify(f) + tapOpts.pattern = pattern + tapOpts.set = m.set + tapOpts.negated = m.negate + + var actual = mm.match(f, pattern, options) + actual.sort(alpha) + + t.equivalent( actual, expect + , JSON.stringify(pattern) + " " + JSON.stringify(expect) + , tapOpts ) + + t.equal(tapOpts.re, expectRe, tapOpts) + }) + + t.comment("time=" + (Date.now() - start) + "ms") + t.end() +}) + +tap.test("global leak test", function (t) { + var globalAfter = Object.keys(global) + t.equivalent(globalAfter, globalBefore, "no new globals, please") + t.end() +}) + +function alpha (a, b) { + return a > b ? 1 : -1 +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/brace-expand.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/brace-expand.js new file mode 100644 index 000000000..e63d3f60c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/brace-expand.js @@ -0,0 +1,40 @@ +var tap = require("tap") + , minimatch = require("../") + +tap.test("brace expansion", function (t) { + // [ pattern, [expanded] ] + ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" + , [ "abxy" + , "abxz" + , "acdxy" + , "acdxz" + , "acexy" + , "acexz" + , "afhxy" + , "afhxz" + , "aghxy" + , "aghxz" ] ] + , [ "a{1..5}b" + , [ "a1b" + , "a2b" + , "a3b" + , "a4b" + , "a5b" ] ] + , [ "a{b}c", ["a{b}c"] ] + , [ "a{00..05}b" + , ["a00b" + ,"a01b" + ,"a02b" + ,"a03b" + ,"a04b" + ,"a05b" ] ] + ].forEach(function (tc) { + var p = tc[0] + , expect = tc[1] + t.equivalent(minimatch.braceExpand(p), expect, p) + }) + console.error("ending") + t.end() +}) + + diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/caching.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/caching.js new file mode 100644 index 000000000..0fec4b0fa --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/caching.js @@ -0,0 +1,14 @@ +var Minimatch = require("../minimatch.js").Minimatch +var tap = require("tap") +tap.test("cache test", function (t) { + var mm1 = new Minimatch("a?b") + var mm2 = new Minimatch("a?b") + t.equal(mm1, mm2, "should get the same object") + // the lru should drop it after 100 entries + for (var i = 0; i < 100; i ++) { + new Minimatch("a"+i) + } + mm2 = new Minimatch("a?b") + t.notEqual(mm1, mm2, "cache should have dropped") + t.end() +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/defaults.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/defaults.js new file mode 100644 index 000000000..75e05712d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/defaults.js @@ -0,0 +1,274 @@ +// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test +// +// TODO: Some of these tests do very bad things with backslashes, and will +// most likely fail badly on windows. They should probably be skipped. + +var tap = require("tap") + , globalBefore = Object.keys(global) + , mm = require("../") + , files = [ "a", "b", "c", "d", "abc" + , "abd", "abe", "bb", "bcd" + , "ca", "cb", "dd", "de" + , "bdir/", "bdir/cfile"] + , next = files.concat([ "a-b", "aXb" + , ".x", ".y" ]) + +tap.test("basic tests", function (t) { + var start = Date.now() + + // [ pattern, [matches], MM opts, files, TAP opts] + ; [ "http://www.bashcookbook.com/bashinfo" + + "/source/bash-1.14.7/tests/glob-test" + , ["a*", ["a", "abc", "abd", "abe"]] + , ["X*", ["X*"], {nonull: true}] + + // allow null glob expansion + , ["X*", []] + + // isaacs: Slightly different than bash/sh/ksh + // \\* is not un-escaped to literal "*" in a failed match, + // but it does make it get treated as a literal star + , ["\\*", ["\\*"], {nonull: true}] + , ["\\**", ["\\**"], {nonull: true}] + , ["\\*\\*", ["\\*\\*"], {nonull: true}] + + , ["b*/", ["bdir/"]] + , ["c*", ["c", "ca", "cb"]] + , ["**", files] + + , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] + , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] + + , "legendary larry crashes bashes" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] + + , "character classes" + , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] + , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", + "bdir/", "ca", "cb", "dd", "de"]] + , ["a*[^c]", ["abd", "abe"]] + , function () { files.push("a-b", "aXb") } + , ["a[X-]b", ["a-b", "aXb"]] + , function () { files.push(".x", ".y") } + , ["[^a-c]*", ["d", "dd", "de"]] + , function () { files.push("a*b/", "a*b/ooo") } + , ["a\\*b/*", ["a*b/ooo"]] + , ["a\\*?/*", ["a*b/ooo"]] + , ["*\\\\!*", [], {null: true}, ["echo !7"]] + , ["*\\!*", ["echo !7"], null, ["echo !7"]] + , ["*.\\*", ["r.*"], null, ["r.*"]] + , ["a[b]c", ["abc"]] + , ["a[\\b]c", ["abc"]] + , ["a?c", ["abc"]] + , ["a\\*c", [], {null: true}, ["abc"]] + , ["", [""], { null: true }, [""]] + + , "http://www.opensource.apple.com/source/bash/bash-23/" + + "bash/tests/glob-test" + , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } + , ["*/man*/bash.*", ["man/man1/bash.1"]] + , ["man/man1/bash.1", ["man/man1/bash.1"]] + , ["a***c", ["abc"], null, ["abc"]] + , ["a*****?c", ["abc"], null, ["abc"]] + , ["?*****??", ["abc"], null, ["abc"]] + , ["*****??", ["abc"], null, ["abc"]] + , ["?*****?c", ["abc"], null, ["abc"]] + , ["?***?****c", ["abc"], null, ["abc"]] + , ["?***?****?", ["abc"], null, ["abc"]] + , ["?***?****", ["abc"], null, ["abc"]] + , ["*******c", ["abc"], null, ["abc"]] + , ["*******?", ["abc"], null, ["abc"]] + , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["[-abc]", ["-"], null, ["-"]] + , ["[abc-]", ["-"], null, ["-"]] + , ["\\", ["\\"], null, ["\\"]] + , ["[\\\\]", ["\\"], null, ["\\"]] + , ["[[]", ["["], null, ["["]] + , ["[", ["["], null, ["["]] + , ["[*", ["[abc"], null, ["[abc"]] + , "a right bracket shall lose its special meaning and\n" + + "represent itself in a bracket expression if it occurs\n" + + "first in the list. -- POSIX.2 2.8.3.2" + , ["[]]", ["]"], null, ["]"]] + , ["[]-]", ["]"], null, ["]"]] + , ["[a-\z]", ["p"], null, ["p"]] + , ["??**********?****?", [], { null: true }, ["abc"]] + , ["??**********?****c", [], { null: true }, ["abc"]] + , ["?************c****?****", [], { null: true }, ["abc"]] + , ["*c*?**", [], { null: true }, ["abc"]] + , ["a*****c*?**", [], { null: true }, ["abc"]] + , ["a********???*******", [], { null: true }, ["abc"]] + , ["[]", [], { null: true }, ["a"]] + , ["[abc", [], { null: true }, ["["]] + + , "nocase tests" + , ["XYZ", ["xYz"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["ab*", ["ABC"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + + // [ pattern, [matches], MM opts, files, TAP opts] + , "onestar/twostar" + , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] + , ["{/?,*}", ["/a", "bb"], {null: true} + , ["/a", "/b/b", "/a/b/c", "bb"]] + + , "dots should not match unless requested" + , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] + + // .. and . can only match patterns starting with ., + // even when options.dot is set. + , function () { + files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] + } + , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] + , ["a/*/b", ["a/c/b"], {dot:false}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] + + + // this also tests that changing the options needs + // to change the cache key, even if the pattern is + // the same! + , ["**", ["a/b","a/.d",".a/.d"], { dot: true } + , [ ".a/.d", "a/.d", "a/b"]] + + , "paren sets cannot contain slashes" + , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] + + // brace sets trump all else. + // + // invalid glob pattern. fails on bash4 and bsdglob. + // however, in this implementation, it's easier just + // to do the intuitive thing, and let brace-expansion + // actually come before parsing any extglob patterns, + // like the documentation seems to say. + // + // XXX: if anyone complains about this, either fix it + // or tell them to grow up and stop complaining. + // + // bash/bsdglob says this: + // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] + // but we do this instead: + , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] + + // test partial parsing in the presence of comment/negation chars + , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] + , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] + + // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. + , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] + , {} + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] + + + // crazy nested {,,} and *(||) tests. + , function () { + files = [ "a", "b", "c", "d" + , "ab", "ac", "ad" + , "bc", "cb" + , "bc,d", "c,db", "c,d" + , "d)", "(b|c", "*(b|c" + , "b|c", "b|cc", "cb|c" + , "x(a|b|c)", "x(a|c)" + , "(a|b|c)", "(a|c)"] + } + , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] + , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] + // a + // *(b|c) + // *(b|d) + , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] + , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] + + + // test various flag settings. + , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] + , { noext: true } ] + , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} + , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] + , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] + + + // begin channelling Boole and deMorgan... + , "negation tests" + , function () { + files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] + } + + // anything that is NOT a* matches. + , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] + + // anything that IS !a* matches. + , ["!a*", ["!ab", "!abc"], {nonegate: true}] + + // anything that IS a* matches + , ["!!a*", ["a!b"]] + + // anything that is NOT !a* matches + , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] + + // negation nestled within a pattern + , function () { + files = [ "foo.js" + , "foo.bar" + // can't match this one without negative lookbehind. + , "foo.js.js" + , "blar.js" + , "foo." + , "boo.js.boo" ] + } + , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] + + ].forEach(function (c) { + if (typeof c === "function") return c() + if (typeof c === "string") return t.comment(c) + + var pattern = c[0] + , expect = c[1].sort(alpha) + , options = c[2] + , f = c[3] || files + , tapOpts = c[4] || {} + + // options.debug = true + var Class = mm.defaults(options).Minimatch + var m = new Class(pattern, {}) + var r = m.makeRe() + tapOpts.re = String(r) || JSON.stringify(r) + tapOpts.files = JSON.stringify(f) + tapOpts.pattern = pattern + tapOpts.set = m.set + tapOpts.negated = m.negate + + var actual = mm.match(f, pattern, options) + actual.sort(alpha) + + t.equivalent( actual, expect + , JSON.stringify(pattern) + " " + JSON.stringify(expect) + , tapOpts ) + }) + + t.comment("time=" + (Date.now() - start) + "ms") + t.end() +}) + +tap.test("global leak test", function (t) { + var globalAfter = Object.keys(global) + t.equivalent(globalAfter, globalBefore, "no new globals, please") + t.end() +}) + +function alpha (a, b) { + return a > b ? 1 : -1 +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/extglob-ending-with-state-char.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/extglob-ending-with-state-char.js new file mode 100644 index 000000000..6676e2629 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/node_modules/minimatch/test/extglob-ending-with-state-char.js @@ -0,0 +1,8 @@ +var test = require('tap').test +var minimatch = require('../') + +test('extglob ending with statechar', function(t) { + t.notOk(minimatch('ax', 'a?(b*)')) + t.ok(minimatch('ax', '?(a*|b)')) + t.end() +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/package.json b/node_modules/jade/node_modules/monocle/node_modules/readdirp/package.json new file mode 100644 index 000000000..4503a75c5 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/package.json @@ -0,0 +1,49 @@ +{ + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "thlorenz.com" + }, + "name": "readdirp", + "description": "Recursive version of fs.readdir with streaming api.", + "version": "0.2.5", + "homepage": "https://github.com/thlorenz/readdirp", + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/readdirp.git" + }, + "engines": { + "node": ">=0.4" + }, + "keywords": [ + "recursive", + "fs", + "stream", + "streams", + "readdir", + "filesystem", + "find", + "filter" + ], + "main": "readdirp.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "minimatch": ">=0.2.4" + }, + "devDependencies": { + "tap": "~0.3.1", + "through": "~1.1.0", + "minimatch": "~0.2.7" + }, + "optionalDependencies": {}, + "license": "MIT", + "readme": "# readdirp [![Build Status](https://secure.travis-ci.org/thlorenz/readdirp.png)](http://travis-ci.org/thlorenz/readdirp)\n\nRecursive version of [fs.readdir](http://nodejs.org/docs/latest/api/fs.html#fs_fs_readdir_path_callback). Exposes a **stream api**.\n\n```javascript\nvar readdirp = require('readdirp'); \n , path = require('path')\n , es = require('event-stream');\n\n// print out all JavaScript files along with their size\n\nvar stream = readdirp({ root: path.join(__dirname), fileFilter: '*.js' });\nstream\n .on('warn', function (err) { \n console.error('non-fatal error', err); \n // optionally call stream.destroy() here in order to abort and cause 'close' to be emitted\n })\n .on('error', function (err) { console.error('fatal error', err); })\n .pipe(es.mapSync(function (entry) { \n return { path: entry.path, size: entry.stat.size };\n }))\n .pipe(es.stringify())\n .pipe(process.stdout);\n```\n\nMeant to be one of the recursive versions of [fs](http://nodejs.org/docs/latest/api/fs.html) functions, e.g., like [mkdirp](https://github.com/substack/node-mkdirp).\n\n**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)*\n\n- [Installation](#installation)\n- [API](#api)\n\t- [entry stream](#entry-stream)\n\t- [options](#options)\n\t- [entry info](#entry-info)\n\t- [Filters](#filters)\n\t- [Callback API](#callback-api)\n\t\t- [allProcessed ](#allprocessed)\n\t\t- [fileProcessed](#fileprocessed)\n- [More Examples](#more-examples)\n\t- [stream api](#stream-api)\n\t- [stream api pipe](#stream-api-pipe)\n\t- [grep](#grep)\n\t- [using callback api](#using-callback-api)\n\t- [tests](#tests)\n\n\n# Installation\n\n npm install readdirp\n\n# API\n\n***var entryStream = readdirp (options)***\n\nReads given root recursively and returns a `stream` of [entry info](#entry-info)s.\n\n## entry stream\n\nBehaves as follows:\n \n- `emit('data')` passes an [entry info](#entry-info) whenever one is found\n- `emit('warn')` passes a non-fatal `Error` that prevents a file/directory from being processed (i.e., if it is\n inaccessible to the user)\n- `emit('error')` passes a fatal `Error` which also ends the stream (i.e., when illegal options where passed)\n- `emit('end')` called when all entries were found and no more will be emitted (i.e., we are done)\n- `emit('close')` called when the stream is destroyed via `stream.destroy()` (which could be useful if you want to\n manually abort even on a non fatal error) - at that point the stream is no longer `readable` and no more entries,\n warning or errors are emitted\n- the stream is `paused` initially in order to allow `pipe` and `on` handlers be connected before data or errors are\n emitted\n- the stream is `resumed` automatically during the next event loop \n- to learn more about streams, consult the [stream-handbook](https://github.com/substack/stream-handbook)\n\n## options\n \n- **root**: path in which to start reading and recursing into subdirectories\n\n- **fileFilter**: filter to include/exclude files found (see [Filters](#filters) for more)\n\n- **directoryFilter**: filter to include/exclude directories found and to recurse into (see [Filters](#filters) for more)\n\n- **depth**: depth at which to stop recursing even if more subdirectories are found\n\n## entry info\n\nHas the following properties:\n\n- **parentDir** : directory in which entry was found (relative to given root)\n- **fullParentDir** : full path to parent directory\n- **name** : name of the file/directory\n- **path** : path to the file/directory (relative to given root)\n- **fullPath** : full path to the file/directory found\n- **stat** : built in [stat object](http://nodejs.org/docs/v0.4.9/api/fs.html#fs.Stats)\n- **Example**: (assuming root was `/User/dev/readdirp`)\n \n parentDir : 'test/bed/root_dir1',\n fullParentDir : '/User/dev/readdirp/test/bed/root_dir1',\n name : 'root_dir1_subdir1',\n path : 'test/bed/root_dir1/root_dir1_subdir1',\n fullPath : '/User/dev/readdirp/test/bed/root_dir1/root_dir1_subdir1',\n stat : [ ... ]\n \n## Filters\n \nThere are three different ways to specify filters for files and directories respectively. \n\n- **function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry\n\n- **glob string**: a string (e.g., `*.js`) which is matched using [minimatch](https://github.com/isaacs/minimatch), so go there for more\n information. \n\n Globstars (`**`) are not supported since specifiying a recursive pattern for an already recursive function doesn't make sense.\n\n Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files.\n\n- **array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown.\n \n `[ '*.json', '*.js' ]` includes all JavaScript and Json files.\n \n \n `[ '!.git', '!node_modules' ]` includes all directories except the '.git' and 'node_modules'.\n\nDirectories that do not pass a filter will not be recursed into.\n\n## Callback API\n\nAlthough the stream api is recommended, readdirp also exposes a callback based api.\n\n***readdirp (options, callback1 [, callback2])***\n\nIf callback2 is given, callback1 functions as the **fileProcessed** callback, and callback2 as the **allProcessed** callback.\n\nIf only callback1 is given, it functions as the **allProcessed** callback.\n\n### allProcessed \n\n- function with err and res parameters, e.g., `function (err, res) { ... }`\n- **err**: array of errors that occurred during the operation, **res may still be present, even if errors occurred**\n- **res**: collection of file/directory [entry infos](#entry-info)\n\n### fileProcessed\n\n- function with [entry info](#entry-info) parameter e.g., `function (entryInfo) { ... }`\n\n\n# More Examples\n\n`on('error', ..)`, `on('warn', ..)` and `on('end', ..)` handling omitted for brevity\n\n```javascript\nvar readdirp = require('readdirp');\n\n// Glob file filter\nreaddirp({ root: './test/bed', fileFilter: '*.js' })\n .on('data', function (entry) {\n // do something with each JavaScript file entry\n });\n\n// Combined glob file filters\nreaddirp({ root: './test/bed', fileFilter: [ '*.js', '*.json' ] })\n .on('data', function (entry) {\n // do something with each JavaScript and Json file entry \n });\n\n// Combined negated directory filters\nreaddirp({ root: './test/bed', directoryFilter: [ '!.git', '!*modules' ] })\n .on('data', function (entry) {\n // do something with each file entry found outside '.git' or any modules directory \n });\n\n// Function directory filter\nreaddirp({ root: './test/bed', directoryFilter: function (di) { return di.name.length === 9; } })\n .on('data', function (entry) {\n // do something with each file entry found inside directories whose name has length 9\n });\n\n// Limiting depth\nreaddirp({ root: './test/bed', depth: 1 })\n .on('data', function (entry) {\n // do something with each file entry found up to 1 subdirectory deep\n });\n\n// callback api\nreaddirp(\n { root: '.' }\n , function(fileInfo) { \n // do something with file entry here\n } \n , function (err, res) {\n // all done, move on or do final step for all file entries here\n }\n);\n```\n\nTry more examples by following [instructions](https://github.com/thlorenz/readdirp/blob/master/examples/Readme.md)\non how to get going.\n\n## stream api\n\n[stream-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api.js)\n\nDemonstrates error and data handling by listening to events emitted from the readdirp stream.\n\n## stream api pipe\n\n[stream-api-pipe.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api-pipe.js)\n\nDemonstrates error handling by listening to events emitted from the readdirp stream and how to pipe the data stream into\nanother destination stream.\n\n## grep\n\n[grep.js](https://github.com/thlorenz/readdirp/blob/master/examples/grep.js)\n\nVery naive implementation of grep, for demonstration purposes only.\n\n## using callback api\n\n[callback-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/callback-api.js)\n\nShows how to pass callbacks in order to handle errors and/or data.\n\n## tests\n\nThe [readdirp tests](https://github.com/thlorenz/readdirp/blob/master/test/readdirp.js) also will give you a good idea on\nhow things work.\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/thlorenz/readdirp/issues" + }, + "_id": "readdirp@0.2.5", + "_from": "readdirp@~0.2.3" +} diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/readdirp.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/readdirp.js new file mode 100644 index 000000000..6111e11dd --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/readdirp.js @@ -0,0 +1,276 @@ +'use strict'; + +var fs = require('fs') + , path = require('path') + , minimatch = require('minimatch') + , toString = Object.prototype.toString + ; + +// Standard helpers +function isFunction (obj) { + return toString.call(obj) == '[object Function]'; +} + +function isString (obj) { + return toString.call(obj) == '[object String]'; +} + +function isRegExp (obj) { + return toString.call(obj) == '[object RegExp]'; +} + +function isUndefined (obj) { + return obj === void 0; +} + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param { Object } opts Options to specify root (start directory), filters and recursion depth + * @param { function } callback1 When callback2 is given calls back for each processed file - function (fileInfo) { ... }, + * when callback2 is not given, it behaves like explained in callback2 + * @param { function } callback2 Calls back once all files have been processed with an array of errors and file infos + * function (err, fileInfos) { ... } + */ +function readdir(opts, callback1, callback2) { + var stream + , handleError + , handleFatalError + , pending = 0 + , errors = [] + , readdirResult = { + directories: [] + , files: [] + } + , fileProcessed + , allProcessed + , realRoot + , aborted = false + ; + + // If no callbacks were given we will use a streaming interface + if (isUndefined(callback1)) { + var api = require('./stream-api')(); + stream = api.stream; + callback1 = api.processEntry; + callback2 = api.done; + handleError = api.handleError; + handleFatalError = api.handleFatalError; + + stream.on('close', function () { aborted = true; }); + } else { + handleError = function (err) { errors.push(err); }; + handleFatalError = function (err) { + handleError(err); + allProcessed(errors, null); + }; + } + + if (isUndefined(opts)){ + handleFatalError(new Error ( + 'Need to pass at least one argument: opts! \n' + + 'https://github.com/thlorenz/readdirp#options' + ) + ); + return stream; + } + + opts.root = opts.root || '.'; + opts.fileFilter = opts.fileFilter || function() { return true; }; + opts.directoryFilter = opts.directoryFilter || function() { return true; }; + opts.depth = typeof opts.depth === 'undefined' ? 999999999 : opts.depth; + + if (isUndefined(callback2)) { + fileProcessed = function() { }; + allProcessed = callback1; + } else { + fileProcessed = callback1; + allProcessed = callback2; + } + + function normalizeFilter (filter) { + + if (isUndefined(filter)) return undefined; + + function isNegated (filters) { + + function negated(f) { + return f.indexOf('!') === 0; + } + + var some = filters.some(negated); + if (!some) { + return false; + } else { + if (filters.every(negated)) { + return true; + } else { + // if we detect illegal filters, bail out immediately + throw new Error( + 'Cannot mix negated with non negated glob filters: ' + filters + '\n' + + 'https://github.com/thlorenz/readdirp#filters' + ); + } + } + } + + // Turn all filters into a function + if (isFunction(filter)) { + + return filter; + + } else if (isString(filter)) { + + return function (entryInfo) { + return minimatch(entryInfo.name, filter.trim()); + }; + + } else if (filter && Array.isArray(filter)) { + + if (filter) filter = filter.map(function (f) { + return f.trim(); + }); + + return isNegated(filter) ? + // use AND to concat multiple negated filters + function (entryInfo) { + return filter.every(function (f) { + return minimatch(entryInfo.name, f); + }); + } + : + // use OR to concat multiple inclusive filters + function (entryInfo) { + return filter.some(function (f) { + return minimatch(entryInfo.name, f); + }); + }; + } + } + + function processDir(currentDir, entries, callProcessed) { + if (aborted) return; + var total = entries.length + , processed = 0 + , entryInfos = [] + ; + + fs.realpath(currentDir, function(err, realCurrentDir) { + if (aborted) return; + if (err) { + handleError(err); + callProcessed(entryInfos); + return; + } + + var relDir = path.relative(realRoot, realCurrentDir); + + if (entries.length === 0) { + callProcessed([]); + } else { + entries.forEach(function (entry) { + + var fullPath = path.join(realCurrentDir, entry), + relPath = path.join(relDir, entry); + + fs.stat(fullPath, function (err, stat) { + if (err) { + handleError(err); + } else { + entryInfos.push({ + name : entry + , path : relPath // relative to root + , fullPath : fullPath + + , parentDir : relDir // relative to root + , fullParentDir : realCurrentDir + + , stat : stat + }); + } + processed++; + if (processed === total) callProcessed(entryInfos); + }); + }); + } + }); + } + + function readdirRec(currentDir, depth, callCurrentDirProcessed) { + if (aborted) return; + + fs.readdir(currentDir, function (err, entries) { + if (err) { + handleError(err); + callCurrentDirProcessed(); + return; + } + + processDir(currentDir, entries, function(entryInfos) { + + var subdirs = entryInfos + .filter(function (ei) { return ei.stat.isDirectory() && opts.directoryFilter(ei); }); + + subdirs.forEach(function (di) { + readdirResult.directories.push(di); + }); + + entryInfos + .filter(function(ei) { return ei.stat.isFile() && opts.fileFilter(ei); }) + .forEach(function (fi) { + fileProcessed(fi); + readdirResult.files.push(fi); + }); + + var pendingSubdirs = subdirs.length; + + // Be done if no more subfolders exist or we reached the maximum desired depth + if(pendingSubdirs === 0 || depth === opts.depth) { + callCurrentDirProcessed(); + } else { + // recurse into subdirs, keeping track of which ones are done + // and call back once all are processed + subdirs.forEach(function (subdir) { + readdirRec(subdir.fullPath, depth + 1, function () { + pendingSubdirs = pendingSubdirs - 1; + if(pendingSubdirs === 0) { + callCurrentDirProcessed(); + } + }); + }); + } + }); + }); + } + + // Validate and normalize filters + try { + opts.fileFilter = normalizeFilter(opts.fileFilter); + opts.directoryFilter = normalizeFilter(opts.directoryFilter); + } catch (err) { + // if we detect illegal filters, bail out immediately + handleFatalError(err); + return stream; + } + + // If filters were valid get on with the show + fs.realpath(opts.root, function(err, res) { + if (err) { + handleFatalError(err); + return stream; + } + + realRoot = res; + readdirRec(opts.root, 0, function () { + // All errors are collected into the errors array + if (errors.length > 0) { + allProcessed(errors, readdirResult); + } else { + allProcessed(null, readdirResult); + } + }); + }); + + return stream; +} + +module.exports = readdir; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/stream-api.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/stream-api.js new file mode 100644 index 000000000..1cfc6162b --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/stream-api.js @@ -0,0 +1,86 @@ +var Stream = require('stream'); + +function createStreamAPI () { + var stream + , processEntry + , done + , handleError + , handleFatalError + , paused = true + , controlled = false + , buffer = [] + , closed = false + ; + + stream = new Stream(); + stream.writable = false; + stream.readable = true; + + stream.pause = function () { + controlled = true; + paused = true; + }; + + stream.resume = function () { + controlled = true; + paused = false; + + // emit all buffered entries, errors and ends + while (!paused && buffer.length) { + var msg = buffer.shift(); + this.emit(msg.type, msg.data); + } + }; + + stream.destroy = function () { + closed = true; + stream.readable = false; + stream.emit('close'); + }; + + // called for each entry + processEntry = function (entry) { + if (closed) return; + return paused ? buffer.push({ type: 'data', data: entry }) : stream.emit('data', entry); + }; + + // called with all found entries when directory walk finished + done = function (err, entries) { + if (closed) return; + + // since we already emitted each entry and all non fatal errors + // all we need to do here is to signal that we are done + stream.emit('end'); + }; + + handleError = function (err) { + if (closed) return; + return paused ? buffer.push({ type: 'warn', data: err }) : stream.emit('warn', err); + }; + + handleFatalError = function (err) { + if (closed) return; + return paused ? buffer.push({ type: 'error', data: err }) : stream.emit('error', err); + }; + + // Allow stream to be returned and handlers to be attached and/or stream to be piped before emitting messages + // Otherwise we may loose data/errors that are emitted immediately + process.nextTick(function () { + if (closed) return; + + // In case was controlled (paused/resumed) manually, we don't interfer + // see https://github.com/thlorenz/readdirp/commit/ab7ff8561d73fca82c2ce7eb4ce9f7f5caf48b55#commitcomment-1964530 + if (controlled) return; + stream.resume(); + }); + + return { + stream : stream + , processEntry : processEntry + , done : done + , handleError : handleError + , handleFatalError : handleFatalError + }; +} + +module.exports = createStreamAPI; diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file1.ext1 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file1.ext1 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file2.ext2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file2.ext2 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file3.ext3 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_file3.ext3 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_subdir1/root1_dir1_subdir1_file1.ext1 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir1/root_dir1_subdir1/root1_dir1_subdir1_file1.ext1 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir2/root_dir2_file1.ext1 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir2/root_dir2_file1.ext1 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir2/root_dir2_file2.ext2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_dir2/root_dir2_file2.ext2 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file1.ext1 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file1.ext1 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file2.ext2 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file2.ext2 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file3.ext3 b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/bed/root_file3.ext3 new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp-stream.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp-stream.js new file mode 100644 index 000000000..261c5f67f --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp-stream.js @@ -0,0 +1,215 @@ +/*jshint asi:true */ + +var test = require('tap').test + , path = require('path') + , fs = require('fs') + , util = require('util') + , Stream = require('stream') + , through = require('through') + , streamapi = require('../stream-api') + , readdirp = require('..') + , root = path.join(__dirname, 'bed') + , totalDirs = 6 + , totalFiles = 12 + , ext1Files = 4 + , ext2Files = 3 + , ext3Files = 2 + ; + +// see test/readdirp.js for test bed layout + +function opts (extend) { + var o = { root: root }; + + if (extend) { + for (var prop in extend) { + o[prop] = extend[prop]; + } + } + return o; +} + +function capture () { + var result = { entries: [], errors: [], ended: false } + , dst = new Stream(); + + dst.writable = true; + dst.readable = true; + + dst.write = function (entry) { + result.entries.push(entry); + } + + dst.end = function () { + result.ended = true; + dst.emit('data', result); + dst.emit('end'); + } + + return dst; +} + +test('\nintegrated', function (t) { + t.test('\n# reading root without filter', function (t) { + t.plan(2); + readdirp(opts()) + .on('error', function (err) { + t.fail('should not throw error', err); + }) + .pipe(capture()) + .pipe(through( + function (result) { + t.equals(result.entries.length, totalFiles, 'emits all files'); + t.ok(result.ended, 'ends stream'); + t.end(); + } + )); + }) + + t.test('\n# normal: ["*.ext1", "*.ext3"]', function (t) { + t.plan(2); + + readdirp(opts( { fileFilter: [ '*.ext1', '*.ext3' ] } )) + .on('error', function (err) { + t.fail('should not throw error', err); + }) + .pipe(capture()) + .pipe(through( + function (result) { + t.equals(result.entries.length, ext1Files + ext3Files, 'all ext1 and ext3 files'); + t.ok(result.ended, 'ends stream'); + t.end(); + } + )) + }) + + t.test('\n# negated: ["!*.ext1", "!*.ext3"]', function (t) { + t.plan(2); + + readdirp(opts( { fileFilter: [ '!*.ext1', '!*.ext3' ] } )) + .on('error', function (err) { + t.fail('should not throw error', err); + }) + .pipe(capture()) + .pipe(through( + function (result) { + t.equals(result.entries.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files'); + t.ok(result.ended, 'ends stream'); + t.end(); + } + )) + }) + + t.test('\n# no options given', function (t) { + t.plan(1); + readdirp() + .on('error', function (err) { + t.similar(err.toString() , /Need to pass at least one argument/ , 'emits meaningful error'); + t.end(); + }) + }) + + t.test('\n# mixed: ["*.ext1", "!*.ext3"]', function (t) { + t.plan(1); + + readdirp(opts( { fileFilter: [ '*.ext1', '!*.ext3' ] } )) + .on('error', function (err) { + t.similar(err.toString() , /Cannot mix negated with non negated glob filters/ , 'emits meaningful error'); + t.end(); + }) + }) +}) + + +test('\napi separately', function (t) { + + t.test('\n# handleError', function (t) { + t.plan(1); + + var api = streamapi() + , warning = new Error('some file caused problems'); + + api.stream + .on('warn', function (err) { + t.equals(err, warning, 'warns with the handled error'); + }) + api.handleError(warning); + }) + + t.test('\n# when stream is paused and then resumed', function (t) { + t.plan(6); + var api = streamapi() + , resumed = false + , fatalError = new Error('fatal!') + , nonfatalError = new Error('nonfatal!') + , processedData = 'some data' + ; + + api.stream + .on('warn', function (err) { + t.equals(err, nonfatalError, 'emits the buffered warning'); + t.ok(resumed, 'emits warning only after it was resumed'); + }) + .on('error', function (err) { + t.equals(err, fatalError, 'emits the buffered fatal error'); + t.ok(resumed, 'emits errors only after it was resumed'); + }) + .on('data', function (data) { + t.equals(data, processedData, 'emits the buffered data'); + t.ok(resumed, 'emits data only after it was resumed'); + }) + .pause() + + api.processEntry(processedData); + api.handleError(nonfatalError); + api.handleFatalError(fatalError); + + process.nextTick(function () { + resumed = true; + api.stream.resume(); + }) + }) + + t.test('\n# when a stream is destroyed, it emits "closed", but no longer emits "data", "warn" and "error"', function (t) { + t.plan(6) + var api = streamapi() + , destroyed = false + , fatalError = new Error('fatal!') + , nonfatalError = new Error('nonfatal!') + , processedData = 'some data' + + var stream = api.stream + .on('warn', function (err) { + t.notOk(destroyed, 'emits warning until destroyed'); + }) + .on('error', function (err) { + t.notOk(destroyed, 'emits errors until destroyed'); + }) + .on('data', function (data) { + t.notOk(destroyed, 'emits data until destroyed'); + }) + .on('close', function () { + t.ok(destroyed, 'emits close when stream is destroyed'); + }) + + + api.processEntry(processedData); + api.handleError(nonfatalError); + api.handleFatalError(fatalError); + + process.nextTick(function () { + destroyed = true + stream.destroy() + + t.notOk(stream.readable, 'stream is no longer readable after it is destroyed') + + api.processEntry(processedData); + api.handleError(nonfatalError); + api.handleFatalError(fatalError); + + process.nextTick(function () { + t.pass('emits no more data, warn or error events after it was destroyed') + }) + }) + }) +}) diff --git a/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp.js b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp.js new file mode 100644 index 000000000..f3edb52b8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/node_modules/readdirp/test/readdirp.js @@ -0,0 +1,252 @@ +/*jshint asi:true */ + +var test = require('tap').test + , path = require('path') + , fs = require('fs') + , util = require('util') + , readdirp = require('../readdirp.js') + , root = path.join(__dirname, '../test/bed') + , totalDirs = 6 + , totalFiles = 12 + , ext1Files = 4 + , ext2Files = 3 + , ext3Files = 2 + , rootDir2Files = 2 + , nameHasLength9Dirs = 2 + , depth1Files = 8 + , depth0Files = 3 + ; + +/* +Structure of test bed: + . + ├── root_dir1 + │   ├── root_dir1_file1.ext1 + │   ├── root_dir1_file2.ext2 + │   ├── root_dir1_file3.ext3 + │   ├── root_dir1_subdir1 + │   │   └── root1_dir1_subdir1_file1.ext1 + │   └── root_dir1_subdir2 + │   └── .gitignore + ├── root_dir2 + │   ├── root_dir2_file1.ext1 + │   ├── root_dir2_file2.ext2 + │   ├── root_dir2_subdir1 + │   │   └── .gitignore + │   └── root_dir2_subdir2 + │   └── .gitignore + ├── root_file1.ext1 + ├── root_file2.ext2 + └── root_file3.ext3 + + 6 directories, 13 files +*/ + +// console.log('\033[2J'); // clear console + +function opts (extend) { + var o = { root: root }; + + if (extend) { + for (var prop in extend) { + o[prop] = extend[prop]; + } + } + return o; +} + +test('\nreading root without filter', function (t) { + t.plan(2); + readdirp(opts(), function (err, res) { + t.equals(res.directories.length, totalDirs, 'all directories'); + t.equals(res.files.length, totalFiles, 'all files'); + t.end(); + }) +}) + +test('\nreading root using glob filter', function (t) { + // normal + t.test('\n# "*.ext1"', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: '*.ext1' } ), function (err, res) { + t.equals(res.files.length, ext1Files, 'all ext1 files'); + t.end(); + }) + }) + t.test('\n# ["*.ext1", "*.ext3"]', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: [ '*.ext1', '*.ext3' ] } ), function (err, res) { + t.equals(res.files.length, ext1Files + ext3Files, 'all ext1 and ext3 files'); + t.end(); + }) + }) + t.test('\n# "root_dir1"', function (t) { + t.plan(1); + readdirp(opts( { directoryFilter: 'root_dir1' }), function (err, res) { + t.equals(res.directories.length, 1, 'one directory'); + t.end(); + }) + }) + t.test('\n# ["root_dir1", "*dir1_subdir1"]', function (t) { + t.plan(1); + readdirp(opts( { directoryFilter: [ 'root_dir1', '*dir1_subdir1' ]}), function (err, res) { + t.equals(res.directories.length, 2, 'two directories'); + t.end(); + }) + }) + + t.test('\n# negated: "!*.ext1"', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: '!*.ext1' } ), function (err, res) { + t.equals(res.files.length, totalFiles - ext1Files, 'all but ext1 files'); + t.end(); + }) + }) + t.test('\n# negated: ["!*.ext1", "!*.ext3"]', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: [ '!*.ext1', '!*.ext3' ] } ), function (err, res) { + t.equals(res.files.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files'); + t.end(); + }) + }) + + t.test('\n# mixed: ["*.ext1", "!*.ext3"]', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: [ '*.ext1', '!*.ext3' ] } ), function (err, res) { + t.similar(err[0].toString(), /Cannot mix negated with non negated glob filters/, 'returns meaningfull error'); + t.end(); + }) + }) + + t.test('\n# leading and trailing spaces: [" *.ext1", "*.ext3 "]', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: [ ' *.ext1', '*.ext3 ' ] } ), function (err, res) { + t.equals(res.files.length, ext1Files + ext3Files, 'all ext1 and ext3 files'); + t.end(); + }) + }) + t.test('\n# leading and trailing spaces: [" !*.ext1", " !*.ext3 "]', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: [ ' !*.ext1', ' !*.ext3' ] } ), function (err, res) { + t.equals(res.files.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files'); + t.end(); + }) + }) + + t.test('\n# ** glob pattern', function (t) { + t.plan(1); + readdirp(opts( { fileFilter: '**/*.ext1' } ), function (err, res) { + t.equals(res.files.length, ext1Files, 'ignores ** in **/*.ext1 -> only *.ext1 files'); + t.end(); + }) + }) +}) + +test('\n\nreading root using function filter', function (t) { + t.test('\n# file filter -> "contains root_dir2"', function (t) { + t.plan(1); + readdirp( + opts( { fileFilter: function (fi) { return fi.name.indexOf('root_dir2') >= 0; } }) + , function (err, res) { + t.equals(res.files.length, rootDir2Files, 'all rootDir2Files'); + t.end(); + } + ) + }) + + t.test('\n# directory filter -> "name has length 9"', function (t) { + t.plan(1); + readdirp( + opts( { directoryFilter: function (di) { return di.name.length === 9; } }) + , function (err, res) { + t.equals(res.directories.length, nameHasLength9Dirs, 'all all dirs with name length 9'); + t.end(); + } + ) + }) +}) + +test('\nreading root specifying maximum depth', function (t) { + t.test('\n# depth 1', function (t) { + t.plan(1); + readdirp(opts( { depth: 1 } ), function (err, res) { + t.equals(res.files.length, depth1Files, 'does not return files at depth 2'); + }) + }) +}) + +test('\nreading root with no recursion', function (t) { + t.test('\n# depth 0', function (t) { + t.plan(1); + readdirp(opts( { depth: 0 } ), function (err, res) { + t.equals(res.files.length, depth0Files, 'does not return files at depth 0'); + }) + }) +}) + +test('\nprogress callbacks', function (t) { + t.plan(2); + + var pluckName = function(fi) { return fi.name; } + , processedFiles = []; + + readdirp( + opts() + , function(fi) { + processedFiles.push(fi); + } + , function (err, res) { + t.equals(processedFiles.length, res.files.length, 'calls back for each file processed'); + t.deepEquals(processedFiles.map(pluckName).sort(),res.files.map(pluckName).sort(), 'same file names'); + t.end(); + } + ) +}) + +test('resolving of name, full and relative paths', function (t) { + var expected = { + name : 'root_dir1_file1.ext1' + , parentDirName : 'root_dir1' + , path : 'root_dir1/root_dir1_file1.ext1' + , fullPath : 'test/bed/root_dir1/root_dir1_file1.ext1' + } + , opts = [ + { root: './bed' , prefix: '' } + , { root: './bed/' , prefix: '' } + , { root: 'bed' , prefix: '' } + , { root: 'bed/' , prefix: '' } + , { root: '../test/bed/' , prefix: '' } + , { root: '.' , prefix: 'bed' } + ] + t.plan(opts.length); + + opts.forEach(function (op) { + op.fileFilter = 'root_dir1_file1.ext1'; + + t.test('\n' + util.inspect(op), function (t) { + t.plan(4); + + readdirp (op, function(err, res) { + t.equals(res.files[0].name, expected.name, 'correct name'); + t.equals(res.files[0].path, path.join(op.prefix, expected.path), 'correct path'); + }) + + fs.realpath(op.root, function(err, fullRoot) { + readdirp (op, function(err, res) { + t.equals( + res.files[0].fullParentDir + , path.join(fullRoot, op.prefix, expected.parentDirName) + , 'correct parentDir' + ); + t.equals( + res.files[0].fullPath + , path.join(fullRoot, op.prefix, expected.parentDirName, expected.name) + , 'correct fullPath' + ); + }) + }) + }) + }) +}) + + diff --git a/node_modules/jade/node_modules/monocle/package.json b/node_modules/jade/node_modules/monocle/package.json new file mode 100644 index 000000000..fbcbb2d61 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/package.json @@ -0,0 +1,56 @@ +{ + "name": "monocle", + "version": "0.1.48", + "description": "a tool for watching directories for file changes", + "main": "monocle.js", + "directories": { + "test": "test" + }, + "dependencies": { + "readdirp": "~0.2.3" + }, + "devDependencies": { + "mocha": "1.8.1" + }, + "scripts": { + "test": "mocha test -R spec -t 2000" + }, + "repository": { + "type": "git", + "url": "https://github.com/samccone/monocle.git" + }, + "bugs": { + "url": "https://github.com/samccone/monocle/issues" + }, + "keywords": [ + "watch", + "filesystem", + "folders", + "fs" + ], + "author": { + "name": "Sam Saccone" + }, + "license": "BSD", + "readme": "[![Build Status](https://travis-ci.org/samccone/monocle.png?branch=master)](https://travis-ci.org/samccone/monocle)\n\n# Monocle -- a tool for watching things\n\n[![logo](https://raw.github.com/samccone/monocle/master/logo.png)](https://raw.github.com/samccone/monocle/master/logo.png)\n\nHave you ever wanted to watch a folder and all of its files/nested folders for changes. well now you can!\n\n## Installation\n\n```\nnpm install monocle\n```\n\n## Usage\n\n### Watch a directory:\n\n```js\nvar monocle = require('monocle')()\nmonocle.watchDirectory({\n root: ,\n fileFilter: ,\n directoryFilter: ,\n listener: fn(fs.stat+ object), //triggered on file change / addition\n complete: //file watching all set up\n});\n```\n\nThe listener will recive an object with the following\n\n```js\n name: ,\n path: ,\n fullPath: ,\n parentDir: ,\n fullParentDir: ,\n stat: \n```\n\n[fs.stats](http://nodejs.org/api/fs.html#fs_class_fs_stats)\n\nWhen a new file is added to the directoy it triggers a file change and thus will be passed to your specified listener.\n\nThe two filters are passed through to `readdirp`. More documentation can be found [here](https://github.com/thlorenz/readdirp#filters)\n\n### Watch a list of files:\n\n```js\nMonocle.watchFiles({\n files: [], //path of file(s)\n listener: , //triggered on file / addition\n complete: //file watching all set up\n});\n```\n\n## Why not just use fs.watch ?\n\n - file watching is really bad cross platforms in node\n - you need to be smart when using fs.watch as compared to fs.watchFile\n - Monocle takes care of this logic for you!\n - windows systems use fs.watch\n - osx and linux uses fs.watchFile\n\n## License\n\nBSD\n", + "readmeFilename": "README.md", + "_id": "monocle@0.1.48", + "dist": { + "shasum": "b96730f5ca900fa75a56041eb6db10aad980a383", + "tarball": "http://registry.npmjs.org/monocle/-/monocle-0.1.48.tgz" + }, + "_from": "monocle@0.1.48", + "_npmVersion": "1.2.18", + "_npmUser": { + "name": "samccone", + "email": "samccone@gmail.com" + }, + "maintainers": [ + { + "name": "samccone", + "email": "samccone@gmail.com" + } + ], + "_shasum": "b96730f5ca900fa75a56041eb6db10aad980a383", + "_resolved": "https://registry.npmjs.org/monocle/-/monocle-0.1.48.tgz" +} diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/creation3.txt b/node_modules/jade/node_modules/monocle/test/sample_files/creation3.txt new file mode 100644 index 000000000..8e9c6658d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/creation3.txt @@ -0,0 +1 @@ +1368234683085 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/creation4.txt b/node_modules/jade/node_modules/monocle/test/sample_files/creation4.txt new file mode 100644 index 000000000..f1937ffec --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/creation4.txt @@ -0,0 +1 @@ +1368234683637 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/creation5.txt b/node_modules/jade/node_modules/monocle/test/sample_files/creation5.txt new file mode 100644 index 000000000..1f5a20669 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/creation5.txt @@ -0,0 +1 @@ +1368234684038 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/foo.txt b/node_modules/jade/node_modules/monocle/test/sample_files/foo.txt new file mode 100644 index 000000000..fe02e96e3 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/foo.txt @@ -0,0 +1 @@ +1361300019687 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/longbow.js b/node_modules/jade/node_modules/monocle/test/sample_files/longbow.js new file mode 100644 index 000000000..08c34733c --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/longbow.js @@ -0,0 +1 @@ +1361300019993 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/nestedDir/servent.txt b/node_modules/jade/node_modules/monocle/test/sample_files/nestedDir/servent.txt new file mode 100644 index 000000000..b26921ea8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/nestedDir/servent.txt @@ -0,0 +1 @@ +1361300019841 diff --git a/node_modules/jade/node_modules/monocle/test/sample_files/zap.bat b/node_modules/jade/node_modules/monocle/test/sample_files/zap.bat new file mode 100644 index 000000000..a358cce5d --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/sample_files/zap.bat @@ -0,0 +1,31 @@ +1361223315286 +1361223316535 +1361223345247 +1361223392495 +1361223394521 +1361223401023 +1361223431160 +1361223432160 +1361223437177 +1361223438592 +1361223466645 +1361223467719 +1361223594858 +1361223614308 +1361223643429 +1361223647989 +1361223649211 +1361223650605 +1361223651566 +1361223663051 +1361223664917 +1361223665860 +1361223777758 +1361223779174 +1361223780023 +1361223780769 +1361223783122 +1361223784141 +1361223791305 +1361223795551 +1361223797217 diff --git a/node_modules/jade/node_modules/monocle/test/tester.js b/node_modules/jade/node_modules/monocle/test/tester.js new file mode 100644 index 000000000..d65d57bf8 --- /dev/null +++ b/node_modules/jade/node_modules/monocle/test/tester.js @@ -0,0 +1,180 @@ +var fs = require('fs'); +var assert = require('assert'); +var Monocle = require('../monocle'); + +// +// setup +// +var monocle = null; +var sample_dir = __dirname + '/sample_files'; +before(function(){ monocle = Monocle(); }); +after(function() { + fs.unlinkSync(__dirname+"/sample_files/creation.txt"); + fs.unlinkSync(__dirname+"/sample_files/creation2.txt"); + fs.unlinkSync(__dirname+"/sample_files/nestedDir/creation3.txt"); +}); +// +// file change tests +// + +describe("file changes", function() { + + it("should detect a change", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f){ cb_helper('foo.txt', f, complete); }, + complete: function(){ complete_helper("/sample_files/foo.txt"); } + }); + }); + + it("should detect a change in a nested dir file", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f) { cb_helper('servent.txt', f, complete); }, + complete: function() { complete_helper("/sample_files/nestedDir/servent.txt"); } + }); + }); + + it("should detect a change", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f) { cb_helper('longbow.js', f, complete); }, + complete: function() { complete_helper('/sample_files/longbow.js'); } + }); + }); + +}); + +// +// file add tests +// + +describe("file added", function() { + it("should detect a file added", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f) { + cb_helper("creation.txt", f, complete) + }, + complete: function() { + complete_helper('/sample_files/creation.txt'); + } + }); + }); + + it("should detect another file added", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f) { + cb_helper("creation2.txt", f, complete); + }, + complete: function() { + complete_helper('/sample_files/creation2.txt'); + } + }); + }); + + it("should detect another file added in a nested folder", function(complete) { + monocle.watchDirectory({ + root: sample_dir, + listener: function(f) { + cb_helper("creation3.txt", f, complete); + }, + complete: function() { + complete_helper('/sample_files/nestedDir/creation3.txt'); + } + }); + }); +}); + + +// +// watch an array of files +// +describe("files watched", function() { + it("should detect a file changed of multiple", function(complete) { + complete_helper('/sample_files/creation.txt'); + complete_helper('/sample_files/creation2.txt'); + complete_helper('/sample_files/creation3.txt'); + + monocle.watchFiles({ + files: [__dirname+"/sample_files/creation.txt", __dirname+"/sample_files/creation2.txt"], + listener: function(f) { + cb_helper("creation2.txt", f, complete) + }, + complete: function() { + complete_helper('/sample_files/creation2.txt'); + } + }); + }); + + it("should detect a file changed (delayed)", function(complete) { + complete_helper('/sample_files/creation3.txt'); + monocle.watchFiles({ + files: [__dirname+"/sample_files/creation3.txt"], + listener: function(f) { + setTimeout(function() { + cb_helper('creation3.txt', f, complete); + }, 400); + }, + complete: function() { + complete_helper('/sample_files/creation3.txt'); + } + }); + }); + + + + it("should detect a file changed (short delayed)", function(complete) { + complete_helper('/sample_files/creation4.txt'); + monocle.watchFiles({ + files: [__dirname+"/sample_files/creation4.txt"], + listener: function(f) { + setTimeout(function() { + cb_helper('creation4.txt', f, complete); + }, 100); + }, + complete: function() { + complete_helper('/sample_files/creation4.txt'); + } + }); + }); + + it("should detect a file changed", function(complete) { + complete_helper('/sample_files/creation.txt'); + monocle.watchFiles({ + files: [__dirname+"/sample_files/creation.txt"], + listener: function(f) { + cb_helper("creation.txt", f, complete) + }, + complete: function() { + complete_helper('/sample_files/creation.txt'); + } + }); + }); + + it("should not bomb when no callback is passed", function(complete) { + complete_helper('/sample_files/creation5.txt'); + monocle.watchFiles({ + files: [__dirname+"/sample_files/creation5.txt"], + complete: function() { + complete_helper('/sample_files/creation5.txt'); + } + }); + setTimeout(function() { + complete(); + }, 300) + }); +}); + +// +// helpers +// + +function cb_helper(name, file, done){ + if (file.name === name) { monocle.unwatchAll(); done(); } +} + +function complete_helper(path){ + fs.writeFile(__dirname + path, (new Date).getTime() + "\n"); +} diff --git a/node_modules/jade/node_modules/transformers/.npmignore b/node_modules/jade/node_modules/transformers/.npmignore new file mode 100644 index 000000000..a72b52ebe --- /dev/null +++ b/node_modules/jade/node_modules/transformers/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/node_modules/jade/node_modules/transformers/.travis.yml b/node_modules/jade/node_modules/transformers/.travis.yml new file mode 100644 index 000000000..baa0031d5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.8 diff --git a/node_modules/jade/node_modules/transformers/README.md b/node_modules/jade/node_modules/transformers/README.md new file mode 100644 index 000000000..a1dae66d2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/README.md @@ -0,0 +1,138 @@ +[![Build Status](https://travis-ci.org/ForbesLindesay/transformers.png?branch=master)](https://travis-ci.org/ForbesLindesay/transformers) +# transformers + + String/Data transformations for use in templating libraries, static site generators and web frameworks. This gathers the most useful transformations you can apply to text or data into one library with a consistent API. Transformations can be pretty much anything but most are either compilers or templating engines. + +## Supported transforms + + To use each of these transforms you will also need to install the associated npm module for that transformer. + +### Template engines + + - [atpl](http://documentup.com/soywiz/atpl.js) - Compatible with twig templates + - [coffeecup](http://documentup.com/gradus/coffeecup) - pure coffee-script templates (fork of coffeekup) + - [dot](http://documentup.com/olado/doT) [(website)](https://github.com/Katahdin/dot-packer) - focused on speed + - [dust](http://documentup.com/akdubya/dustjs) [(website)](http://akdubya.github.com/dustjs/) - asyncronous templates + - [eco](http://documentup.com/sstephenson/eco) - Embedded CoffeeScript templates + - [ect](http://documentup.com/baryshev/ect) [(website)](http://ectjs.com/) - Embedded CoffeeScript templates + - [ejs](http://documentup.com/visionmedia/ejs) - Embedded JavaScript templates + - [haml](http://documentup.com/visionmedia/haml.js) [(website)](http://haml-lang.com/) - dry indented markup + - [haml-coffee](http://documentup.com/netzpirat/haml-coffee/) [(website)](http://haml-lang.com/) - haml with embedded CoffeeScript + - [handlebars](http://documentup.com/wycats/handlebars.js/) [(website)](http://handlebarsjs.com/) - extension of mustache templates + - [hogan](http://documentup.com/twitter/hogan.js) [(website)](http://twitter.github.com/hogan.js/) - Mustache templates + - [jade](http://documentup.com/visionmedia/jade) [(website)](http://jade-lang.com/) - robust, elegant, feature rich template engine + - [jazz](http://documentup.com/shinetech/jazz) + - [jqtpl](http://documentup.com/kof/jqtpl) [(website)](http://api.jquery.com/category/plugins/templates/) - extensible logic-less templates + - [JUST](http://documentup.com/baryshev/just) - EJS style template with some special syntax for layouts/partials etc. + - [liquor](http://documentup.com/chjj/liquor) - extended EJS with significant white space + - [mustache](http://documentup.com/janl/mustache.js) - logic less templates + - [QEJS](http://documentup.com/jepso/QEJS) - Promises + EJS for async templating + - [swig](http://documentup.com/paularmstrong/swig) [(website)](http://paularmstrong.github.com/swig/) - Django-like templating engine + - [templayed](http://documentup.com/archan937/templayed.js/) [(website)](http://archan937.github.com/templayed.js/) - Mustache focused on performance + - [toffee](http://documentup.com/malgorithms/toffee) - templating language based on coffeescript + - [underscore](http://documentup.com/documentcloud/underscore) [(website)](http://documentcloud.github.com/underscore/) + - [walrus](http://documentup.com/jeremyruppel/walrus) - A bolder kind of mustache + - [whiskers](http://documentup.com/gsf/whiskers.js/tree/) - logic-less focused on readability + +### Stylesheet Languages + + - [less](http://documentup.com/cloudhead/less.js) [(website)](http://lesscss.org/) - LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. + - [stylus](http://documentup.com/learnboost/stylus) [(website)](http://learnboost.github.com/stylus/) - revolutionary CSS generator making braces optional + - [sass](http://documentup.com/visionmedia/sass.js) [(website)](http://sass-lang.com/) - Sassy CSS + +### Minifiers + + - [uglify-js](http://documentup.com/mishoo/UglifyJS2) - No need to install anything, just minifies/beautifies JavaScript + - [uglify-css](https://github.com/visionmedia/css) - No need to install anything, just minifies/beautifies CSS + - ugilify-json - No need to install anything, just minifies/beautifies JSON + +### Other + + - cdata - No need to install anything, just wrapps text in `` + - [coffee-script](http://coffeescript.org/) - `npm install coffee-script` + - [cson](https://github.com/bevry/cson) - coffee-script based JSON format + - markdown - You can use `marked`, `supermarked`, `markdown-js` or `markdown` + - [component-js](http://documentup.com/component/component) [(website)](http://component.io) - `npm install component-builder` options: `{development: false}` + - [component-css](http://documentup.com/component/component) [(website)](http://component.io) - `npm install component-builder` options: `{development: false}` + - [html2jade](http://documentup.com/donpark/html2jade) [(website)](http://html2jade.aaron-powell.com/) - `npm install html2jade` - Converts HTML back into jade + +Pull requests to add more transforms will always be accepted providing they are open-source, come with unit tests, and don't cause any of the tests to fail. + +## API + + The exported object `transformers` is a collection of named transformers. To access an individual transformer just do: + + ```javascript + var transformer = require('transformers')['transformer-name'] + ``` + +### Transformer + + The following options are given special meaning by `transformers`: + + - `filename` is set by transformers automatically if using the `renderFile` APIs. It is used if `cache` is enabled. + - `cache` if true, the template function will be cached where possible (templates are still updated if you provide new options, so this can be used in most live applications). + - `sudoSync` used internally to put some asyncronous transformers into "sudo syncronous" mode. Don't touch this. + - `minify` if set to true on a transformer that isn't a minifier, it will cause the output to be minified. e.g. `coffeeScript.renderSync(str, {minify: true})` will result in minified JavaScript. + +#### Transformer.engines + + Returns an array of engines that can be used to power this transformer. The first of these that's installed will be used for the transformation. + + To enable a transformation just take `[engine] = Transformer.engines[0]` and then do `npm install [engine]`. If `[engine]` is `.` there is no need to install an engine from npm to use the transformer. + +#### Transformer.render(str, options, cb) + + Tranform the string `str` using the `Transformer` with the provided options and call the callback `cb(err, res)`. + + If no `cb` is provided, this method returns a [promises/A+](http://promises-aplus.github.com/promises-spec/) promise. + +#### Transformer.renderSync(str, options) + + Synchronous version of `Transformer.render` + +#### Transformer.renderFile(filename, options, cb) + + Reads the file at filename into `str` and sets `options.filename = filename` then calls `Transform.render(str, options, cb)`. + + If no `cb` is provided, this method returns a [promises/A+](http://promises-aplus.github.com/promises-spec/) promise. + +#### Tranformer.renderFileSync(filename, options) + + Synchronous version of `Tranformer.renderFile` + +#### Transformer.outputFormat + + A string, one of: + + - `'xml'` + - `'css'` + - `'js'` + - `'json'` + - `'text'` + +Adding to this list will **not** result in a major version change, so you should handle unexpected types gracefully (I'd suggest default to assuming `'text'`). + +#### Transformer.sync + + `true` if the transformer can be used syncronously, `false` otherwise. + +## Libraries that don't work synchronously + + The following transformations will always throw an exception if you attempt to run them synchronously: + + 1. dust + 2. qejs + 3. html2jade + +The following transformations sometimes throw an exception if run syncronously, typically they only throw an exception if you are doing something like including another file. If you are not doing the things that cause them to fail then they are consistently safe to use syncronously. + + - jade (only when using `then-jade` instead of `jade`) + - less (when `@import` is used with a url instead of a filename) + - jazz (When one of the functions passed as locals is asyncronous) + +The following libraries look like they might sometimes throw exceptions when used syncronously (if you read the source) but they never actually do so: + + - just + - ect + - stylus \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/history.md b/node_modules/jade/node_modules/transformers/history.md new file mode 100644 index 000000000..096b9f956 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/history.md @@ -0,0 +1,69 @@ +## 2.0.1 - 2013-04-22 + + - Fix global leak of `exportscoffeeScript` (test still fails because `jade` requires an out of date version of `transformers`) + +## 2.0.0 - 2013-03-31 + + - Add `minify` support to all transformers + - Bundle minifiers in package + +## 1.8.3 - 2013-03-19 + + - Update promise dependency + +## 1.8.2 - 2013-02-10 + + - Support `sourceURLs` in **component** + +## 1.8.1 - 2013-02-10 + + - Add travis-ci + - FIX **toffee** support which was broken by their latest update + - FIX lookup paths for **component** weren't set so you couldn't build components with dependancies + +## 1.8.0 - 2013-01-30 + + - **highlight** (needs tests) + +## 1.7.0 - 2013-01-30 + + - **component-js** + - **component-css** + - **html2jade** - must be `v0.0.7` because of a bug in later versions + - Much more extensive tests + +## 1.6.0 - 2013-01-29 + + - **uglify-css** + - **uglify-json** + - Rename **uglify** to **uglify-js** + +## 1.5.0 - 2013-01-27 + + - **dot** + +## 1.4.0 - 2013-01-25 + + - Support sync `@import` statements in **less** + - Report real errors from **less** (rather than objects) + +## 1.3.0 - 2013-01-25 + + - **templayed** + - **plates** + +## 1.2.1 - 2013-01-09 + + - make **markdown** work when using **markdown** as the engine (**marked** is the recommended engine). + +## 1.2.0 - 2013-01-09 + + - **js** (pass through) + - **css** (pass through) + - rename **coffee-script** from **coffee** to **coffee-script** and add **coffee** as an alias + +## 1.1.0 - 2013-01-08 + + - **coffeecup** + - **cson** + - FIX: disabling **dust** cache \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/lib/shared.js b/node_modules/jade/node_modules/transformers/lib/shared.js new file mode 100644 index 000000000..866311784 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/lib/shared.js @@ -0,0 +1,162 @@ +var Promise = require('promise'); +var fs = require('fs'); +var path = require('path'); +var normalize = path.normalize; + + +Promise.prototype.nodeify = function (cb) { + if (typeof cb === 'function') { + this.then(function (res) { process.nextTick(function () { cb(null, res); }); }, + function (err) { process.nextTick(function () { cb(err); }); }); + return undefined; + } else { + return this; + } +} + +var minifiers = {}; + +module.exports = Transformer; +function Transformer(obj) { + this.name = obj.name; + this.engines = obj.engines; + this.isBinary = obj.isBinary || false; + this.isMinifier = obj.isMinifier || false; + this.outputFormat = obj.outputFormat; + this._cache = {}; + if (typeof obj.async === 'function') { + this._renderAsync = obj.async; + this.sudoSync = obj.sudoSync || false; + } + if (typeof obj.sync === 'function') { + this._renderSync = obj.sync; + this.sync = true; + } else { + this.sync = obj.sudoSync || false; + } + + if (this.isMinifier) + minifiers[this.outputFormat] = this; + else { + var minifier = minifiers[this.outputFormat]; + if (minifier) { + this.minify = function(str, options) { + if (options && options.minify) + return minifier.renderSync(str, typeof options.minify === 'object' && options.minify || {}); + return str; + } + } + } +} + +Transformer.prototype.cache = function (options, data) { + if (options.cache && options.filename) { + if (data) return this.cache[options.filename] = data; + else return this.cache[options.filename]; + } else { + return data; + } +}; +Transformer.prototype.loadModule = function () { + if (this.engine) return this.engine; + for (var i = 0; i < this.engines.length; i++) { + try { + var res = this.engines[i] === '.' ? null : (this.engine = require(this.engines[i])); + this.engineName = this.engines[i]; + return res; + } catch (ex) { + if (this.engines.length === 1) { + throw ex; + } + } + } + throw new Error('In order to apply the transform ' + this.name + ' you must install one of ' + this.engines.map(function (e) { return '"' + e + '"'; }).join()); +}; +Transformer.prototype.minify = function(str, options) { + return str; +} +Transformer.prototype.renderSync = function (str, options) { + options = options || {}; + options = clone(options); + this.loadModule(); + if (this._renderSync) { + return this.minify(this._renderSync((this.isBinary ? str : fixString(str)), options), options); + } else if (this.sudoSync) { + options.sudoSync = true; + var res, err; + this._renderAsync((this.isBinary ? str : fixString(str)), options, function (e, val) { + if (e) err = e; + else res = val; + }); + if (err) throw err; + else if (res != undefined) return this.minify(res, options); + else if (typeof this.sudoSync === 'string') throw new Error(this.sudoSync.replace(/FILENAME/g, options.filename || '')); + else throw new Error('There was a problem transforming ' + (options.filename || '') + ' syncronously using ' + this.name); + } else { + throw new Error(this.name + ' does not support transforming syncronously.'); + } +}; +Transformer.prototype.render = function (str, options, cb) { + options = options || {}; + var self = this; + return new Promise(function (resolve, reject) { + self.loadModule(); + if (self._renderAsync) { + self._renderAsync((self.isBinary ? str : fixString(str)), clone(options), function (err, val) { + if (err) reject(err); + else resolve(self.minify(val, options)); + }) + } else { + resolve(self.renderSync(str, options)); + } + }) + .nodeify(cb); +}; +Transformer.prototype.renderFile = function (path, options, cb) { + options = options || {}; + var self = this; + return new Promise(function (resolve, reject) { + options.filename = (path = normalize(path)); + if (self._cache[path]) + resolve(null); + else + fs.readFile(path, function (err, data) { + if (err) reject(err); + else resolve(data); + }) + }) + .then(function (str) { + return self.render(str, options); + }) + .nodeify(cb); +}; +Transformer.prototype.renderFileSync = function (path, options) { + options = options || {}; + options.filename = (path = normalize(path)); + return this.renderSync((this._cache[path] ? null : fs.readFileSync(path)), options); +}; +function fixString(str) { + if (str == null) return str; + //convert buffer to string + str = str.toString(); + // Strip UTF-8 BOM if it exists + str = (0xFEFF == str.charCodeAt(0) + ? str.substring(1) + : str); + //remove `\r` added by windows + return str.replace(/\r/g, ''); +} + +function clone(obj) { + if (Array.isArray(obj)) { + return obj.map(clone); + } else if (obj && typeof obj === 'object') { + var res = {}; + for (var key in obj) { + res[key] = clone(obj[key]); + } + return res; + } else { + return obj; + } +} diff --git a/node_modules/jade/node_modules/transformers/lib/transformers.js b/node_modules/jade/node_modules/transformers/lib/transformers.js new file mode 100644 index 000000000..2ebeaa412 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/lib/transformers.js @@ -0,0 +1,575 @@ +var dirname = require('path').dirname; +var Transformer = require('./shared'); + +/** + * minifiers must be first in order to be incorporated inside instances of respective output formats + */ +var uglifyJS = require('uglify-js'); +exports.uglify = exports.uglifyJS = exports['uglify-js'] = new Transformer({ + name: 'uglify-js', + engines: ['.'], + outputFormat: 'js', + isMinifier: true, + sync: function (str, options) { + options.fromString = true; + return this.cache(options) || this.cache(options, uglifyJS.minify(str, options).code); + } +}); +var uglifyCSS = require('css'); +exports.uglifyCSS = exports['uglify-css'] = new Transformer({ + name: 'uglify-css', + engines: ['.'], + outputFormat: 'css', + isMinifier: true, + sync: function (str, options) { + options.compress = options.compress != false && options.beautify != true; + return this.cache(options) || this.cache(options, uglifyCSS.stringify(uglifyCSS.parse(str), options)); + } +}); + +exports.uglifyJSON = exports['uglify-json'] = new Transformer({ + name: 'uglify-json', + engines: ['.'], + outputFormat: 'json', + isMinifier: true, + sync: function (str, options) { + return JSON.stringify(JSON.parse(str), null, options.beautify); + } +}); + + +/** + * Syncronous Templating Languages + */ + +function sync(str, options) { + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + return tmpl(options); +} + +exports.swig = new Transformer({ + name: 'swig', + engines: ['swig'], + outputFormat: 'xml', + sync: sync +}); + +exports.atpl = new Transformer({ + name: 'atpl', + engines: ['atpl'], + outputFormat: 'xml', + sync: function sync(str, options) { + var tmpl = this.cache(options); + if (!tmpl) { + var cInfo = {cache: options.cache, filename: options.filename}; + if (options.filename) { + delete options.filename; //atpl can't handle absolute windows file paths properly + } + tmpl = this.cache(cInfo, this.engine.compile(str, options)); + } + return tmpl(options); + } +}); + +exports.dot = new Transformer({ + name: 'dot', + engines: ['dot'], + outputFormat: 'xml', + sync: function sync(str, options) { + var tmpl = this.cache(options) || this.cache(options, this.engine.template(str)); + return tmpl(options); + } +}); + +exports.liquor = new Transformer({ + name: 'liquor', + engines: ['liquor'], + outputFormat: 'xml', + sync: sync +}); + +exports.ejs = new Transformer({ + name: 'ejs', + engines: ['ejs'], + outputFormat: 'xml', + sync: sync +}); + +exports.eco = new Transformer({ + name: 'eco', + engines: ['eco'], + outputFormat: 'xml', + sync: sync//N.B. eco's internal this.cache isn't quite right but this bypasses it +}); + +exports.jqtpl = new Transformer({ + name: 'jqtpl', + engines: ['jqtpl'], + outputFormat: 'xml', + sync: function (str, options) { + var engine = this.engine; + var key = (options.cache && options.filename) ? options.filename : '@'; + engine.compile(str, key); + var res = this.engine.render(key, options); + if (!(options.cache && options.filename)) { + delete engine.cache[key]; + } + this.cache(options, true); // caching handled internally + return res; + } +}); + +exports.haml = new Transformer({ + name: 'haml', + engines: ['hamljs'], + outputFormat: 'xml', + sync: sync +}); + +exports['haml-coffee'] = new Transformer({ + name: 'haml-coffee', + engines: ['haml-coffee'], + outputFormat: 'xml', + sync: sync +}); + +exports.whiskers = new Transformer({ + name: 'whiskers', + engines: ['whiskers'], + outputFormat: 'xml', + sync: sync +}); + +exports.hogan = new Transformer({ + name: 'hogan', + engines: ['hogan.js'], + outputFormat: 'xml', + sync: function(str, options){ + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + return tmpl.render(options, options.partials); + } +}); + +exports.handlebars = new Transformer({ + name: 'handlebars', + engines: ['handlebars'], + outputFormat: 'xml', + sync: function(str, options){ + for (var partial in options.partials) { + this.engine.registerPartial(partial, options.partials[partial]); + } + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + return tmpl(options); + } +}); + +exports.underscore = new Transformer({ + name: 'underscore', + engines: ['underscore'], + outputFormat: 'xml', + sync: function(str, options){ + var tmpl = this.cache(options) || this.cache(options, this.engine.template(str)); + return tmpl(options); + } +}); + +exports.walrus = new Transformer({ + name: 'walrus', + engines: ['walrus'], + outputFormat: 'xml', + sync: function(str, options){ + var tmpl = this.cache(options) || this.cache(options, this.engine.parse(str)); + return tmpl.compile(options); + } +}); + +exports.mustache = new Transformer({ + name: 'mustache', + engines: ['mustache'], + outputFormat: 'xml', + sync: function(str, options){ + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str)); + return tmpl(options, options.partials); + } +}); + +exports.templayed = new Transformer({ + name: 'templayed', + engines: ['templayed'], + outputFormat: 'xml', + sync: function(str, options){ + var tmpl = this.cache(options) || this.cache(options, this.engine(str)); + return tmpl(options); + } +}); + +exports.plates = new Transformer({ + name: 'plates', + engines: ['plates'], + outputFormat: 'xml', + sync: function(str, options){ + str = this.cache(options) || this.cache(options, str); + return this.engine.bind(str, options, options.map); + } +}); + +exports.mote = new Transformer({ + name: 'mote', + engines: ['mote'], + outputFormat: 'xml', + sync: sync +}); + +exports.toffee = new Transformer({ + name: 'toffee', + engines: ['toffee'], + outputFormat: 'xml', + sync: function (str, options) { + var View = this.engine.view; + var v = this.cache(options) || this.cache(options, new View(str, options)); + var res = v.run(options, require('vm').createContext({})); + if (res[0]) throw res[0]; + else return res[1]; + } +}); + +exports.coffeekup = exports.coffeecup = new Transformer({ + name: 'coffeecup', + engines: ['coffeecup', 'coffeekup'], + outputFormat: 'xml', + sync: function (str, options) { + var compiled = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + return compiled(options); + } +}); + +/** + * Asyncronous Templating Languages + */ + +exports.just = new Transformer({ + name: 'just', + engines: ['just'], + outputFormat: 'xml', + sudoSync: true, + async: function (str, options, cb) { + var JUST = this.engine; + var tmpl = this.cache(options) || this.cache(options, new JUST({ root: { page: str }})); + tmpl.render('page', options, cb); + } +}); + +exports.ect = new Transformer({ + name: 'ect', + engines: ['ect'], + outputFormat: 'xml', + sudoSync: true, // Always runs syncronously + async: function (str, options, cb) { + var ECT = this.engine; + var tmpl = this.cache(options) || this.cache(options, new ECT({ root: { page: str }})); + tmpl.render('page', options, cb); + } +}); + +exports.jade = new Transformer({ + name: 'jade', + engines: ['jade', 'then-jade'], + outputFormat: 'xml', + sudoSync: 'The jade file FILENAME could not be rendered syncronously. N.B. then-jade does not support syncronous rendering.', + async: function (str, options, cb) { + this.cache(options, true);//jade handles this.cache internally + this.engine.render(str, options, cb); + } +}) + +exports.dust = new Transformer({ + name: 'dust', + engines: ['dust', 'dustjs-linkedin'], + outputFormat: 'xml', + sudoSync: false, + async: function (str, options, cb) { + var ext = 'dust' + , views = '.'; + + if (options) { + if (options.ext) ext = options.ext; + if (options.views) views = options.views; + if (options.settings && options.settings.views) views = options.settings.views; + } + + this.engine.onLoad = function(path, callback){ + if ('' == extname(path)) path += '.' + ext; + if ('/' !== path[0]) path = views + '/' + path; + read(path, options, callback); + }; + + var tmpl = this.cache(options) || this.cache(options, this.engine.compileFn(str)); + if (options && !options.cache) this.engine.cache = {};//invalidate dust's internal cache + tmpl(options, cb); + } +}); + +exports.jazz = new Transformer({ + name: 'jazz', + engines: ['jazz'], + outputFormat: 'xml', + sudoSync: true, // except when an async function is passed to locals + async: function (str, options, cb) { + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + tmpl.eval(options, function(str){ + cb(null, str); + }); + } +}); + +exports.qejs = new Transformer({ + name: 'qejs', + engines: ['qejs'], + outputFormat: 'xml', + sudoSync: false, + async: function (str, options, cb) { + var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); + tmpl(options).done(function (result) { + cb(null, result); + }, function (err) { + cb(err); + }); + } +}); + +/** + * Stylsheet Languages + */ + +exports.less = new Transformer({ + name: 'less', + engines: ['less'], + outputFormat: 'css', + sudoSync: 'The less file FILENAME could not be rendered syncronously. This is usually because the file contains `@import url` statements.', + async: function (str, options, cb) { + var self = this; + if (self.cache(options)) return cb(null, self.cache(options)); + if (options.filename) { + options.paths = options.paths || [dirname(options.filename)]; + } + //If this.cache is enabled, compress by default + if (options.compress !== true && options.compress !== false) { + options.compress = options.cache || false; + } + if (options.sudoSync) { + options.syncImport = true; + } + var parser = new(this.engine.Parser)(options); + parser.parse(str, function (err, tree) { + try { + if (err) throw err; + var res = tree.toCSS(options); + self.cache(options, res); + cb(null, res); + } catch (ex) { + if (!(ex instanceof Error) && typeof ex === 'object') { + ex.filename = ex.filename || '"Unkown Source"'; + var err = new Error(self.engine.formatError(ex, options).replace(/^[^:]+:/, ''), ex.filename, ex.line); + err.name = ex.type; + ex = err; + } + console.log('\n\n' + ex.stack + '\n\n'); + return cb(ex); + } + }); + } +}); + +exports.styl = exports.stylus = new Transformer({ + name: 'stylus', + engines: ['stylus'], + outputFormat: 'css', + sudoSync: true,// always runs syncronously + async: function (str, options, cb) { + var self = this; + if (self.cache(options)) return cb(null, self.cache(options)); + if (options.filename) { + options.paths = options.paths || [dirname(options.filename)]; + } + //If this.cache is enabled, compress by default + if (options.compress !== true && options.compress !== false) { + options.compress = options.cache || false; + } + this.engine.render(str, options, function (err, res) { + if (err) return cb(err); + self.cache(options, res); + cb(null, res); + }); + } +}) + +exports.sass = new Transformer({ + name: 'sass', + engines: ['sass'], + outputFormat: 'css', + sync: function (str, options) { + try { + return this.cache(options) || this.cache(options, this.engine.render(str)); + } catch (ex) { + if (options.filename) ex.message += ' in ' + options.filename; + throw ex; + } + } +}); + +/** + * Miscelaneous + */ + +exports.md = exports.markdown = new Transformer({ + name: 'markdown', + engines: ['marked', 'supermarked', 'markdown-js', 'markdown'], + outputFormat: 'html', + sync: function (str, options) { + var arg = options; + if (this.engineName === 'markdown') arg = options.dialect; //even if undefined + return this.cache(options) || this.cache(options, this.engine.parse(str, arg)); + } +}); + + +exports.coffee = exports['coffee-script'] = exports.coffeescript = exports.coffeeScript = new Transformer({ + name: 'coffee-script', + engines: ['coffee-script'], + outputFormat: 'js', + sync: function (str, options) { + return this.cache(options) || this.cache(options, this.engine.compile(str, options)); + } +}); + +exports.cson = new Transformer({ + name: 'cson', + engines: ['cson'], + outputFormat: 'json', + sync: function (str, options) { + //todo: remove once https://github.com/rstacruz/js2coffee/pull/174 accepted & released + if (global.Narcissus) delete global.Narcissus; //prevent global leak + return this.cache(options) || this.cache(options, JSON.stringify(this.engine.parseSync(str))); + } +}); + +exports.cdata = new Transformer({ + name: 'cdata', + engines: ['.'],// `.` means "no dependency" + outputFormat: 'xml', + sync: function (str, options) { + return this.cache(options) || this.cache(options, ''); + } +}); + +exports.component = exports['component-js'] = new Transformer({ + name: 'component-js', + engines: ['component-builder'], + outputFormat: 'js', + async: function (str, options, cb) { + if (this.cache(options)) return this.cache(options); + var self = this; + var builder = new this.engine(dirname(options.filename)); + if (options.development) { + builder.development(); + } + if (options.sourceURLs === true || (options.sourceURLs !== false && options.development)) { + builder.addSourceURLs(); + } + var path = require('path'); + builder.paths = (options.paths || ['components']).map(function (p) { + if (path.resolve(p) === p) { + return p; + } else { + return path.join(dirname(options.filename), p); + } + }); + builder.build(function (err, obj) { + if (err) return cb(err); + else return cb(null, self.cache(options, obj.require + obj.js)); + }); + } +}); + +exports['component-css'] = new Transformer({ + name: 'component-css', + engines: ['component-builder'], + outputFormat: 'css', + async: function (str, options, cb) { + if (this.cache(options)) return this.cache(options); + var self = this; + var builder = new this.engine(dirname(options.filename)); + if (options.development) { + builder.development(); + } + if (options.sourceURLs === true || (options.sourceURLs !== false && options.development)) { + builder.addSourceURLs(); + } + var path = require('path'); + builder.paths = (options.paths || ['components']).map(function (p) { + if (path.resolve(p) === p) { + return p; + } else { + return path.join(dirname(options.filename), p); + } + }); + builder.build(function (err, obj) { + if (err) return cb(err); + else return cb(null, self.cache(options, obj.css)); + }); + } +}); + +exports['html2jade'] = new Transformer({ + name: 'html2jade', + engines: ['html2jade'], + outputFormat: 'jade', + async: function (str, options, cb) { + return this.cache(options) || this.cache(options, this.engine.convertHtml(str, options, cb)); + } +}); + +exports['highlight'] = new Transformer({ + name: 'highlight', + engines: ['highlight.js'], + outputFormat: 'xml', + sync: function (str, options, cb) { + if (this.cache(options)) return this.cache(options); + if (options.lang) { + try { + return this.cache(options, this.engine.highlight(options.lang, str).value); + } catch (ex) {} + } + if (options.auto || !options.lang) { + try { + return this.cache(options, this.engine.highlightAuto(str).value); + } catch (ex) {} + } + return this.cache(options, str); + } +}); + + +/** + * Marker transformers (they don't actually apply a transformation, but let you declare the 'outputFormat') + */ + +exports.css = new Transformer({ + name: 'css', + engines: ['.'],// `.` means "no dependency" + outputFormat: 'css', + sync: function (str, options) { + return this.cache(options) || this.cache(options, str); + } +}); + +exports.js = new Transformer({ + name: 'js', + engines: ['.'],// `.` means "no dependency" + outputFormat: 'js', + sync: function (str, options) { + return this.cache(options) || this.cache(options, str); + } +}); + + diff --git a/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs b/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs new file mode 100644 index 000000000..27606b8e5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@" + ret=$? +else + node "$basedir/../uglify-js/bin/uglifyjs" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs.cmd b/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs.cmd new file mode 100644 index 000000000..88ff40f5d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/.bin/uglifyjs.cmd @@ -0,0 +1,5 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\uglify-js\bin\uglifyjs" %* +) ELSE ( + node "%~dp0\..\uglify-js\bin\uglifyjs" %* +) \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/css/.npmignore new file mode 100644 index 000000000..f1250e584 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/History.md b/node_modules/jade/node_modules/transformers/node_modules/css/History.md new file mode 100644 index 000000000..93b15c2f6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/History.md @@ -0,0 +1,20 @@ + +1.0.7 / 2012-11-21 +================== + + * fix component.json + +1.0.4 / 2012-11-15 +================== + + * update css-stringify + +1.0.3 / 2012-09-01 +================== + + * add component support + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/Makefile b/node_modules/jade/node_modules/transformers/node_modules/css/Makefile new file mode 100644 index 000000000..f13b4a784 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/Makefile @@ -0,0 +1,8 @@ + +test: + @node test + +benchmark: + @node benchmark + +.PHONY: test benchmark \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/Readme.md b/node_modules/jade/node_modules/transformers/node_modules/css/Readme.md new file mode 100644 index 000000000..cf578dfed --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/Readme.md @@ -0,0 +1,77 @@ + +# css + + CSS parser / stringifier using [css-parse](https://github.com/visionmedia/css-parse) and [css-stringify](https://github.com/visionmedia/css-stringify). + +## Installation + + $ npm install css + +## Example + +js: + +```js +var css = require('css') +var obj = css.parse('tobi { name: "tobi" }') +css.stringify(obj); +``` + +object returned by `.parse()`: + +```json +{ + "stylesheet": { + "rules": [ + { + "selector": "tobi", + "declarations": [ + { + "property": "name", + "value": "tobi" + } + ] + } + ] + } +} +``` + +string returned by `.stringify(ast)`: + +```css +tobi { + name: tobi; +} +``` + +string returned by `.stringify(ast, { compress: true })`: + +```css +tobi{name:tobi} +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/benchmark.js b/node_modules/jade/node_modules/transformers/node_modules/css/benchmark.js new file mode 100644 index 000000000..dec711dc2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/benchmark.js @@ -0,0 +1,36 @@ + +var css = require('./') + , fs = require('fs') + , read = fs.readFileSync + , str = read('examples/ui.css', 'utf8'); + +var n = 5000; +var ops = 200; +var t = process.hrtime(t); +var results = []; + +while (n--) { + css.stringify(css.parse(str)); + if (n % ops == 0) { + t = process.hrtime(t); + var ms = t[1] / 1000 / 1000; + var persec = (ops * (1000 / ms) | 0); + results.push(persec); + process.stdout.write('\r [' + persec + ' ops/s] [' + n + ']'); + t = process.hrtime(); + } +} + +function sum(arr) { + return arr.reduce(function(sum, n){ + return sum + n; + }); +} + +function mean(arr) { + return sum(arr) / arr.length | 0; +} + +console.log(); +console.log(' avg: %d ops/s', mean(results)); +console.log(' size: %d kb', (str.length / 1024).toFixed(2)); \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/component.json b/node_modules/jade/node_modules/transformers/node_modules/css/component.json new file mode 100644 index 000000000..27691659b --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/component.json @@ -0,0 +1,13 @@ +{ + "name": "css", + "version": "1.0.8", + "description": "CSS parser / stringifier using css-parse and css-stringify", + "keywords": ["css", "parser", "stylesheet"], + "dependencies": { + "visionmedia/css-parse": "*", + "visionmedia/css-stringify": "*" + }, + "scripts": [ + "index.js" + ] +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/index.js b/node_modules/jade/node_modules/transformers/node_modules/css/index.js new file mode 100644 index 000000000..19ec91a14 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/index.js @@ -0,0 +1,3 @@ + +exports.parse = require('css-parse'); +exports.stringify = require('css-stringify'); diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/.npmignore new file mode 100644 index 000000000..4a3c398e9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +*.sock +test.css +test.js diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/History.md b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/History.md new file mode 100644 index 000000000..5276aab43 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/History.md @@ -0,0 +1,30 @@ + +1.0.4 / 2012-09-17 +================== + + * fix keyframes float percentages + * fix an issue with comments containing slashes. + +1.0.3 / 2012-09-01 +================== + + * add component support + * fix unquoted data uris [rstacruz] + * fix keyframe names with no whitespace [rstacruz] + * fix excess semicolon support [rstacruz] + +1.0.2 / 2012-09-01 +================== + + * fix IE property hack support [rstacruz] + * fix quoted strings in declarations [rstacruz] + +1.0.1 / 2012-07-26 +================== + + * change "selector" to "selectors" array + +1.0.0 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Makefile b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Makefile new file mode 100644 index 000000000..4e9c8d36e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Readme.md b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Readme.md new file mode 100644 index 000000000..fde74a5b1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/Readme.md @@ -0,0 +1,62 @@ + +# css-parse + + CSS parser. + +## Example + +js: + +```js +var parse = require('css-parse') +parse('tobi { name: "tobi" }') +``` + +object returned: + +```json +{ + "stylesheet": { + "rules": [ + { + "selectors": ["tobi"], + "declarations": [ + { + "property": "name", + "value": "tobi" + } + ] + } + ] + } +} +``` + +## Performance + + Parsed 15,000 lines of CSS (2mb) in 40ms on my macbook air. + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/component.json b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/component.json new file mode 100644 index 000000000..234ebbead --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/component.json @@ -0,0 +1,8 @@ +{ + "name": "css-parse", + "repo": "visionmedia/node-css-parse", + "version": "1.0.3", + "description": "CSS parser", + "keywords": ["css", "parser", "stylesheet"], + "scripts": ["index.js"] +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/index.js b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/index.js new file mode 100644 index 000000000..3ed278fa2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/index.js @@ -0,0 +1,265 @@ + +module.exports = function(css){ + + /** + * Parse stylesheet. + */ + + function stylesheet() { + return { stylesheet: { rules: rules() }}; + } + + /** + * Opening brace. + */ + + function open() { + return match(/^{\s*/); + } + + /** + * Closing brace. + */ + + function close() { + return match(/^}\s*/); + } + + /** + * Parse ruleset. + */ + + function rules() { + var node; + var rules = []; + whitespace(); + comments(); + while (css[0] != '}' && (node = atrule() || rule())) { + comments(); + rules.push(node); + } + return rules; + } + + /** + * Match `re` and return captures. + */ + + function match(re) { + var m = re.exec(css); + if (!m) return; + css = css.slice(m[0].length); + return m; + } + + /** + * Parse whitespace. + */ + + function whitespace() { + match(/^\s*/); + } + + /** + * Parse comments; + */ + + function comments() { + while (comment()) ; + } + + /** + * Parse comment. + */ + + function comment() { + if ('/' == css[0] && '*' == css[1]) { + var i = 2; + while ('*' != css[i] || '/' != css[i + 1]) ++i; + i += 2; + css = css.slice(i); + whitespace(); + return true; + } + } + + /** + * Parse selector. + */ + + function selector() { + var m = match(/^([^{]+)/); + if (!m) return; + return m[0].trim().split(/\s*,\s*/); + } + + /** + * Parse declaration. + */ + + function declaration() { + // prop + var prop = match(/^(\*?[-\w]+)\s*/); + if (!prop) return; + prop = prop[0]; + + // : + if (!match(/^:\s*/)) return; + + // val + var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)\s*/); + if (!val) return; + val = val[0].trim(); + + // ; + match(/^[;\s]*/); + + return { property: prop, value: val }; + } + + /** + * Parse keyframe. + */ + + function keyframe() { + var m; + var vals = []; + + while (m = match(/^(from|to|\d+%|\.\d+%|\d+\.\d+%)\s*/)) { + vals.push(m[1]); + match(/^,\s*/); + } + + if (!vals.length) return; + + return { + values: vals, + declarations: declarations() + }; + } + + /** + * Parse keyframes. + */ + + function keyframes() { + var m = match(/^@([-\w]+)?keyframes */); + if (!m) return; + var vendor = m[1]; + + // identifier + var m = match(/^([-\w]+)\s*/); + if (!m) return; + var name = m[1]; + + if (!open()) return; + comments(); + + var frame; + var frames = []; + while (frame = keyframe()) { + frames.push(frame); + comments(); + } + + if (!close()) return; + + return { + name: name, + vendor: vendor, + keyframes: frames + }; + } + + /** + * Parse media. + */ + + function media() { + var m = match(/^@media *([^{]+)/); + if (!m) return; + var media = m[1].trim(); + + if (!open()) return; + comments(); + + var style = rules(); + + if (!close()) return; + + return { media: media, rules: style }; + } + + /** + * Parse import + */ + + function atimport() { + return _atrule('import') + } + + /** + * Parse charset + */ + + function atcharset() { + return _atrule('charset'); + } + + /** + * Parse non-block at-rules + */ + + function _atrule(name) { + var m = match(new RegExp('^@' + name + ' *([^;\\n]+);\\s*')); + if (!m) return; + var ret = {} + ret[name] = m[1].trim(); + return ret; + } + + /** + * Parse declarations. + */ + + function declarations() { + var decls = []; + + if (!open()) return; + comments(); + + // declarations + var decl; + while (decl = declaration()) { + decls.push(decl); + comments(); + } + + if (!close()) return; + return decls; + } + + /** + * Parse at rule. + */ + + function atrule() { + return keyframes() + || media() + || atimport() + || atcharset(); + } + + /** + * Parse rule. + */ + + function rule() { + var sel = selector(); + if (!sel) return; + comments(); + return { selectors: sel, declarations: declarations() }; + } + + return stylesheet(); +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/package.json b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/package.json new file mode 100644 index 000000000..01be9c0ee --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-parse/package.json @@ -0,0 +1,39 @@ +{ + "name": "css-parse", + "version": "1.0.4", + "description": "CSS parser", + "keywords": [ + "css", + "parser", + "stylesheet" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "main": "index", + "_id": "css-parse@1.0.4", + "dist": { + "shasum": "38b0503fbf9da9f54e9c1dbda60e145c77117bdd", + "tarball": "http://registry.npmjs.org/css-parse/-/css-parse-1.0.4.tgz" + }, + "_npmVersion": "1.1.61", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "38b0503fbf9da9f54e9c1dbda60e145c77117bdd", + "_from": "css-parse@1.0.4", + "_resolved": "https://registry.npmjs.org/css-parse/-/css-parse-1.0.4.tgz" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/.npmignore new file mode 100644 index 000000000..4a3c398e9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +*.sock +test.css +test.js diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/History.md b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/History.md new file mode 100644 index 000000000..a6ff960f1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/History.md @@ -0,0 +1,30 @@ + +1.0.5 / 2013-03-15 +================== + + * fix indentation of multiple selectors in @media. Closes #11 + +1.0.4 / 2012-11-15 +================== + + * fix indentation + +1.0.3 / 2012-09-04 +================== + + * add __@charset__ support [rstacruz] + +1.0.2 / 2012-09-01 +================== + + * add component support + +1.0.1 / 2012-07-26 +================== + + * add "selectors" array support + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Makefile b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Makefile new file mode 100644 index 000000000..4e9c8d36e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Readme.md b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Readme.md new file mode 100644 index 000000000..a36e7803d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/Readme.md @@ -0,0 +1,33 @@ + +# css-stringify + + CSS compiler using the AST provided by [css-parse](https://github.com/visionmedia/css-parse). + +## Performance + + Formats 15,000 lines of CSS (2mb) in 23ms on my macbook air. + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/component.json b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/component.json new file mode 100644 index 000000000..259baef07 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/component.json @@ -0,0 +1,8 @@ +{ + "name": "css-stringify", + "repo": "visionmedia/css-stringify", + "version": "1.0.5", + "description": "CSS compiler", + "keywords": ["css", "stringify", "stylesheet"], + "scripts": ["index.js"] +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/index.js b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/index.js new file mode 100644 index 000000000..f528e41e5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/index.js @@ -0,0 +1,182 @@ + +/** + * Stringfy the given AST `node`. + * + * @param {Object} node + * @param {Object} options + * @return {String} + * @api public + */ + +module.exports = function(node, options){ + return new Compiler(options).compile(node); +}; + +/** + * Initialize a new `Compiler`. + */ + +function Compiler(options) { + options = options || {}; + this.compress = options.compress; + this.indentation = options.indent; +} + +/** + * Compile `node`. + */ + +Compiler.prototype.compile = function(node){ + return node.stylesheet.rules.map(this.visit, this) + .join(this.compress ? '' : '\n\n'); +}; + +/** + * Visit `node`. + */ + +Compiler.prototype.visit = function(node){ + if (node.charset) return this.charset(node); + if (node.keyframes) return this.keyframes(node); + if (node.media) return this.media(node); + if (node.import) return this.import(node); + return this.rule(node); +}; + +/** + * Visit import node. + */ + +Compiler.prototype.import = function(node){ + return '@import ' + node.import + ';'; +}; + +/** + * Visit media node. + */ + +Compiler.prototype.media = function(node){ + if (this.compress) { + return '@media ' + + node.media + + '{' + + node.rules.map(this.visit, this).join('') + + '}'; + } + + return '@media ' + + node.media + + ' {\n' + + this.indent(1) + + node.rules.map(this.visit, this).join('\n\n') + + this.indent(-1) + + '\n}'; +}; + +/** + * Visit charset node. + */ + +Compiler.prototype.charset = function(node){ + if (this.compress) { + return '@charset ' + node.charset + ';'; + } + + return '@charset ' + node.charset + ';\n'; +}; + +/** + * Visit keyframes node. + */ + +Compiler.prototype.keyframes = function(node){ + if (this.compress) { + return '@' + + (node.vendor || '') + + 'keyframes ' + + node.name + + '{' + + node.keyframes.map(this.keyframe, this).join('') + + '}'; + } + + return '@' + + (node.vendor || '') + + 'keyframes ' + + node.name + + ' {\n' + + this.indent(1) + + node.keyframes.map(this.keyframe, this).join('\n') + + this.indent(-1) + + '}'; +}; + +/** + * Visit keyframe node. + */ + +Compiler.prototype.keyframe = function(node){ + if (this.compress) { + return node.values.join(',') + + '{' + + node.declarations.map(this.declaration, this).join(';') + + '}'; + } + + return this.indent() + + node.values.join(', ') + + ' {\n' + + this.indent(1) + + node.declarations.map(this.declaration, this).join(';\n') + + this.indent(-1) + + '\n' + this.indent() + '}\n'; +}; + +/** + * Visit rule node. + */ + +Compiler.prototype.rule = function(node){ + var indent = this.indent(); + + if (this.compress) { + return node.selectors.join(',') + + '{' + + node.declarations.map(this.declaration, this).join(';') + + '}'; + } + + return node.selectors.map(function(s){ return indent + s }).join(',\n') + + ' {\n' + + this.indent(1) + + node.declarations.map(this.declaration, this).join(';\n') + + this.indent(-1) + + '\n' + this.indent() + '}'; +}; + +/** + * Visit declaration node. + */ + +Compiler.prototype.declaration = function(node){ + if (this.compress) { + return node.property + ':' + node.value; + } + + return this.indent() + node.property + ': ' + node.value; +}; + +/** + * Increase, decrease or return current indentation. + */ + +Compiler.prototype.indent = function(level) { + this.level = this.level || 1; + + if (null != level) { + this.level += level; + return ''; + } + + return Array(this.level).join(this.indentation || ' '); +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/package.json b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/package.json new file mode 100644 index 000000000..de08dd225 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/node_modules/css-stringify/package.json @@ -0,0 +1,40 @@ +{ + "name": "css-stringify", + "version": "1.0.5", + "description": "CSS compiler", + "keywords": [ + "css", + "stringify", + "stylesheet" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "devDependencies": { + "mocha": "*", + "should": "*", + "css-parse": "1.0.3" + }, + "main": "index", + "_id": "css-stringify@1.0.5", + "dist": { + "shasum": "b0d042946db2953bb9d292900a6cb5f6d0122031", + "tarball": "http://registry.npmjs.org/css-stringify/-/css-stringify-1.0.5.tgz" + }, + "_from": "css-stringify@1.0.5", + "_npmVersion": "1.2.14", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "b0d042946db2953bb9d292900a6cb5f6d0122031", + "_resolved": "https://registry.npmjs.org/css-stringify/-/css-stringify-1.0.5.tgz" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/package.json b/node_modules/jade/node_modules/transformers/node_modules/css/package.json new file mode 100644 index 000000000..638ae9638 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/package.json @@ -0,0 +1,23 @@ +{ + "name": "css", + "version": "1.0.8", + "description": "CSS parser / stringifier using css-parse and css-stringify", + "keywords": [ + "css", + "parser", + "stylesheet" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": { + "css-parse": "1.0.4", + "css-stringify": "1.0.5" + }, + "main": "index", + "readme": "\n# css\n\n CSS parser / stringifier using [css-parse](https://github.com/visionmedia/css-parse) and [css-stringify](https://github.com/visionmedia/css-stringify).\n\n## Installation\n\n $ npm install css\n\n## Example\n\njs:\n\n```js\nvar css = require('css')\nvar obj = css.parse('tobi { name: \"tobi\" }')\ncss.stringify(obj);\n```\n\nobject returned by `.parse()`:\n\n```json\n{\n \"stylesheet\": {\n \"rules\": [\n {\n \"selector\": \"tobi\",\n \"declarations\": [\n {\n \"property\": \"name\",\n \"value\": \"tobi\"\n }\n ]\n }\n ]\n }\n}\n```\n\nstring returned by `.stringify(ast)`:\n\n```css\ntobi {\n name: tobi;\n}\n```\n\nstring returned by `.stringify(ast, { compress: true })`:\n\n```css\ntobi{name:tobi}\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md", + "_id": "css@1.0.8", + "_from": "css@~1.0.8" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/css/test.js b/node_modules/jade/node_modules/transformers/node_modules/css/test.js new file mode 100644 index 000000000..3e1b4d3f0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/css/test.js @@ -0,0 +1,6 @@ + +var css = require('./') + , assert = require('assert'); + +assert(css.parse); +assert(css.stringify); diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/promise/.npmignore new file mode 100644 index 000000000..11952487a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/.npmignore @@ -0,0 +1,6 @@ +components +node_modules +test +.gitignore +.travis.yml +component.json \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/Readme.md b/node_modules/jade/node_modules/transformers/node_modules/promise/Readme.md new file mode 100644 index 000000000..2b9dfe93c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/Readme.md @@ -0,0 +1,85 @@ +[![Build Status](https://travis-ci.org/then/promise.png)](https://travis-ci.org/then/promise) + +# promise + + This a bare bones [Promises/A+](http://promises-aplus.github.com/promises-spec/) implementation. + + It is designed to get the basics spot on correct, so that you can build extended promise implementations on top of it. + +## Installation + + Server: + + $ npm install promise + + Client: + + $ component install then/promise + +## API + + In the example below shows how you can load the promise library (in a way that works on both client and server). It then demonstrates creating a promise from scratch. You simply call `new Promise(fn)`. There is a complete specification for what is returned by this method in [Promises/A+](http://promises-aplus.github.com/promises-spec/). + +```javascript +var Promise = require('promise'); + +var promise = new Promise(function (resolve, reject) { + get('http://www.google.com', function (err, res) { + if (err) reject(err); + else resolve(res); + }); + }); +``` + +## Extending Promises + + There are three options for extending the promises created by this library. + +### Inheritance + + You can use inheritance if you want to create your own complete promise library with this as your basic starting point, perfect if you have lots of cool features you want to add. Here is an example of a promise library called `Awesome`, which is built on top of `Promise` correctly. + +```javascript +var Promise = require('promise'); +function Awesome(fn) { + if (!(this instanceof Awesome)) return new Awesome(fn); + Promise.call(this, fn); +} +Awesome.prototype = Object.create(Promise.prototype); +Awesome.prototype.constructor = Awesome; + +//Awesome extension +Awesome.prototype.spread = function (cb) { + return this.then(function (arr) { + return cb.apply(this, arr); + }) +}; +``` + + N.B. if you fail to set the prototype and constructor properly or fail to do Promise.call, things can fail in really subtle ways. + +### Wrap + + This is the nuclear option, for when you want to start from scratch. It ensures you won't be impacted by anyone who is extending the prototype (see below). + +```javascript +function Uber(fn) { + if (!(this instanceof Uber)) return new Uber(fn); + var _prom = new Promise(fn); + this.then = _prom.then; +} + +Uber.prototype.spread = function (cb) { + return this.then(function (arr) { + return cb.apply(this, arr); + }) +}; +``` + +### Extending the Prototype + + In general, you should never extend the prototype of this promise implimenation because your extensions could easily conflict with someone elses extensions. However, this organisation will host a library of extensions which do not conflict with each other, so you can safely enable any of those. If you think of an extension that we don't provide and you want to write it, submit an issue on this repository and (if I agree) I'll set you up with a repository and give you permission to commit to it. + +## License + + MIT diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/index.js b/node_modules/jade/node_modules/transformers/node_modules/promise/index.js new file mode 100644 index 000000000..492eb99c9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/index.js @@ -0,0 +1,164 @@ +var isPromise = require('is-promise') + +var nextTick +if (typeof setImediate === 'function') nextTick = setImediate +else if (typeof process === 'object' && process && process.nextTick) nextTick = process.nextTick +else nextTick = function (cb) { setTimeout(cb, 0) } + +var extensions = [] + +module.exports = Promise +function Promise(fn) { + if (!(this instanceof Promise)) { + return fn ? new Promise(fn) : defer() + } + if (typeof fn !== 'function') { + throw new TypeError('fn is not a function') + } + + var state = { + isResolved: false, + isSettled: false, + isFulfilled: false, + value: null, + waiting: [], + running: false + } + + function _resolve(val) { + resolve(state, val); + } + function _reject(err) { + reject(state, err); + } + this.then = function _then(onFulfilled, onRejected) { + return then(state, onFulfilled, onRejected); + } + + _resolve.fulfill = deprecate(_resolve, 'resolver.fulfill(x)', 'resolve(x)') + _resolve.reject = deprecate(_reject, 'resolver.reject', 'reject(x)') + + try { + fn(_resolve, _reject) + } catch (ex) { + _reject(ex) + } +} + +function resolve(promiseState, value) { + if (promiseState.isResolved) return + if (isPromise(value)) { + assimilate(promiseState, value) + } else { + settle(promiseState, true, value) + } +} + +function reject(promiseState, reason) { + if (promiseState.isResolved) return + settle(promiseState, false, reason) +} + +function then(promiseState, onFulfilled, onRejected) { + return new Promise(function (resolve, reject) { + function done(next, skipTimeout) { + var callback = promiseState.isFulfilled ? onFulfilled : onRejected + if (typeof callback === 'function') { + function timeoutDone() { + var val + try { + val = callback(promiseState.value) + } catch (ex) { + reject(ex) + return next(true) + } + resolve(val) + next(true) + } + if (skipTimeout) timeoutDone() + else nextTick(timeoutDone) + } else if (promiseState.isFulfilled) { + resolve(promiseState.value) + next(skipTimeout) + } else { + reject(promiseState.value) + next(skipTimeout) + } + } + promiseState.waiting.push(done) + if (promiseState.isSettled && !promiseState.running) processQueue(promiseState) + }) +} + +function processQueue(promiseState) { + function next(skipTimeout) { + if (promiseState.waiting.length) { + promiseState.running = true + promiseState.waiting.shift()(next, skipTimeout) + } else { + promiseState.running = false + } + } + next(false) +} + +function settle(promiseState, isFulfilled, value) { + if (promiseState.isSettled) return + + promiseState.isResolved = promiseState.isSettled = true + promiseState.value = value + promiseState.isFulfilled = isFulfilled + + processQueue(promiseState) +} + +function assimilate(promiseState, thenable) { + try { + promiseState.isResolved = true + thenable.then(function (res) { + if (isPromise(res)) { + assimilate(promiseState, res) + } else { + settle(promiseState, true, res) + } + }, function (err) { + settle(promiseState, false, err) + }) + } catch (ex) { + settle(promiseState, false, ex) + } +} + +Promise.use = function (extension) { + extensions.push(extension) +} + + +function deprecate(method, name, alternative) { + return function () { + var err = new Error(name + ' is deprecated use ' + alternative) + if (typeof console !== 'undefined' && console && typeof console.warn === 'function') { + console.warn(name + ' is deprecated use ' + alternative) + if (err.stack) console.warn(err.stack) + } else { + nextTick(function () { + throw err + }) + } + method.apply(this, arguments) + } +} +function defer() { + var err = new Error('promise.defer() is deprecated') + if (typeof console !== 'undefined' && console && typeof console.warn === 'function') { + console.warn('promise.defer() is deprecated') + if (err.stack) console.warn(err.stack) + } else { + nextTick(function () { + throw err + }) + } + var resolver + var promise = new Promise(function (res) { resolver = res }) + return {resolver: resolver, promise: promise} +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.npmignore new file mode 100644 index 000000000..aeb7b4536 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.npmignore @@ -0,0 +1,6 @@ +component +build +node_modules +test.js +component.json +.gitignore \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.travis.yml b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.travis.yml new file mode 100644 index 000000000..87f8cd91a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/LICENSE b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/LICENSE new file mode 100644 index 000000000..27cc9f377 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Forbes Lindesay + +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. \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/index.js b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/index.js new file mode 100644 index 000000000..776c3a5d2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/index.js @@ -0,0 +1,5 @@ +module.exports = isPromise; + +function isPromise(obj) { + return obj && typeof obj.then === 'function'; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/package.json b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/package.json new file mode 100644 index 000000000..27422face --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/package.json @@ -0,0 +1,29 @@ +{ + "name": "is-promise", + "version": "1.0.1", + "description": "Test whether an object looks like a promises-a+ promise", + "main": "index.js", + "scripts": { + "test": "mocha -R spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/then/is-promise.git" + }, + "author": { + "name": "ForbesLindesay" + }, + "license": "MIT", + "devDependencies": { + "better-assert": "~0.1.0", + "mocha": "~1.7.4" + }, + "readme": "\r\n# is-promise\r\n\r\n Test whether an object looks like a promises-a+ promise\r\n\r\n [![Build Status](https://img.shields.io/travis/then/is-promise/master.svg)](https://travis-ci.org/then/is-promise)\r\n [![Dependency Status](https://img.shields.io/gemnasium/then/is-promise.svg)](https://gemnasium.com/then/is-promise)\r\n [![NPM version](https://img.shields.io/npm/v/is-promise.svg)](https://www.npmjs.org/package/is-promise)\r\n\r\n## Installation\r\n\r\n $ npm install is-promise\r\n\r\nYou can also use it client side via npm.\r\n\r\n## API\r\n\r\n```javascript\r\nvar isPromise = require('is-promise');\r\n\r\nisPromise({then:function () {...}});//=>true\r\nisPromise(null);//=>false\r\nisPromise({});//=>false\r\nisPromise({then: true})//=>false\r\n```\r\n\r\n## License\r\n\r\n MIT\r\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/then/is-promise/issues" + }, + "homepage": "https://github.com/then/is-promise", + "_id": "is-promise@1.0.1", + "_from": "is-promise@~1" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/readme.md b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/readme.md new file mode 100644 index 000000000..50d5d9891 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/node_modules/is-promise/readme.md @@ -0,0 +1,29 @@ + +# is-promise + + Test whether an object looks like a promises-a+ promise + + [![Build Status](https://img.shields.io/travis/then/is-promise/master.svg)](https://travis-ci.org/then/is-promise) + [![Dependency Status](https://img.shields.io/gemnasium/then/is-promise.svg)](https://gemnasium.com/then/is-promise) + [![NPM version](https://img.shields.io/npm/v/is-promise.svg)](https://www.npmjs.org/package/is-promise) + +## Installation + + $ npm install is-promise + +You can also use it client side via npm. + +## API + +```javascript +var isPromise = require('is-promise'); + +isPromise({then:function () {...}});//=>true +isPromise(null);//=>false +isPromise({});//=>false +isPromise({then: true})//=>false +``` + +## License + + MIT diff --git a/node_modules/jade/node_modules/transformers/node_modules/promise/package.json b/node_modules/jade/node_modules/transformers/node_modules/promise/package.json new file mode 100644 index 000000000..b1a3dcf4c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/promise/package.json @@ -0,0 +1,33 @@ +{ + "name": "promise", + "version": "2.0.0", + "description": "Bare bones Promises/A+ implementation", + "main": "index.js", + "scripts": { + "test": "mocha -R spec --timeout 200 --slow 99999" + }, + "repository": { + "type": "git", + "url": "https://github.com/then/promise.git" + }, + "author": { + "name": "ForbesLindesay" + }, + "license": "MIT", + "dependencies": { + "is-promise": "~1" + }, + "devDependencies": { + "promises-aplus-tests": "*", + "mocha-as-promised": "~1.2.1", + "better-assert": "~1.0.0" + }, + "readme": "[![Build Status](https://travis-ci.org/then/promise.png)](https://travis-ci.org/then/promise)\r\n\r\n# promise\r\n\r\n This a bare bones [Promises/A+](http://promises-aplus.github.com/promises-spec/) implementation.\r\n\r\n It is designed to get the basics spot on correct, so that you can build extended promise implementations on top of it.\r\n\r\n## Installation\r\n\r\n Server:\r\n\r\n $ npm install promise\r\n\r\n Client:\r\n\r\n $ component install then/promise\r\n\r\n## API\r\n\r\n In the example below shows how you can load the promise library (in a way that works on both client and server). It then demonstrates creating a promise from scratch. You simply call `new Promise(fn)`. There is a complete specification for what is returned by this method in [Promises/A+](http://promises-aplus.github.com/promises-spec/).\r\n\r\n```javascript\r\nvar Promise = require('promise');\r\n\r\nvar promise = new Promise(function (resolve, reject) {\r\n get('http://www.google.com', function (err, res) {\r\n if (err) reject(err);\r\n else resolve(res);\r\n });\r\n });\r\n```\r\n\r\n## Extending Promises\r\n\r\n There are three options for extending the promises created by this library.\r\n\r\n### Inheritance\r\n\r\n You can use inheritance if you want to create your own complete promise library with this as your basic starting point, perfect if you have lots of cool features you want to add. Here is an example of a promise library called `Awesome`, which is built on top of `Promise` correctly.\r\n\r\n```javascript\r\nvar Promise = require('promise');\r\nfunction Awesome(fn) {\r\n if (!(this instanceof Awesome)) return new Awesome(fn);\r\n Promise.call(this, fn);\r\n}\r\nAwesome.prototype = Object.create(Promise.prototype);\r\nAwesome.prototype.constructor = Awesome;\r\n\r\n//Awesome extension\r\nAwesome.prototype.spread = function (cb) {\r\n return this.then(function (arr) {\r\n return cb.apply(this, arr);\r\n })\r\n};\r\n```\r\n\r\n N.B. if you fail to set the prototype and constructor properly or fail to do Promise.call, things can fail in really subtle ways.\r\n\r\n### Wrap\r\n\r\n This is the nuclear option, for when you want to start from scratch. It ensures you won't be impacted by anyone who is extending the prototype (see below).\r\n\r\n```javascript\r\nfunction Uber(fn) {\r\n if (!(this instanceof Uber)) return new Uber(fn);\r\n var _prom = new Promise(fn);\r\n this.then = _prom.then;\r\n}\r\n\r\nUber.prototype.spread = function (cb) {\r\n return this.then(function (arr) {\r\n return cb.apply(this, arr);\r\n })\r\n};\r\n```\r\n\r\n### Extending the Prototype\r\n\r\n In general, you should never extend the prototype of this promise implimenation because your extensions could easily conflict with someone elses extensions. However, this organisation will host a library of extensions which do not conflict with each other, so you can safely enable any of those. If you think of an extension that we don't provide and you want to write it, submit an issue on this repository and (if I agree) I'll set you up with a repository and give you permission to commit to it.\r\n\r\n## License\r\n\r\n MIT\r\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/then/promise/issues" + }, + "homepage": "https://github.com/then/promise", + "_id": "promise@2.0.0", + "_from": "promise@~2.0" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/.npmignore new file mode 100644 index 000000000..94fceeb20 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/.npmignore @@ -0,0 +1,2 @@ +tmp/ +node_modules/ diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/README.md b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/README.md new file mode 100644 index 000000000..de6abe5dd --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/README.md @@ -0,0 +1,544 @@ +UglifyJS 2 +========== + +UglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit. + +This page documents the command line utility. For +[API and internals documentation see my website](http://lisperator.net/uglifyjs/). +There's also an +[in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox, +Chrome and probably Safari). + +Install +------- + +First make sure you have installed the latest version of [node.js](http://nodejs.org/) +(You may need to restart your computer after this step). + +From NPM for use as a command line app: + + npm install uglify-js -g + +From NPM for programmatic use: + + npm install uglify-js + +From Git: + + git clone git://github.com/mishoo/UglifyJS2.git + cd UglifyJS2 + npm link . + +Usage +----- + + uglifyjs [input files] [options] + +UglifyJS2 can take multiple input files. It's recommended that you pass the +input files first, then pass the options. UglifyJS will parse input files +in sequence and apply any compression options. The files are parsed in the +same global scope, that is, a reference from a file to some +variable/function declared in another file will be matched properly. + +If you want to read from STDIN instead, pass a single dash instead of input +files. + +The available options are: + + --source-map Specify an output file where to generate source map. + [string] + --source-map-root The path to the original source to be included in the + source map. [string] + --source-map-url The path to the source map to be added in //@ + sourceMappingURL. Defaults to the value passed with + --source-map. [string] + --in-source-map Input source map, useful if you're compressing JS that was + generated from some other original code. + -p, --prefix Skip prefix for original filenames that appear in source + maps. For example -p 3 will drop 3 directories from file + names and ensure they are relative paths. + -o, --output Output file (default STDOUT). + -b, --beautify Beautify output/specify output options. [string] + -m, --mangle Mangle names/pass mangler options. [string] + -r, --reserved Reserved names to exclude from mangling. + -c, --compress Enable compressor/pass compressor options. Pass options + like -c hoist_vars=false,if_return=false. Use -c with no + argument to use the default compression options. [string] + -d, --define Global definitions [string] + --comments Preserve copyright comments in the output. By default this + works like Google Closure, keeping JSDoc-style comments + that contain "@license" or "@preserve". You can optionally + pass one of the following arguments to this flag: + - "all" to keep all comments + - a valid JS regexp (needs to start with a slash) to keep + only comments that match. + Note that currently not *all* comments can be kept when + compression is on, because of dead code removal or + cascading statements into sequences. [string] + --stats Display operations run time on STDERR. [boolean] + --acorn Use Acorn for parsing. [boolean] + --spidermonkey Assume input fles are SpiderMonkey AST format (as JSON). + [boolean] + --self Build itself (UglifyJS2) as a library (implies + --wrap=UglifyJS --export-all) [boolean] + --wrap Embed everything in a big function, making the “exports” + and “global” variables available. You need to pass an + argument to this option to specify the name that your + module will take when included in, say, a browser. + [string] + --export-all Only used when --wrap, this tells UglifyJS to add code to + automatically export all globals. [boolean] + --lint Display some scope warnings [boolean] + -v, --verbose Verbose [boolean] + -V, --version Print version number and exit. [boolean] + +Specify `--output` (`-o`) to declare the output file. Otherwise the output +goes to STDOUT. + +## Source map options + +UglifyJS2 can generate a source map file, which is highly useful for +debugging your compressed JavaScript. To get a source map, pass +`--source-map output.js.map` (full path to the file where you want the +source map dumped). + +Additionally you might need `--source-map-root` to pass the URL where the +original files can be found. In case you are passing full paths to input +files to UglifyJS, you can use `--prefix` (`-p`) to specify the number of +directories to drop from the path prefix when declaring files in the source +map. + +For example: + + uglifyjs /home/doe/work/foo/src/js/file1.js \ + /home/doe/work/foo/src/js/file2.js \ + -o foo.min.js \ + --source-map foo.min.js.map \ + --source-map-root http://foo.com/src \ + -p 5 -c -m + +The above will compress and mangle `file1.js` and `file2.js`, will drop the +output in `foo.min.js` and the source map in `foo.min.js.map`. The source +mapping will refer to `http://foo.com/src/js/file1.js` and +`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` +as the source map root, and the original files as `js/file1.js` and +`js/file2.js`). + +### Composed source map + +When you're compressing JS code that was output by a compiler such as +CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd +like to map back to the original code (i.e. CoffeeScript). UglifyJS has an +option to take an input source map. Assuming you have a mapping from +CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript → +compressed JS by mapping every token in the compiled JS to its original +location. + +To use this feature you need to pass `--in-source-map +/path/to/input/source.map`. Normally the input source map should also point +to the file containing the generated JS, so if that's correct you can omit +input files from the command line. + +## Mangler options + +To enable the mangler you need to pass `--mangle` (`-m`). Optionally you +can pass `-m sort=true` (we'll possibly have other flags in the future) in order +to assign shorter names to most frequently used variables. This saves a few +hundred bytes on jQuery before gzip, but the output is _bigger_ after gzip +(and seems to happen for other libraries I tried it on) therefore it's not +enabled by default. + +When mangling is enabled but you want to prevent certain names from being +mangled, you can declare those names with `--reserved` (`-r`) — pass a +comma-separated list of names. For example: + + uglifyjs ... -m -r '$,require,exports' + +to prevent the `require`, `exports` and `$` names from being changed. + +## Compressor options + +You need to pass `--compress` (`-c`) to enable the compressor. Optionally +you can pass a comma-separated list of options. Options are in the form +`foo=bar`, or just `foo` (the latter implies a boolean option that you want +to set `true`; it's effectively a shortcut for `foo=true`). + +The defaults should be tuned for maximum compression on most code. Here are +the available options (all are `true` by default, except `hoist_vars`): + +- `sequences` -- join consecutive simple statements using the comma operator +- `properties` -- rewrite property access using the dot notation, for + example `foo["bar"] → foo.bar` +- `dead_code` -- remove unreachable code +- `drop_debugger` -- remove `debugger;` statements +- `unsafe` -- apply "unsafe" transformations (discussion below) +- `conditionals` -- apply optimizations for `if`-s and conditional + expressions +- `comparisons` -- apply certain optimizations to binary nodes, for example: + `!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes, + e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. +- `evaluate` -- attempt to evaluate constant expressions +- `booleans` -- various optimizations for boolean context, for example `!!a + ? b : c → a ? b : c` +- `loops` -- optimizations for `do`, `while` and `for` loops when we can + statically determine the condition +- `unused` -- drop unreferenced functions and variables +- `hoist_funs` -- hoist function declarations +- `hoist_vars` -- hoist `var` declarations (this is `false` by default + because it seems to increase the size of the output in general) +- `if_return` -- optimizations for if/return and if/continue +- `join_vars` -- join consecutive `var` statements +- `cascade` -- small optimization for sequences, transform `x, x` into `x` + and `x = something(), x` into `x = something()` +- `warnings` -- display warnings when dropping unreachable code or unused + declarations etc. + +### Conditional compilation + +You can use the `--define` (`-d`) switch in order to declare global +variables that UglifyJS will assume to be constants (unless defined in +scope). For example if you pass `--define DEBUG=false` then, coupled with +dead code removal UglifyJS will discard the following from the output: + + if (DEBUG) { + console.log("debug stuff"); + } + +UglifyJS will warn about the condition being always false and about dropping +unreachable code; for now there is no option to turn off only this specific +warning, you can pass `warnings=false` to turn off *all* warnings. + +Another way of doing that is to declare your globals as constants in a +separate file and include it into the build. For example you can have a +`build/defines.js` file with the following: + + const DEBUG = false; + const PRODUCTION = true; + // etc. + +and build your code like this: + + uglifyjs build/defines.js js/foo.js js/bar.js... -c + +UglifyJS will notice the constants and, since they cannot be altered, it +will evaluate references to them to the value itself and drop unreachable +code as usual. The possible downside of this approach is that the build +will contain the `const` declarations. + + +## Beautifier options + +The code generator tries to output shortest code possible by default. In +case you want beautified output, pass `--beautify` (`-b`). Optionally you +can pass additional arguments that control the code output: + +- `beautify` (default `true`) -- whether to actually beautify the output. + Passing `-b` will set this to true, but you might need to pass `-b` even + when you want to generate minified code, in order to specify additional + arguments, so you can use `-b beautify=false` to override it. +- `indent-level` (default 4) +- `indent-start` (default 0) -- prefix all lines by that many spaces +- `quote-keys` (default `false`) -- pass `true` to quote all keys in literal + objects +- `space-colon` (default `true`) -- insert a space after the colon signs +- `ascii-only` (default `false`) -- escape Unicode characters in strings and + regexps +- `inline-script` (default `false`) -- escape the slash in occurrences of + ` 0) { + sys.error("WARN: Ignoring input files since --self was passed"); + } + files = UglifyJS.FILES; + if (!ARGS.wrap) ARGS.wrap = "UglifyJS"; + ARGS.export_all = true; +} + +var ORIG_MAP = ARGS.in_source_map; + +if (ORIG_MAP) { + ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP)); + if (files.length == 0) { + sys.error("INFO: Using file from the input source map: " + ORIG_MAP.file); + files = [ ORIG_MAP.file ]; + } + if (ARGS.source_map_root == null) { + ARGS.source_map_root = ORIG_MAP.sourceRoot; + } +} + +if (files.length == 0) { + files = [ "-" ]; +} + +if (files.indexOf("-") >= 0 && ARGS.source_map) { + sys.error("ERROR: Source map doesn't work with input from STDIN"); + process.exit(1); +} + +if (files.filter(function(el){ return el == "-" }).length > 1) { + sys.error("ERROR: Can read a single file from STDIN (two or more dashes specified)"); + process.exit(1); +} + +var STATS = {}; +var OUTPUT_FILE = ARGS.o; +var TOPLEVEL = null; + +var SOURCE_MAP = ARGS.source_map ? UglifyJS.SourceMap({ + file: OUTPUT_FILE, + root: ARGS.source_map_root, + orig: ORIG_MAP, +}) : null; + +OUTPUT_OPTIONS.source_map = SOURCE_MAP; + +try { + var output = UglifyJS.OutputStream(OUTPUT_OPTIONS); + var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS); +} catch(ex) { + if (ex instanceof UglifyJS.DefaultsError) { + sys.error(ex.msg); + sys.error("Supported options:"); + sys.error(sys.inspect(ex.defs)); + process.exit(1); + } +} + +files.forEach(function(file) { + var code = read_whole_file(file); + if (ARGS.p != null) { + file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/"); + } + time_it("parse", function(){ + if (ARGS.spidermonkey) { + var program = JSON.parse(code); + if (!TOPLEVEL) TOPLEVEL = program; + else TOPLEVEL.body = TOPLEVEL.body.concat(program.body); + } + else if (ARGS.acorn) { + TOPLEVEL = acorn.parse(code, { + locations : true, + trackComments : true, + sourceFile : file, + program : TOPLEVEL + }); + } + else { + TOPLEVEL = UglifyJS.parse(code, { + filename: file, + toplevel: TOPLEVEL + }); + }; + }); +}); + +if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){ + TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL); +}); + +if (ARGS.wrap) { + TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all); +} + +var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint; + +if (SCOPE_IS_NEEDED) { + time_it("scope", function(){ + TOPLEVEL.figure_out_scope(); + if (ARGS.lint) { + TOPLEVEL.scope_warnings(); + } + }); +} + +if (COMPRESS) { + time_it("squeeze", function(){ + TOPLEVEL = TOPLEVEL.transform(compressor); + }); +} + +if (SCOPE_IS_NEEDED) { + time_it("scope", function(){ + TOPLEVEL.figure_out_scope(); + if (MANGLE) { + TOPLEVEL.compute_char_frequency(MANGLE); + } + }); +} + +if (MANGLE) time_it("mangle", function(){ + TOPLEVEL.mangle_names(MANGLE); +}); +time_it("generate", function(){ + TOPLEVEL.print(output); +}); + +output = output.get(); + +if (SOURCE_MAP) { + fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8"); + output += "\n/*\n//@ sourceMappingURL=" + (ARGS.source_map_url || ARGS.source_map) + "\n*/"; +} + +if (OUTPUT_FILE) { + fs.writeFileSync(OUTPUT_FILE, output, "utf8"); +} else { + sys.print(output); + sys.error("\n"); +} + +if (ARGS.stats) { + sys.error(UglifyJS.string_template("Timing information (compressed {count} files):", { + count: files.length + })); + for (var i in STATS) if (STATS.hasOwnProperty(i)) { + sys.error(UglifyJS.string_template("- {name}: {time}s", { + name: i, + time: (STATS[i] / 1000).toFixed(3) + })); + } +} + +/* -----[ functions ]----- */ + +function normalize(o) { + for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) { + o[i.replace(/-/g, "_")] = o[i]; + delete o[i]; + } +} + +function getOptions(x, constants) { + x = ARGS[x]; + if (!x) return null; + var ret = {}; + if (x !== true) { + var ast; + try { + ast = UglifyJS.parse(x); + } catch(ex) { + if (ex instanceof UglifyJS.JS_Parse_Error) { + sys.error("Error parsing arguments in: " + x); + process.exit(1); + } + } + ast.walk(new UglifyJS.TreeWalker(function(node){ + if (node instanceof UglifyJS.AST_Toplevel) return; // descend + if (node instanceof UglifyJS.AST_SimpleStatement) return; // descend + if (node instanceof UglifyJS.AST_Seq) return; // descend + if (node instanceof UglifyJS.AST_Assign) { + var name = node.left.print_to_string({ beautify: false }).replace(/-/g, "_"); + var value = node.right; + if (constants) + value = new Function("return (" + value.print_to_string() + ")")(); + ret[name] = value; + return true; // no descend + } + sys.error(node.TYPE) + sys.error("Error parsing arguments in: " + x); + process.exit(1); + })); + } + return ret; +} + +function read_whole_file(filename) { + if (filename == "-") { + // XXX: this sucks. How does one read the whole STDIN + // synchronously? + filename = "/dev/stdin"; + } + try { + return fs.readFileSync(filename, "utf8"); + } catch(ex) { + sys.error("ERROR: can't read file: " + filename); + process.exit(1); + } +} + +function time_it(name, cont) { + var t1 = new Date().getTime(); + var ret = cont(); + if (ARGS.stats) { + var spent = new Date().getTime() - t1; + if (STATS[name]) STATS[name] += spent; + else STATS[name] = spent; + } + return ret; +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/ast.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/ast.js new file mode 100644 index 000000000..62bdd8dbc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/ast.js @@ -0,0 +1,964 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +function DEFNODE(type, props, methods, base) { + if (arguments.length < 4) base = AST_Node; + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + var proto = base && new base; + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (methods.hasOwnProperty(i)) { + if (/^\$/.test(i)) { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + return ctor; +}; + +var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", { +}, null); + +var AST_Node = DEFNODE("Node", "start end", { + clone: function() { + return new this.CTOR(this); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + } +}, null); + +AST_Node.warn_function = null; +AST_Node.warn = function(txt, props) { + if (AST_Node.warn_function) + AST_Node.warn_function(string_template(txt, props)); +}; + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value scope", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + scope: "[AST_Scope/S] The scope that this directive affects" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +function walk_body(node, visitor) { + if (node.body instanceof AST_Statement) { + node.body._walk(visitor); + } + else node.body.forEach(function(stat){ + stat._walk(visitor); + }); +}; + +var AST_Block = DEFNODE("Block", "body", { + $documentation: "A body of statements (usually bracketed)", + $propdoc: { + body: "[AST_Statement*] an array of statements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + }); + } +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)", + _walk: function(visitor) { + return visitor._visit(this); + } +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.label._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +var AST_ForIn = DEFNODE("ForIn", "init name object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + directives: "[string*/S] an array of directives declared in this scope", + variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + functions: "[Object/S] like `variables`, but only lists function declarations", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_commonjs: function(name, export_all) { + var self = this; + var to_export = []; + if (export_all) { + self.figure_out_scope(); + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_SymbolDeclaration && node.definition().global) { + if (!find_if(function(n){ return n.name == node.name }, to_export)) + to_export.push(node); + } + })); + } + var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_SimpleStatement) { + node = node.body; + if (node instanceof AST_String) switch (node.getValue()) { + case "$ORIG": + return MAP.splice(self.body); + case "$EXPORTS": + var body = []; + to_export.forEach(function(sym){ + body.push(new AST_SimpleStatement({ + body: new AST_Assign({ + left: new AST_Sub({ + expression: new AST_SymbolRef({ name: "exports" }), + property: new AST_String({ value: sym.name }), + }), + operator: "=", + right: new AST_SymbolRef(sym), + }), + })); + }); + return MAP.splice(body); + } + } + })); + return wrapped_tl; + } +}, AST_Scope); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg*] array of function arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.name) this.name._walk(visitor); + this.argnames.forEach(function(arg){ + arg._walk(visitor); + }); + walk_body(this, visitor); + }); + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function" +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function(){ + this.value._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function(){ + this.label._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + } +}, AST_Block); + +// XXX: this is wrong according to ECMA-262 (12.4). the catch block +// should introduce another scope, as the argname should be visible +// only inside the catch block. However, doing it this way because of +// IE which simply introduces the name in the surrounding scope. If +// we ever want to fix this then AST_Catch should inherit from +// AST_Scope. +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.argname._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.definitions.forEach(function(def){ + def._walk(visitor); + }); + }); + } +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + } +}); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.args.forEach(function(arg){ + arg._walk(visitor); + }); + }); + } +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Seq = DEFNODE("Seq", "car cdr", { + $documentation: "A sequence expression (two comma-separated expressions)", + $propdoc: { + car: "[AST_Node] first element in sequence", + cdr: "[AST_Node] second element in sequence" + }, + $cons: function(x, y) { + var seq = new AST_Seq(x); + seq.car = x; + seq.cdr = y; + return seq; + }, + $from_array: function(array) { + if (array.length == 0) return null; + if (array.length == 1) return array[0].clone(); + var list = null; + for (var i = array.length; --i >= 0;) { + list = AST_Seq.cons(array[i], list); + } + var p = list; + while (p) { + if (p.cdr && !p.cdr.cdr) { + p.cdr = p.cdr.car; + break; + } + p = p.cdr; + } + return list; + }, + to_array: function() { + var p = this, a = []; + while (p) { + a.push(p.car); + if (p.cdr && !(p.cdr instanceof AST_Seq)) { + a.push(p.cdr); + break; + } + p = p.cdr; + } + return a; + }, + add: function(node) { + var p = this; + while (p) { + if (!(p.cdr instanceof AST_Seq)) { + var cell = AST_Seq.cons(p.cdr, node); + return p.cdr = cell; + } + p = p.cdr; + } + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.car._walk(visitor); + if (this.cdr) this.cdr._walk(visitor); + }); + } +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" + } +}); + +var AST_Dot = DEFNODE("Dot", null, { + $documentation: "A dotted property access expression", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.property._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "left operator right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.left._walk(visitor); + this.right._walk(visitor); + }); + } +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + } +}); + +var AST_Assign = DEFNODE("Assign", null, { + $documentation: "An assignment expression — `a = b + 5`", +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.elements.forEach(function(el){ + el._walk(visitor); + }); + }); + } +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.properties.forEach(function(prop){ + prop._walk(visitor); + }); + }); + } +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string] the property name; it's always a plain string in our AST, no matter if it was a string, number or identifier in original code", + value: "[AST_Node] property value. For setters and getters this is an AST_Function." + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.value._walk(visitor); + }); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, { + $documentation: "A key: value object property", +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { + $documentation: "An object setter property", +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { + $documentation: "An object getter property", +}, AST_ObjectProperty); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols", +}); + +var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { + $documentation: "The name of a property accessor (setter/getter function)" +}, AST_Symbol); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", + $propdoc: { + init: "[AST_Node*/S] array of initializers for this declaration." + } +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolDeclaration); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LabelRef*] a list of nodes referring to this label" + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp" + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function(){}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function(){}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ TreeWalker ]----- */ + +function TreeWalker(callback) { + this.visit = callback; + this.stack = []; +}; +TreeWalker.prototype = { + _visit: function(node, descend) { + this.stack.push(node); + var ret = this.visit(node, descend ? function(){ + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.stack.pop(); + return ret; + }, + parent: function(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + }, + push: function (node) { + this.stack.push(node); + }, + pop: function() { + return this.stack.pop(); + }, + self: function() { + return this.stack[this.stack.length - 1]; + }, + find_parent: function(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + }, + in_boolean_context: function() { + var stack = this.stack; + var i = stack.length, self = stack[--i]; + while (i > 0) { + var p = stack[--i]; + if ((p instanceof AST_If && p.condition === self) || + (p instanceof AST_Conditional && p.condition === self) || + (p instanceof AST_DWLoop && p.condition === self) || + (p instanceof AST_For && p.condition === self) || + (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) + { + return true; + } + if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) + return false; + self = p; + } + }, + loopcontrol_target: function(label) { + var stack = this.stack; + if (label) { + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == label.name) { + return x.body; + } + } + } else { + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_Switch + || x instanceof AST_For + || x instanceof AST_ForIn + || x instanceof AST_DWLoop) return x; + } + } + } +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/compress.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/compress.js new file mode 100644 index 000000000..ca23c40ee --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/compress.js @@ -0,0 +1,1968 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +function Compressor(options, false_by_default) { + if (!(this instanceof Compressor)) + return new Compressor(options, false_by_default); + TreeTransformer.call(this, this.before, this.after); + this.options = defaults(options, { + sequences : !false_by_default, + properties : !false_by_default, + dead_code : !false_by_default, + drop_debugger : !false_by_default, + unsafe : !false_by_default, + unsafe_comps : false, + conditionals : !false_by_default, + comparisons : !false_by_default, + evaluate : !false_by_default, + booleans : !false_by_default, + loops : !false_by_default, + unused : !false_by_default, + hoist_funs : !false_by_default, + hoist_vars : false, + if_return : !false_by_default, + join_vars : !false_by_default, + cascade : !false_by_default, + side_effects : !false_by_default, + + warnings : true, + global_defs : {} + }, true); +}; + +Compressor.prototype = new TreeTransformer; +merge(Compressor.prototype, { + option: function(key) { return this.options[key] }, + warn: function() { + if (this.options.warnings) + AST_Node.warn.apply(AST_Node, arguments); + }, + before: function(node, descend, in_list) { + if (node._squeezed) return node; + if (node instanceof AST_Scope) { + node.drop_unused(this); + node = node.hoist_declarations(this); + } + descend(node, this); + node = node.optimize(this); + if (node instanceof AST_Scope) { + // dead code removal might leave further unused declarations. + // this'll usually save very few bytes, but the performance + // hit seems negligible so I'll just drop it here. + + // no point to repeat warnings. + var save_warnings = this.options.warnings; + this.options.warnings = false; + node.drop_unused(this); + this.options.warnings = save_warnings; + } + node._squeezed = true; + return node; + } +}); + +(function(){ + + function OPT(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor){ + var self = this; + if (self._optimized) return self; + var opt = optimizer(self, compressor); + opt._optimized = true; + if (opt === self) return opt; + return opt.transform(compressor); + }); + }; + + OPT(AST_Node, function(self, compressor){ + return self; + }); + + AST_Node.DEFMETHOD("equivalent_to", function(node){ + // XXX: this is a rather expensive way to test two node's equivalence: + return this.print_to_string() == node.print_to_string(); + }); + + function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); + }; + + function make_node_from_constant(compressor, val, orig) { + // XXX: WIP. + // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){ + // if (node instanceof AST_SymbolRef) { + // var scope = compressor.find_parent(AST_Scope); + // var def = scope.find_variable(node); + // node.thedef = def; + // return node; + // } + // })).transform(compressor); + + if (val instanceof AST_Node) return val.transform(compressor); + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }).optimize(compressor); + case "number": + return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, { + value: val + }).optimize(compressor); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig).optimize(compressor); + default: + if (val === null) { + return make_node(AST_Null, orig).optimize(compressor); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig).optimize(compressor); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } + }; + + function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); + }; + + function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; + }; + + function loop_body(x) { + if (x instanceof AST_Switch) return x; + if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { + return (x.body instanceof AST_BlockStatement ? x.body : x); + } + return x; + }; + + function tighten_body(statements, compressor) { + var CHANGED; + do { + CHANGED = false; + statements = eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + statements = eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + statements = handle_if_return(statements, compressor); + } + if (compressor.option("sequences")) { + statements = sequencesize(statements, compressor); + } + if (compressor.option("join_vars")) { + statements = join_consecutive_vars(statements, compressor); + } + } while (CHANGED); + return statements; + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_BlockStatement) { + CHANGED = true; + a.push.apply(a, eliminate_spurious_blocks(stat.body)); + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + a.push(stat); + seen_dirs.push(stat.value); + } else { + CHANGED = true; + } + } else { + a.push(stat); + } + return a; + }, []); + }; + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var in_lambda = self instanceof AST_Lambda; + var ret = []; + loop: for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + switch (true) { + case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): + CHANGED = true; + // note, ret.length is probably always zero + // because we drop unreachable code before this + // step. nevertheless, it's good to check. + continue loop; + case stat instanceof AST_If: + if (stat.body instanceof AST_Return) { + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (((in_lambda && ret.length == 0) + || (ret[0] instanceof AST_Return && !ret[0].value)) + && !stat.body.value && !stat.alternative) { + CHANGED = true; + var cond = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + ret.unshift(cond); + continue loop; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0]; + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0] || make_node(AST_Return, stat, { + value: make_node(AST_Undefined, stat) + }); + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } + if (!stat.body.value && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(ret) + }); + stat.alternative = null; + ret = [ stat.transform(compressor) ]; + continue loop; + } + //--- + if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement + && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) { + CHANGED = true; + ret.push(make_node(AST_Return, ret[0], { + value: make_node(AST_Undefined, ret[0]) + }).transform(compressor)); + ret = as_statement_array(stat.alternative).concat(ret); + ret.unshift(stat); + continue loop; + } + } + + var ab = aborts(stat.body); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab.label); + } + CHANGED = true; + var body = as_statement_array(stat.body).slice(0, -1); + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: ret + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: body + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + var ab = aborts(stat.alternative); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab.label); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(ret) + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: as_statement_array(stat.alternative).slice(0, -1) + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + ret.unshift(stat); + break; + default: + ret.unshift(stat); + break; + } + } + return ret; + }; + + function eliminate_dead_code(statements, compressor) { + var has_quit = false; + var orig = statements.length; + var self = compressor.self(); + statements = statements.reduce(function(a, stat){ + if (has_quit) { + extract_declarations_from_unreachable_code(compressor, stat, a); + } else { + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat.label); + if ((stat instanceof AST_Break + && lct instanceof AST_BlockStatement + && loop_body(lct) === self) || (stat instanceof AST_Continue + && loop_body(lct) === self)) { + if (stat.label) { + remove(stat.label.thedef.references, stat.label); + } + } else { + a.push(stat); + } + } else { + a.push(stat); + } + if (aborts(stat)) has_quit = true; + } + return a; + }, []); + CHANGED = statements.length != orig; + return statements; + }; + + function sequencesize(statements, compressor) { + if (statements.length < 2) return statements; + var seq = [], ret = []; + function push_seq() { + seq = AST_Seq.from_array(seq); + if (seq) ret.push(make_node(AST_SimpleStatement, seq, { + body: seq + })); + seq = []; + }; + statements.forEach(function(stat){ + if (stat instanceof AST_SimpleStatement) seq.push(stat.body); + else push_seq(), ret.push(stat); + }); + push_seq(); + ret = sequencesize_2(ret, compressor); + CHANGED = ret.length != statements.length; + return ret; + }; + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + ret.pop(); + var left = prev.body; + if (left instanceof AST_Seq) { + left.add(right); + } else { + left = AST_Seq.cons(left, right); + } + return left.transform(compressor); + }; + var ret = [], prev = null; + statements.forEach(function(stat){ + if (prev) { + if (stat instanceof AST_For) { + var opera = {}; + try { + prev.body.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw opera; + })); + if (stat.init && !(stat.init instanceof AST_Definitions)) { + stat.init = cons_seq(stat.init); + } + else if (!stat.init) { + stat.init = prev.body; + ret.pop(); + } + } catch(ex) { + if (ex !== opera) throw ex; + } + } + else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } + else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + else if (stat instanceof AST_Exit && stat.value) { + stat.value = cons_seq(stat.value); + } + else if (stat instanceof AST_Exit) { + stat.value = cons_seq(make_node(AST_Undefined, stat)); + } + else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } + } + ret.push(stat); + prev = stat instanceof AST_SimpleStatement ? stat : null; + }); + return ret; + }; + + function join_consecutive_vars(statements, compressor) { + var prev = null; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } + else if (stat instanceof AST_For + && prev instanceof AST_Definitions + && (!stat.init || stat.init.TYPE == prev.TYPE)) { + CHANGED = true; + a.pop(); + if (stat.init) { + stat.init.definitions = prev.definitions.concat(stat.init.definitions); + } else { + stat.init = prev; + } + a.push(stat); + prev = stat; + } + else { + prev = stat; + a.push(stat); + } + return a; + }, []); + }; + + }; + + function extract_declarations_from_unreachable_code(compressor, stat, target) { + compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); + stat.walk(new TreeWalker(function(node){ + if (node instanceof AST_Definitions) { + compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); + node.remove_initializers(); + target.push(node); + return true; + } + if (node instanceof AST_Defun) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + })); + }; + + /* -----[ boolean/negation helpers ]----- */ + + // methods to determine whether an expression has a boolean result type + (function (def){ + var unary_bool = [ "!", "delete" ]; + var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; + def(AST_Node, function(){ return false }); + def(AST_UnaryPrefix, function(){ + return member(this.operator, unary_bool); + }); + def(AST_Binary, function(){ + return member(this.operator, binary_bool) || + ( (this.operator == "&&" || this.operator == "||") && + this.left.is_boolean() && this.right.is_boolean() ); + }); + def(AST_Conditional, function(){ + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def(AST_Assign, function(){ + return this.operator == "=" && this.right.is_boolean(); + }); + def(AST_Seq, function(){ + return this.cdr.is_boolean(); + }); + def(AST_True, function(){ return true }); + def(AST_False, function(){ return true }); + })(function(node, func){ + node.DEFMETHOD("is_boolean", func); + }); + + // methods to determine if an expression has a string result type + (function (def){ + def(AST_Node, function(){ return false }); + def(AST_String, function(){ return true }); + def(AST_UnaryPrefix, function(){ + return this.operator == "typeof"; + }); + def(AST_Binary, function(compressor){ + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def(AST_Assign, function(compressor){ + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def(AST_Seq, function(compressor){ + return this.cdr.is_string(compressor); + }); + def(AST_Conditional, function(compressor){ + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); + def(AST_Call, function(compressor){ + return compressor.option("unsafe") + && this.expression instanceof AST_SymbolRef + && this.expression.name == "String" + && this.expression.undeclared(); + }); + })(function(node, func){ + node.DEFMETHOD("is_string", func); + }); + + function best_of(ast1, ast2) { + return ast1.print_to_string().length > + ast2.print_to_string().length + ? ast2 : ast1; + }; + + // methods to evaluate a constant expression + (function (def){ + // The evaluate method returns an array with one or two + // elements. If the node has been successfully reduced to a + // constant, then the second element tells us the value; + // otherwise the second element is missing. The first element + // of the array is always an AST_Node descendant; when + // evaluation was successful it's a node that represents the + // constant; otherwise it's the original node. + AST_Node.DEFMETHOD("evaluate", function(compressor){ + if (!compressor.option("evaluate")) return [ this ]; + try { + var val = this._eval(), ast = make_node_from_constant(compressor, val, this); + return [ best_of(ast, this), val ]; + } catch(ex) { + if (ex !== def) throw ex; + return [ this ]; + } + }); + def(AST_Statement, function(){ + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); + }); + def(AST_Function, function(){ + // XXX: AST_Function inherits from AST_Scope, which itself + // inherits from AST_Statement; however, an AST_Function + // isn't really a statement. This could byte in other + // places too. :-( Wish JS had multiple inheritance. + return [ this ]; + }); + function ev(node) { + return node._eval(); + }; + def(AST_Node, function(){ + throw def; // not constant + }); + def(AST_Constant, function(){ + return this.getValue(); + }); + def(AST_UnaryPrefix, function(){ + var e = this.expression; + switch (this.operator) { + case "!": return !ev(e); + case "typeof": return typeof ev(e); + case "void": return void ev(e); + case "~": return ~ev(e); + case "-": + e = ev(e); + if (e === 0) throw def; + return -e; + case "+": return +ev(e); + } + throw def; + }); + def(AST_Binary, function(){ + var left = this.left, right = this.right; + switch (this.operator) { + case "&&" : return ev(left) && ev(right); + case "||" : return ev(left) || ev(right); + case "|" : return ev(left) | ev(right); + case "&" : return ev(left) & ev(right); + case "^" : return ev(left) ^ ev(right); + case "+" : return ev(left) + ev(right); + case "*" : return ev(left) * ev(right); + case "/" : return ev(left) / ev(right); + case "%" : return ev(left) % ev(right); + case "-" : return ev(left) - ev(right); + case "<<" : return ev(left) << ev(right); + case ">>" : return ev(left) >> ev(right); + case ">>>" : return ev(left) >>> ev(right); + case "==" : return ev(left) == ev(right); + case "===" : return ev(left) === ev(right); + case "!=" : return ev(left) != ev(right); + case "!==" : return ev(left) !== ev(right); + case "<" : return ev(left) < ev(right); + case "<=" : return ev(left) <= ev(right); + case ">" : return ev(left) > ev(right); + case ">=" : return ev(left) >= ev(right); + case "in" : return ev(left) in ev(right); + case "instanceof" : return ev(left) instanceof ev(right); + } + throw def; + }); + def(AST_Conditional, function(){ + return ev(this.condition) + ? ev(this.consequent) + : ev(this.alternative); + }); + def(AST_SymbolRef, function(){ + var d = this.definition(); + if (d && d.constant && d.init) return ev(d.init); + throw def; + }); + })(function(node, func){ + node.DEFMETHOD("_eval", func); + }); + + // method to negate an expression + (function(def){ + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + }; + def(AST_Node, function(){ + return basic_negation(this); + }); + def(AST_Statement, function(){ + throw new Error("Cannot negate a statement"); + }); + def(AST_Function, function(){ + return basic_negation(this); + }); + def(AST_UnaryPrefix, function(){ + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def(AST_Seq, function(compressor){ + var self = this.clone(); + self.cdr = self.cdr.negate(compressor); + return self; + }); + def(AST_Conditional, function(compressor){ + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best_of(basic_negation(this), self); + }); + def(AST_Binary, function(compressor){ + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor); + self.right = self.right.negate(compressor); + return best_of(basic_negation(this), self); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor); + self.right = self.right.negate(compressor); + return best_of(basic_negation(this), self); + } + return basic_negation(this); + }); + })(function(node, func){ + node.DEFMETHOD("negate", function(compressor){ + return func.call(this, compressor); + }); + }); + + // determine if expression has side effects + (function(def){ + def(AST_Node, function(){ return true }); + + def(AST_EmptyStatement, function(){ return false }); + def(AST_Constant, function(){ return false }); + def(AST_This, function(){ return false }); + + def(AST_Block, function(){ + for (var i = this.body.length; --i >= 0;) { + if (this.body[i].has_side_effects()) + return true; + } + return false; + }); + + def(AST_SimpleStatement, function(){ + return this.body.has_side_effects(); + }); + def(AST_Defun, function(){ return true }); + def(AST_Function, function(){ return false }); + def(AST_Binary, function(){ + return this.left.has_side_effects() + || this.right.has_side_effects(); + }); + def(AST_Assign, function(){ return true }); + def(AST_Conditional, function(){ + return this.condition.has_side_effects() + || this.consequent.has_side_effects() + || this.alternative.has_side_effects(); + }); + def(AST_Unary, function(){ + return this.operator == "delete" + || this.operator == "++" + || this.operator == "--" + || this.expression.has_side_effects(); + }); + def(AST_SymbolRef, function(){ return false }); + def(AST_Object, function(){ + for (var i = this.properties.length; --i >= 0;) + if (this.properties[i].has_side_effects()) + return true; + return false; + }); + def(AST_ObjectProperty, function(){ + return this.value.has_side_effects(); + }); + def(AST_Array, function(){ + for (var i = this.elements.length; --i >= 0;) + if (this.elements[i].has_side_effects()) + return true; + return false; + }); + // def(AST_Dot, function(){ + // return this.expression.has_side_effects(); + // }); + // def(AST_Sub, function(){ + // return this.expression.has_side_effects() + // || this.property.has_side_effects(); + // }); + def(AST_PropAccess, function(){ + return true; + }); + def(AST_Seq, function(){ + return this.car.has_side_effects() + || this.cdr.has_side_effects(); + }); + })(function(node, func){ + node.DEFMETHOD("has_side_effects", func); + }); + + // tell me if a statement aborts + function aborts(thing) { + return thing && thing.aborts(); + }; + (function(def){ + def(AST_Statement, function(){ return null }); + def(AST_Jump, function(){ return this }); + function block_aborts(){ + var n = this.body.length; + return n > 0 && aborts(this.body[n - 1]); + }; + def(AST_BlockStatement, block_aborts); + def(AST_SwitchBranch, block_aborts); + def(AST_If, function(){ + return this.alternative && aborts(this.body) && aborts(this.alternative); + }); + })(function(node, func){ + node.DEFMETHOD("aborts", func); + }); + + /* -----[ optimizers ]----- */ + + OPT(AST_Directive, function(self, compressor){ + if (self.scope.has_directive(self.value) !== self.scope) { + return make_node(AST_EmptyStatement, self); + } + return self; + }); + + OPT(AST_Debugger, function(self, compressor){ + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_LabeledStatement, function(self, compressor){ + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body.label) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; + }); + + OPT(AST_Block, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + return self; + }); + + OPT(AST_BlockStatement, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: return self.body[0]; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; + }); + + AST_Scope.DEFMETHOD("drop_unused", function(compressor){ + var self = this; + if (compressor.option("unused") + && !(self instanceof AST_Toplevel) + && !self.uses_eval + ) { + var in_use = []; + var initializations = new Dictionary(); + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend){ + if (node !== self) { + if (node instanceof AST_Defun) { + initializations.add(node.name.name, node); + return true; // don't go in nested scopes + } + if (node instanceof AST_Definitions && scope === self) { + node.definitions.forEach(function(def){ + if (def.value) { + initializations.add(def.name.name, def.value); + if (def.value.has_side_effects()) { + def.value.walk(tw); + } + } + }); + return true; + } + if (node instanceof AST_SymbolRef) { + push_uniq(in_use, node.definition()); + return true; + } + if (node instanceof AST_Scope) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + for (var i = 0; i < in_use.length; ++i) { + in_use[i].orig.forEach(function(decl){ + // undeclared globals will be instanceof AST_SymbolRef + var init = initializations.get(decl.name); + if (init) init.forEach(function(init){ + var tw = new TreeWalker(function(node){ + if (node instanceof AST_SymbolRef) { + push_uniq(in_use, node.definition()); + } + }); + init.walk(tw); + }); + }); + } + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + if (node instanceof AST_Lambda) { + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (sym.unreferenced()) { + a.pop(); + compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", { + name : sym.name, + file : sym.start.file, + line : sym.start.line, + col : sym.start.col + }); + } + else break; + } + } + if (node instanceof AST_Defun && node !== self) { + if (!member(node.name.definition(), in_use)) { + compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", { + name : node.name.name, + file : node.name.start.file, + line : node.name.start.line, + col : node.name.start.col + }); + return make_node(AST_EmptyStatement, node); + } + return node; + } + if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) { + var def = node.definitions.filter(function(def){ + if (member(def.name.definition(), in_use)) return true; + var w = { + name : def.name.name, + file : def.name.start.file, + line : def.name.start.line, + col : def.name.start.col + }; + if (def.value && def.value.has_side_effects()) { + def._unused_side_effects = true; + compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); + return true; + } + compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w); + return false; + }); + // place uninitialized names at the start + def = mergeSort(def, function(a, b){ + if (!a.value && b.value) return -1; + if (!b.value && a.value) return 1; + return 0; + }); + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + for (var i = 0; i < def.length;) { + var x = def[i]; + if (x._unused_side_effects) { + side_effects.push(x.value); + def.splice(i, 1); + } else { + if (side_effects.length > 0) { + side_effects.push(x.value); + x.value = AST_Seq.from_array(side_effects); + side_effects = []; + } + ++i; + } + } + if (side_effects.length > 0) { + side_effects = make_node(AST_BlockStatement, node, { + body: [ make_node(AST_SimpleStatement, node, { + body: AST_Seq.from_array(side_effects) + }) ] + }); + } else { + side_effects = null; + } + if (def.length == 0 && !side_effects) { + return make_node(AST_EmptyStatement, node); + } + if (def.length == 0) { + return side_effects; + } + node.definitions = def; + if (side_effects) { + side_effects.body.unshift(node); + node = side_effects; + } + return node; + } + if (node instanceof AST_For && node.init instanceof AST_BlockStatement) { + descend(node, this); + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + var body = node.init.body.slice(0, -1); + node.init = node.init.body.slice(-1)[0].body; + body.push(node); + return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { + body: body + }); + } + if (node instanceof AST_Scope && node !== self) + return node; + } + ); + self.transform(tt); + } + }); + + AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + var self = this; + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Dictionary(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + })); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Defun && hoist_funs) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Var && hoist_vars) { + node.definitions.forEach(function(def){ + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) return node.definitions[0].name; + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + vars.each(function(def, name){ + if (self instanceof AST_Lambda + && find_if(function(x){ return x.name == def.name.name }, + self.argnames)) { + vars.del(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Seq + && (assign = expr.car) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = expr.cdr; + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + var tmp = [ i, 1 ].concat(self.body[i].body); + self.body.splice.apply(self.body, tmp); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + }; + } + self.body = dirs.concat(hoisted, self.body); + } + return self; + }); + + OPT(AST_SimpleStatement, function(self, compressor){ + if (compressor.option("side_effects")) { + if (!self.body.has_side_effects()) { + compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); + return make_node(AST_EmptyStatement, self); + } + } + return self; + }); + + OPT(AST_DWLoop, function(self, compressor){ + var cond = self.condition.evaluate(compressor); + self.condition = cond[0]; + if (!compressor.option("loops")) return self; + if (cond.length > 1) { + if (cond[1]) { + return make_node(AST_For, self, { + body: self.body + }); + } else if (self instanceof AST_While) { + if (compressor.option("dead_code")) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }); + } + } else { + return self.body; + } + } + return self; + }); + + function if_break_in_loop(self, compressor) { + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + if_break_in_loop(self, compressor); + } + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (first instanceof AST_If) { + if (first.body instanceof AST_Break + && compressor.loopcontrol_target(first.body.label) === self) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } + else if (first.alternative instanceof AST_Break + && compressor.loopcontrol_target(first.alternative.label) === self) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + }; + + OPT(AST_While, function(self, compressor) { + if (!compressor.option("loops")) return self; + self = AST_DWLoop.prototype.optimize.call(self, compressor); + if (self instanceof AST_While) { + if_break_in_loop(self, compressor); + self = make_node(AST_For, self, self).transform(compressor); + } + return self; + }); + + OPT(AST_For, function(self, compressor){ + var cond = self.condition; + if (cond) { + cond = cond.evaluate(compressor); + self.condition = cond[0]; + } + if (!compressor.option("loops")) return self; + if (cond) { + if (cond.length > 1 && !cond[1]) { + if (compressor.option("dead_code")) { + var a = []; + if (self.init instanceof AST_Statement) { + a.push(self.init); + } + else if (self.init) { + a.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }); + } + } + } + if_break_in_loop(self, compressor); + return self; + }); + + OPT(AST_If, function(self, compressor){ + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, warn and drop + // one of the blocks. note, statically determined implies + // “has no side effects”; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + self.condition = cond[0]; + if (cond.length > 1) { + if (cond[1]) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + if (self.alternative) { + extract_declarations_from_unreachable_code(compressor, self.alternative, a); + } + a.push(self.body); + return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); + } + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + if (self.alternative) a.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); + } + } + } + if (is_empty(self.alternative)) self.alternative = null; + var negated = self.condition.negate(compressor); + var negated_is_best = best_of(self.condition, negated) === negated; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }).transform(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).transform(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).transform(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).transform(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).transform(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor) + }) + }).transform(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self.condition = make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }).transform(compressor); + self.body = self.body.body; + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).transform(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).transform(compressor); + } + return self; + }); + + OPT(AST_Switch, function(self, compressor){ + if (self.body.length == 0 && compressor.option("conditionals")) { + return make_node(AST_SimpleStatement, self, { + body: self.expression + }).transform(compressor); + } + var last_branch = self.body[self.body.length - 1]; + if (last_branch) { + var stat = last_branch.body[last_branch.body.length - 1]; // last statement + if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self) + last_branch.body.pop(); + } + var exp = self.expression.evaluate(compressor); + out: if (exp.length == 2) try { + // constant expression + self.expression = exp[0]; + if (!compressor.option("dead_code")) break out; + var value = exp[1]; + var in_if = false; + var in_block = false; + var started = false; + var stopped = false; + var ruined = false; + var tt = new TreeTransformer(function(node, descend, in_list){ + if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) { + // no need to descend these node types + return node; + } + else if (node instanceof AST_Switch && node === self) { + node = node.clone(); + descend(node, this); + return ruined ? node : make_node(AST_BlockStatement, node, { + body: node.body.reduce(function(a, branch){ + return a.concat(branch.body); + }, []) + }).transform(compressor); + } + else if (node instanceof AST_If || node instanceof AST_Try) { + var save = in_if; + in_if = !in_block; + descend(node, this); + in_if = save; + return node; + } + else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) { + var save = in_block; + in_block = true; + descend(node, this); + in_block = save; + return node; + } + else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) { + if (in_if) { + ruined = true; + return node; + } + if (in_block) return node; + stopped = true; + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + else if (node instanceof AST_SwitchBranch && this.parent() === self) { + if (stopped) return MAP.skip; + if (node instanceof AST_Case) { + var exp = node.expression.evaluate(compressor); + if (exp.length < 2) { + // got a case with non-constant expression, baling out + throw self; + } + if (exp[1] === value || started) { + started = true; + if (aborts(node)) stopped = true; + descend(node, this); + return node; + } + return MAP.skip; + } + descend(node, this); + return node; + } + }); + tt.stack = compressor.stack.slice(); // so that's able to see parent nodes + self = self.transform(tt); + } catch(ex) { + if (ex !== self) throw ex; + } + return self; + }); + + OPT(AST_Case, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + return self; + }); + + OPT(AST_Try, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + return self; + }); + + AST_Definitions.DEFMETHOD("remove_initializers", function(){ + this.definitions.forEach(function(def){ def.value = null }); + }); + + AST_Definitions.DEFMETHOD("to_assignments", function(){ + var assignments = this.definitions.reduce(function(a, def){ + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + a.push(make_node(AST_Assign, def, { + operator : "=", + left : name, + right : def.value + })); + } + return a; + }, []); + if (assignments.length == 0) return null; + return AST_Seq.from_array(assignments); + }); + + OPT(AST_Definitions, function(self, compressor){ + if (self.definitions.length == 0) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_Function, function(self, compressor){ + self = AST_Lambda.prototype.optimize.call(self, compressor); + if (compressor.option("unused")) { + if (self.name && self.name.unreferenced()) { + self.name = null; + } + } + return self; + }); + + OPT(AST_Call, function(self, compressor){ + if (compressor.option("unsafe")) { + var exp = self.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }); + } + } + else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).transform(compressor); + } + } + if (compressor.option("side_effects")) { + if (self.expression instanceof AST_Function + && self.args.length == 0 + && !AST_Block.prototype.has_side_effects.call(self.expression)) { + return make_node(AST_Undefined, self).transform(compressor); + } + } + return self; + }); + + OPT(AST_New, function(self, compressor){ + if (compressor.option("unsafe")) { + var exp = self.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Object": + case "RegExp": + case "Function": + case "Error": + case "Array": + return make_node(AST_Call, self, self).transform(compressor); + } + } + } + return self; + }); + + OPT(AST_Seq, function(self, compressor){ + if (!compressor.option("side_effects")) + return self; + if (!self.car.has_side_effects()) { + // we shouldn't compress (1,eval)(something) to + // eval(something) because that changes the meaning of + // eval (becomes lexical instead of global). + var p; + if (!(self.cdr instanceof AST_SymbolRef + && self.cdr.name == "eval" + && self.cdr.undeclared() + && (p = compressor.parent()) instanceof AST_Call + && p.expression === self)) { + return self.cdr; + } + } + if (compressor.option("cascade")) { + if (self.car instanceof AST_Assign + && !self.car.left.has_side_effects() + && self.car.left.equivalent_to(self.cdr)) { + return self.car; + } + if (!self.car.has_side_effects() + && !self.cdr.has_side_effects() + && self.car.equivalent_to(self.cdr)) { + return self.car; + } + } + return self; + }); + + AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Seq) { + var seq = this.expression; + var x = seq.to_array(); + this.expression = x.pop(); + x.push(this); + seq = AST_Seq.from_array(x).transform(compressor); + return seq; + } + } + return this; + }); + + OPT(AST_UnaryPostfix, function(self, compressor){ + return self.lift_sequences(compressor); + }); + + OPT(AST_UnaryPrefix, function(self, compressor){ + self = self.lift_sequences(compressor); + var e = self.expression; + if (compressor.option("booleans") && compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); + return make_node(AST_True, self); + } + if (e instanceof AST_Binary && self.operator == "!") { + self = best_of(self, e.negate(compressor)); + } + } + return self.evaluate(compressor)[0]; + }); + + AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.left instanceof AST_Seq) { + var seq = this.left; + var x = seq.to_array(); + this.left = x.pop(); + x.push(this); + seq = AST_Seq.from_array(x).transform(compressor); + return seq; + } + if (this.right instanceof AST_Seq + && !(this.operator == "||" || this.operator == "&&") + && !this.left.has_side_effects()) { + var seq = this.right; + var x = seq.to_array(); + this.right = x.pop(); + x.push(this); + seq = AST_Seq.from_array(x).transform(compressor); + return seq; + } + } + return this; + }); + + var commutativeOperators = makePredicate("== === != !== * & | ^"); + + OPT(AST_Binary, function(self, compressor){ + function reverse(op) { + if (!(self.left.has_side_effects() && self.right.has_side_effects())) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + }; + if (commutativeOperators(self.operator)) { + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + reverse(); + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_boolean() && self.right.is_boolean())) { + self.operator = self.operator.substr(0, 2); + } + // XXX: intentionally falling down to the next case + case "==": + case "!=": + if (self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof" + && compressor.option("unsafe")) { + if (!(self.right.expression instanceof AST_SymbolRef) + || !self.right.expression.undeclared()) { + self.left = self.right.expression; + self.right = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } + break; + } + if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) { + case "&&": + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) { + compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); + return make_node(AST_False, self); + } + if (ll.length > 1 && ll[1]) { + return rr[0]; + } + if (rr.length > 1 && rr[1]) { + return ll[0]; + } + break; + case "||": + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) { + compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); + return make_node(AST_True, self); + } + if (ll.length > 1 && !ll[1]) { + return rr[0]; + } + if (rr.length > 1 && !rr[1]) { + return ll[0]; + } + break; + case "+": + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) || + (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) { + compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); + return make_node(AST_True, self); + } + break; + } + var exp = self.evaluate(compressor); + if (exp.length > 1) { + if (best_of(exp[0], self) !== self) + return exp[0]; + } + if (compressor.option("comparisons")) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor) + }); + self = best_of(self, negated); + } + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + if (self.operator == "+" && self.right instanceof AST_String + && self.right.getValue() === "" && self.left instanceof AST_Binary + && self.left.operator == "+" && self.left.is_string(compressor)) { + return self.left; + } + return self; + }); + + OPT(AST_SymbolRef, function(self, compressor){ + if (self.undeclared()) { + var defines = compressor.option("global_defs"); + if (defines && defines.hasOwnProperty(self.name)) { + return make_node_from_constant(compressor, defines[self.name], self); + } + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self); + case "NaN": + return make_node(AST_NaN, self); + case "Infinity": + return make_node(AST_Infinity, self); + } + } + return self; + }); + + OPT(AST_Undefined, function(self, compressor){ + if (compressor.option("unsafe")) { + var scope = compressor.find_parent(AST_Scope); + var undef = scope.find_variable("undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : scope, + thedef : undef + }); + ref.reference(); + return ref; + } + } + return self; + }); + + var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; + OPT(AST_Assign, function(self, compressor){ + self = self.lift_sequences(compressor); + if (self.operator == "=" + && self.left instanceof AST_SymbolRef + && self.right instanceof AST_Binary + && self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && member(self.right.operator, ASSIGN_OPS)) { + self.operator = self.right.operator + "="; + self.right = self.right.right; + } + return self; + }); + + OPT(AST_Conditional, function(self, compressor){ + if (!compressor.option("conditionals")) return self; + if (self.condition instanceof AST_Seq) { + var car = self.condition.car; + self.condition = self.condition.cdr; + return AST_Seq.cons(car, self); + } + var cond = self.condition.evaluate(compressor); + if (cond.length > 1) { + if (cond[1]) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.start); + return self.consequent; + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.start); + return self.alternative; + } + } + var negated = cond[0].negate(compressor); + if (best_of(cond[0], negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var consequent = self.consequent; + var alternative = self.alternative; + if (consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator == alternative.operator + && consequent.left.equivalent_to(alternative.left) + ) { + /* + * Stuff like this: + * if (foo) exp = something; else exp = something_else; + * ==> + * exp = foo ? something : something_else; + */ + self = make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + return self; + }); + + OPT(AST_Boolean, function(self, compressor){ + if (compressor.option("booleans")) { + var p = compressor.parent(); + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { + operator : p.operator, + value : self.value, + file : p.start.file, + line : p.start.line, + col : p.start.col, + }); + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; + }); + + OPT(AST_Sub, function(self, compressor){ + var prop = self.property; + if (prop instanceof AST_String && compressor.option("properties")) { + prop = prop.getValue(); + if (is_identifier(prop)) { + return make_node(AST_Dot, self, { + expression : self.expression, + property : prop + }); + } + } + return self; + }); + + function literals_in_boolean_context(self, compressor) { + if (compressor.option("booleans") && compressor.in_boolean_context()) { + return make_node(AST_True, self); + } + return self; + }; + OPT(AST_Array, literals_in_boolean_context); + OPT(AST_Object, literals_in_boolean_context); + OPT(AST_RegExp, literals_in_boolean_context); + +})(); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/mozilla-ast.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/mozilla-ast.js new file mode 100644 index 000000000..982d621a8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/mozilla-ast.js @@ -0,0 +1,265 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +(function(){ + + var MOZ_TO_ME = { + TryStatement : function(M) { + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(M.handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + CatchClause : function(M) { + return new AST_Catch({ + start : my_start_token(M), + end : my_end_token(M), + argname : from_moz(M.param), + body : from_moz(M.body).body + }); + }, + ObjectExpression : function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop){ + var key = prop.key; + var name = key.type == "Identifier" ? key.name : key.value; + var args = { + start : my_start_token(key), + end : my_end_token(prop.value), + key : name, + value : from_moz(prop.value) + }; + switch (prop.kind) { + case "init": + return new AST_ObjectKeyVal(args); + case "set": + args.value.name = from_moz(key); + return new AST_ObjectSetter(args); + case "get": + args.value.name = from_moz(key); + return new AST_ObjectGetter(args); + } + }) + }); + }, + SequenceExpression : function(M) { + return AST_Seq.from_array(M.expressions.map(from_moz)); + }, + MemberExpression : function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object) + }); + }, + SwitchCase : function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + Literal : function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + default: + args.value = val; + return new AST_RegExp(args); + } + }, + UnaryExpression: From_Moz_Unary, + UpdateExpression: From_Moz_Unary, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new (M.name == "this" ? AST_This + : p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + } + }; + + function From_Moz_Unary(M) { + return new (M.prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }) + }; + + var ME_TO_MOZ = {}; + + map("Node", AST_Node); + map("Program", AST_Toplevel, "body@body"); + map("Function", AST_Function, "id>name, params@argnames, body%body"); + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("ExpressionStatement", AST_SimpleStatement, "expression>body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("DebuggerStatement", AST_Debugger); + map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body"); + map("VariableDeclaration", AST_Var, "declarations@definitions"); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + + map("ThisExpression", AST_This); + map("ArrayExpression", AST_Array, "elements@elements"); + map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body"); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, arguments@args"); + + /* -----[ tools ]----- */ + + function my_start_token(moznode) { + return new AST_Token({ + file : moznode.loc && moznode.loc.source, + line : moznode.loc && moznode.loc.start.line, + col : moznode.loc && moznode.loc.start.column, + pos : moznode.start, + endpos : moznode.start + }); + }; + + function my_end_token(moznode) { + return new AST_Token({ + file : moznode.loc && moznode.loc.source, + line : moznode.loc && moznode.loc.end.line, + col : moznode.loc && moznode.loc.end.column, + pos : moznode.end, + endpos : moznode.end + }); + }; + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new mytype({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ + var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = "M." + m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + if (how == "@") { + moz_to_me += moz + ".map(from_moz)"; + } else if (how == ">") { + moz_to_me += "from_moz(" + moz + ")"; + } else if (how == "=") { + moz_to_me += moz; + } else if (how == "%") { + moz_to_me += "from_moz(" + moz + ").body"; + } else throw new Error("Can't understand operator in propmap: " + prop); + }); + moz_to_me += "\n})}"; + + // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); + // console.log(moz_to_me); + + moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + mytype, my_start_token, my_end_token, from_moz + ); + return MOZ_TO_ME[moztype] = moz_to_me; + }; + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + }; + + AST_Node.from_mozilla_ast = function(node){ + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + +})(); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/output.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/output.js new file mode 100644 index 000000000..42b3aad92 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/output.js @@ -0,0 +1,1220 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +function OutputStream(options) { + + options = defaults(options, { + indent_start : 0, + indent_level : 4, + quote_keys : false, + space_colon : true, + ascii_only : false, + inline_script : false, + width : 80, + max_line_len : 32000, + ie_proof : true, + beautify : false, + source_map : null, + bracketize : false, + semicolons : true, + comments : false, + preserve_line : false + }, true); + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = ""; + + 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; + }); + }; + + function make_string(str) { + 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 (options.ascii_only) str = to_ascii(str); + if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; + else return '"' + str.replace(/\x22/g, '\\"') + '"'; + }; + + function encode_string(str) { + var ret = make_string(str); + 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 make_indent(back) { + return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); + }; + + /* -----[ beautification/minification ]----- */ + + var might_need_space = false; + var might_need_semicolon = false; + var last = null; + + function last_char() { + return last.charAt(last.length - 1); + }; + + function maybe_newline() { + if (options.max_line_len && current_col > options.max_line_len) + print("\n"); + }; + + var requireSemicolonChars = makePredicate("( [ + * / - , ."); + + function print(str) { + str = String(str); + var ch = str.charAt(0); + if (might_need_semicolon) { + if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) { + if (options.semicolons || requireSemicolonChars(ch)) { + OUTPUT += ";"; + current_col++; + current_pos++; + } else { + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + } + if (!options.beautify) + might_need_space = false; + } + might_need_semicolon = false; + maybe_newline(); + } + + if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { + var target_line = stack[stack.length - 1].start.line; + while (current_line < target_line) { + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + might_need_space = false; + } + } + + if (might_need_space) { + var prev = last_char(); + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (/^[\+\-\/]$/.test(ch) && ch == prev)) + { + OUTPUT += " "; + current_col++; + current_pos++; + } + might_need_space = false; + } + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + if (n == 0) { + current_col += a[n].length; + } else { + current_col = a[n].length; + } + current_pos += str.length; + last = str; + OUTPUT += str; + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont() }; + + var newline = options.beautify ? function() { + print("\n"); + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + }; + + function next_indent() { + return indentation + options.indent_level; + }; + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function(){ + ret = cont(); + }); + indent(); + print("}"); + return ret; + }; + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + }; + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + }; + + function comma() { + print(","); + space(); + }; + + function colon() { + print(":"); + if (options.space_colon) space(); + }; + + var add_mapping = options.source_map ? function(token, name) { + try { + if (token) options.source_map.add( + token.file || "?", + current_line, current_col, + token.line, token.col, + (!name && token.type == "name") ? token.value : name + ); + } catch(ex) { + AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { + file: token.file, + line: token.line, + col: token.col, + cline: current_line, + ccol: current_col, + name: name || "" + }) + } + } : noop; + + function get() { + return OUTPUT; + }; + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + indentation : function() { return indentation }, + current_width : function() { return current_col - indentation }, + should_break : function() { return options.width && this.current_width() >= options.width }, + newline : newline, + print : print, + space : space, + comma : comma, + colon : colon, + last : function() { return last }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_ascii : to_ascii, + print_name : function(name) { print(make_name(name)) }, + print_string : function(str) { print(encode_string(str)) }, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt] }, + line : function() { return current_line }, + col : function() { return current_col }, + pos : function() { return current_pos }, + push_node : function(node) { stack.push(node) }, + pop_node : function() { return stack.pop() }, + stack : function() { return stack }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +}; + +/* -----[ code generators ]----- */ + +(function(){ + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + }; + + AST_Node.DEFMETHOD("print", function(stream, force_parens){ + var self = this, generator = self._codegen; + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(function(){ + self.add_comments(stream); + self.add_source_map(stream); + generator(self, stream); + }); + } else { + self.add_comments(stream); + self.add_source_map(stream); + generator(self, stream); + } + stream.pop_node(); + }); + + AST_Node.DEFMETHOD("print_to_string", function(options){ + var s = OutputStream(options); + this.print(s); + return s.get(); + }); + + /* -----[ comments ]----- */ + + AST_Node.DEFMETHOD("add_comments", function(output){ + var c = output.option("comments"), self = this; + if (c) { + var start = self.start; + if (start && !start._comments_dumped) { + start._comments_dumped = true; + var comments = start.comments_before; + + // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 + // if this node is `return` or `throw`, we cannot allow comments before + // the returned or thrown value. + if (self instanceof AST_Exit && + self.value && self.value.start.comments_before.length > 0) { + comments = (comments || []).concat(self.value.start.comments_before); + self.value.start.comments_before = []; + } + + if (c.test) { + comments = comments.filter(function(comment){ + return c.test(comment.value); + }); + } else if (typeof c == "function") { + comments = comments.filter(function(comment){ + return c(self, comment); + }); + } + comments.forEach(function(c){ + if (c.type == "comment1") { + output.print("//" + c.value + "\n"); + output.indent(); + } + else if (c.type == "comment2") { + output.print("/*" + c.value + "*/"); + if (start.nlb) { + output.print("\n"); + output.indent(); + } else { + output.space(); + } + } + }); + } + } + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + nodetype.DEFMETHOD("needs_parens", func); + }; + + PARENS(AST_Node, function(){ + return false; + }); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output){ + return first_in_statement(output); + }); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + PARENS(AST_Object, function(output){ + return first_in_statement(output); + }); + + PARENS(AST_Unary, function(output){ + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this; + }); + + PARENS(AST_Seq, function(output){ + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_Dot // (1, {foo:2}).foo ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + ; + }); + + PARENS(AST_Binary, function(output){ + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && this === p.right + && !(so == po && + (so == "*" || + so == "&&" || + so == "||")))) { + return true; + } + } + }); + + PARENS(AST_PropAccess, function(output){ + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + try { + this.walk(new TreeWalker(function(node){ + if (node instanceof AST_Call) throw p; + })); + } catch(ex) { + if (ex !== p) throw ex; + return true; + } + } + }); + + PARENS(AST_Call, function(output){ + var p = output.parent(); + return p instanceof AST_New && p.expression === this; + }); + + PARENS(AST_New, function(output){ + var p = output.parent(); + if (no_constructor_parens(this, output) + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output){ + var p = output.parent(); + if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_NaN, function(output){ + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + function assign_and_conditional_paren_rules(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }; + + PARENS(AST_Assign, assign_and_conditional_paren_rules); + PARENS(AST_Conditional, assign_and_conditional_paren_rules); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output){ + output.print_string(self.value); + output.semicolon(); + }); + DEFPRINT(AST_Debugger, function(self, output){ + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output) { + var last = body.length - 1; + body.forEach(function(stmt, i){ + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + }); + }; + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output){ + display_body(self.body, true, output); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output){ + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + function print_bracketed(body, output) { + if (body.length > 0) output.with_block(function(){ + display_body(body, false, output); + }); + else output.print("{}"); + }; + DEFPRINT(AST_BlockStatement, function(self, output){ + print_bracketed(self.body, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output){ + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output){ + output.print("do"); + output.space(); + self._do_print_body(output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output){ + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + self.init.print(output); + output.space(); + output.print("in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output){ + output.print("with"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ + var self = this; + if (!nokeyword) { + output.print("function"); + } + if (self.name) { + output.space(); + self.name.print(output); + } + output.with_parens(function(){ + self.argnames.forEach(function(arg, i){ + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Lambda, function(self, output){ + self._do_print(output); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.value) { + output.space(); + this.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output){ + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output){ + self._do_print(output, "throw"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output){ + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output){ + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + if (output.option("bracketize")) { + make_block(self.body, output); + return; + } + // 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. + if (!self.body) + return output.force_semicolon(); + if (self.body instanceof AST_Do + && output.option("ie_proof")) { + // 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 + make_block(self.body, output); + return; + } + var b = self.body; + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } + else if (b instanceof AST_StatementWithBody) { + b = b.body; + } + else break; + } + force_statement(self.body, output); + }; + DEFPRINT(AST_If, function(self, output){ + output.print("if"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output){ + output.print("switch"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + if (self.body.length > 0) output.with_block(function(){ + self.body.forEach(function(stmt, i){ + if (i) output.newline(); + output.indent(true); + stmt.print(output); + }); + }); + else output.print("{}"); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ + if (this.body.length > 0) { + output.newline(); + this.body.forEach(function(stmt){ + output.indent(); + stmt.print(output); + output.newline(); + }); + } + }); + DEFPRINT(AST_Default, function(self, output){ + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output){ + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output){ + output.print("try"); + output.space(); + print_bracketed(self.body, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output){ + output.print("catch"); + output.space(); + output.with_parens(function(){ + self.argname.print(output); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Finally, function(self, output){ + output.print("finally"); + output.space(); + print_bracketed(self.body, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i){ + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var avoid_semicolon = in_for && p.init === this; + if (!avoid_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Var, function(self, output){ + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output){ + self._do_print(output, "const"); + }); + + function parenthesize_for_noin(node, output, noin) { + if (!noin) node.print(output); + else try { + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw output; + })); + node.print(output); + } catch(ex) { + if (ex !== output) throw ex; + node.print(output, true); + } + }; + + DEFPRINT(AST_VarDef, function(self, output){ + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output){ + self.expression.print(output); + if (self instanceof AST_New && no_constructor_parens(self, output)) + return; + output.with_parens(function(){ + self.args.forEach(function(expr, i){ + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output){ + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Seq.DEFMETHOD("_do_print", function(output){ + this.car.print(output); + if (this.cdr) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + this.cdr.print(output); + } + }); + DEFPRINT(AST_Seq, function(self, output){ + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output){ + var expr = self.expression; + expr.print(output); + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.]/i.test(output.last())) { + output.print("."); + } + } + output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(self.property); + }); + DEFPRINT(AST_Sub, function(self, output){ + self.expression.print(output); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output){ + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op)) + output.space(); + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output){ + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output){ + self.left.print(output); + output.space(); + output.print(self.operator); + output.space(); + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(self, output){ + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(self, output){ + output.with_square(function(){ + var a = self.elements, len = a.length; + if (len > 0) output.space(); + a.forEach(function(exp, i){ + if (i) output.comma(); + exp.print(output); + }); + if (len > 0) output.space(); + }); + }); + DEFPRINT(AST_Object, function(self, output){ + if (self.properties.length > 0) output.with_block(function(){ + self.properties.forEach(function(prop, i){ + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else output.print("{}"); + }); + DEFPRINT(AST_ObjectKeyVal, function(self, output){ + var key = self.key; + if (output.option("quote_keys")) { + output.print_string(key); + } else if ((typeof key == "number" + || !output.option("beautify") + && +key + "" == key) + && parseFloat(key) >= 0) { + output.print(make_num(key)); + } else if (!is_identifier(key)) { + output.print_string(key); + } else { + output.print_name(key); + } + output.colon(); + self.value.print(output); + }); + DEFPRINT(AST_ObjectSetter, function(self, output){ + output.print("set"); + self.value._do_print(output, true); + }); + DEFPRINT(AST_ObjectGetter, function(self, output){ + output.print("get"); + self.value._do_print(output, true); + }); + DEFPRINT(AST_Symbol, function(self, output){ + var def = self.definition(); + output.print_name(def ? def.mangled_name || def.name : self.name); + }); + DEFPRINT(AST_Undefined, function(self, output){ + output.print("void 0"); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_Infinity, function(self, output){ + output.print("1/0"); + }); + DEFPRINT(AST_NaN, function(self, output){ + output.print("0/0"); + }); + DEFPRINT(AST_This, function(self, output){ + output.print("this"); + }); + DEFPRINT(AST_Constant, function(self, output){ + output.print(self.getValue()); + }); + DEFPRINT(AST_String, function(self, output){ + output.print_string(self.getValue()); + }); + DEFPRINT(AST_Number, function(self, output){ + output.print(make_num(self.getValue())); + }); + DEFPRINT(AST_RegExp, function(self, output){ + var str = self.getValue().toString(); + if (output.option("ascii_only")) + str = output.to_ascii(str); + output.print(str); + var p = output.parent(); + if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self) + output.print(" "); + }); + + function force_statement(stat, output) { + if (output.option("bracketize")) { + if (!stat || stat instanceof AST_EmptyStatement) + output.print("{}"); + else if (stat instanceof AST_BlockStatement) + stat.print(output); + else output.with_block(function(){ + output.indent(); + stat.print(output); + output.newline(); + }); + } else { + if (!stat || stat instanceof AST_EmptyStatement) + output.force_semicolon(); + else + stat.print(output); + } + }; + + // return true if the node at the top of the stack (that means the + // innermost node in the current output) is lexically the first in + // a statement. + function first_in_statement(output) { + var a = output.stack(), i = a.length, node = a[--i], p = a[--i]; + while (i > 0) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Seq && p.car === node ) || + (p instanceof AST_Call && p.expression === node ) || + (p instanceof AST_Dot && p.expression === node ) || + (p instanceof AST_Sub && p.expression === node ) || + (p instanceof AST_Conditional && p.condition === node ) || + (p instanceof AST_Binary && p.left === node ) || + (p instanceof AST_UnaryPostfix && p.expression === node )) + { + node = p; + p = a[--i]; + } else { + return false; + } + } + }; + + // self should be AST_New. decide if we want to show parens or not. + function no_constructor_parens(self, output) { + return self.args.length == 0 && !output.option("beautify"); + }; + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + }; + + function make_num(num) { + var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], 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); + }; + + function make_block(stmt, output) { + if (stmt instanceof AST_BlockStatement) { + stmt.print(output); + return; + } + output.with_block(function(){ + output.indent(); + stmt.print(output); + output.newline(); + }); + }; + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.DEFMETHOD("add_source_map", function(stream){ + generator(this, stream); + }); + }; + + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + DEFMAP(AST_Node, noop); + + function basic_sourcemap_gen(self, output) { + output.add_mapping(self.start); + }; + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + + DEFMAP(AST_Directive, basic_sourcemap_gen); + DEFMAP(AST_Debugger, basic_sourcemap_gen); + DEFMAP(AST_Symbol, basic_sourcemap_gen); + DEFMAP(AST_Jump, basic_sourcemap_gen); + DEFMAP(AST_StatementWithBody, basic_sourcemap_gen); + DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it + DEFMAP(AST_Lambda, basic_sourcemap_gen); + DEFMAP(AST_Switch, basic_sourcemap_gen); + DEFMAP(AST_SwitchBranch, basic_sourcemap_gen); + DEFMAP(AST_BlockStatement, basic_sourcemap_gen); + DEFMAP(AST_Toplevel, noop); + DEFMAP(AST_New, basic_sourcemap_gen); + DEFMAP(AST_Try, basic_sourcemap_gen); + DEFMAP(AST_Catch, basic_sourcemap_gen); + DEFMAP(AST_Finally, basic_sourcemap_gen); + DEFMAP(AST_Definitions, basic_sourcemap_gen); + DEFMAP(AST_Constant, basic_sourcemap_gen); + DEFMAP(AST_ObjectProperty, function(self, output){ + output.add_mapping(self.start, self.key); + }); + +})(); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/parse.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/parse.js new file mode 100644 index 000000000..5a75e7536 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/parse.js @@ -0,0 +1,1407 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser 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. + + ***********************************************************************/ + +"use strict"; + +var KEYWORDS = '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 KEYWORDS_ATOM = 'false null true'; +var RESERVED_WORDS = '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 this throws transient volatile' + + " " + KEYWORDS_ATOM + " " + KEYWORDS; +var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); + +var OPERATOR_CHARS = makePredicate(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 = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = makePredicate(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 = makePredicate(characters("[{(,.;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = makePredicate(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(code) { + return (code >= 97 && code <= 122) + || (code >= 65 && code <= 90) + || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); +}; + +function is_digit(code) { + return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9 +}; + +function is_alphanumeric_char(code) { + return is_digit(code) || is_letter(code); +}; + +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(name) { + return /^[a-z_$][a-z0-9_$]*$/i.test(name) && !RESERVED_WORDS(name); +}; + +function is_identifier_start(code) { + return code == 36 || code == 95 || is_letter(code); +}; + +function is_identifier_char(ch) { + var code = ch.charCodeAt(0); + return is_identifier_start(code) + || is_digit(code) + || code == 8204 // \u200c: zero-width non-joiner + || code == 8205 // \u200d: zero-width joiner (in my ECMA-262 PDF, this is also 200c) + || is_unicode_combining_mark(ch) + || is_unicode_connector_punctuation(ch) + ; +}; + +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; + this.col = col; + this.pos = pos; + 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, filename, line, col, pos) { + AST_Node.warn("ERROR: {message} [{file}:{line},{col}]", { + message: message, + file: filename, + line: line, + col: col + }); + 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, filename) { + + var S = { + text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''), + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + 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 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" && !UNARY_POSTFIX[value]) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || + (type == "punc" && 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, + file : filename + }; + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return new AST_Token(ret); + }; + + function skip_whitespace() { + while (WHITESPACE_CHARS(peek())) + next(); + }; + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + }; + + function parse_error(err) { + js_error(err, filename, 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){ + var code = ch.charCodeAt(0); + switch (code) { + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + return is_alphanumeric_char(code); + }); + 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.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 48 : return "\0"; + case 120 : return String.fromCharCode(hex_bytes(2)); // \x + case 117 : return String.fromCharCode(hex_bytes(4)); // \u + case 10 : return ""; // newline + 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; + }; + + var read_string = 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); + }; + + var read_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ + next(); + var i = find("*/", true); + var text = S.text.substring(S.pos, i); + var a = text.split("\n"), n = a.length; + // update stream position + S.pos = i + 2; + S.line += n - 1; + if (n > 1) S.col = a[n - 1].length; + else S.col += a[n - 1].length; + S.col += 2; + S.newline_before = S.newline_before || text.indexOf("\n") >= 0; + 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 (KEYWORDS(name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ + 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", new RegExp(regexp, mods)); + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (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().charCodeAt(0)) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + return KEYWORDS_ATOM(word) ? token("atom", word) + : !KEYWORDS(word) ? token("name", word) + : OPERATORS(word) ? token("operator", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } 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"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(); + case 46: return handle_dot(); + case 47: return handle_slash(); + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS(ch)) return token("punc", next()); + if (OPERATOR_CHARS(ch)) return read_operator(); + if (code == 92 || is_identifier_start(code)) 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 = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +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 parse($TEXT, options) { + + options = defaults(options, { + strict : false, + filename : null, + toplevel : null + }); + + var S = { + input : typeof $TEXT == "string" ? tokenizer($TEXT, options.filename) : $TEXT, + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + 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(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + 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 + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !options.strict && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon() { + if (is("punc", ";")) next(); + else if (!can_insert_semicolon()) unexpected(); + }; + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + }; + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser(); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + }; + + var statement = embed_tokens(function() { + var tmp; + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + switch (S.token.type) { + case "string": + var dir = S.in_directives, stat = simple_statement(); + // XXXv2: decide how to fix directives + if (dir && stat.body instanceof AST_String && !is("punc", ",")) + return new AST_Directive({ value: stat.body.value }); + return stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (tmp = S.token.value, next(), tmp) { + case "break": + return break_cont(AST_Break); + + case "continue": + return break_cont(AST_Continue); + + case "debugger": + semicolon(); + return new AST_Debugger(); + + case "do": + return new AST_Do({ + body : in_loop(statement), + condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp) + }); + + case "while": + return new AST_While({ + condition : parenthesised(), + 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 new AST_Return({ + value: ( is("punc", ";") + ? (next(), null) + : can_insert_semicolon() + ? null + : (tmp = expression(true), semicolon(), tmp) ) + }); + + case "switch": + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + return new AST_Throw({ + value: (tmp = expression(true), semicolon(), tmp) + }); + + case "try": + return try_(); + + case "var": + return tmp = var_(), semicolon(), tmp; + + case "const": + return tmp = const_(), semicolon(), tmp; + + case "with": + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + default: + unexpected(); + } + } + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (find_if(function(l){ return l.name == label.name }, S.labels)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + return new AST_LabeledStatement({ body: stat, label: label }); + }; + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + }; + + function break_cont(type) { + var label = null; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + if (!find_if(function(l){ return l.name == label.name }, S.labels)) + croak("Undefined label " + label.name); + } + else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + return new type({ label: label }); + }; + + 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 instanceof AST_Var && init.definitions.length > 1) + croak("Only one variable declaration allowed in for..in loop"); + next(); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(statement) + }); + }; + + function for_in(init) { + var lhs = init instanceof AST_Var ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + name : lhs, + object : obj, + body : in_loop(statement) + }); + }; + + var function_ = function(in_statement, ctor) { + var is_accessor = ctor === AST_Accessor; + var name = (is("name") ? as_symbol(in_statement + ? AST_SymbolDefun + : is_accessor + ? AST_SymbolAccessor + : AST_SymbolLambda) + : is_accessor && (is("string") || is("num")) ? as_atom_node() + : null); + if (in_statement && !name) + unexpected(); + expect("("); + if (!ctor) ctor = in_statement ? AST_Defun : AST_Function; + return new ctor({ + name: name, + argnames: (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + a.push(as_symbol(AST_SymbolFunarg)); + } + next(); + return a; + })(true, []), + body: (function(loop, labels){ + ++S.in_function; + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + var a = block_(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + return a; + })(S.in_loop, S.labels) + }); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } + else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + }; + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + expect("("); + var name = as_symbol(AST_SymbolCatch); + expect(")"); + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + }; + + function vardefs(no_in, in_const) { + var a = []; + for (;;) { + a.push(new AST_VarDef({ + start : S.token, + name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), + value : is("operator", "=") ? (next(), expression(false, no_in)) : null, + end : prev() + })); + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, false), + end : prev() + }); + }; + + var const_ = function() { + return new AST_Const({ + start : prev(), + definitions : vardefs(false, true), + end : prev() + }); + }; + + var new_ = function() { + var start = S.token; + expect_token("operator", "new"); + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }), true); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + return as_symbol(AST_SymbolRef); + case "num": + ret = new AST_Number({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ start: tok, end: tok, value: tok.value }); + break; + case "regexp": + ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + }; + + var expr_atom = function(allow_calls) { + if (is("operator", "new")) { + return new_(); + } + var start = S.token; + if (is("punc")) { + switch (start.value) { + case "(": + next(); + var ex = expression(true); + ex.start = start; + ex.end = S.token; + expect(")"); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + var func = function_(false); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (ATOMIC_START_TOKEN[S.token.type]) { + return subscripts(as_atom_node(), 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(new AST_Hole({ start: S.token, end: S.token })); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var object_ = embed_tokens(function() { + expect("{"); + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + var start = S.token; + var type = start.type; + var name = as_property_name(); + if (type == "name" && !is("punc", ":")) { + if (name == "get") { + a.push(new AST_ObjectGetter({ + start : start, + key : name, + value : function_(false, AST_Accessor), + end : prev() + })); + continue; + } + if (name == "set") { + a.push(new AST_ObjectSetter({ + start : start, + key : name, + value : function_(false, AST_Accessor), + end : prev() + })); + continue; + } + } + expect(":"); + a.push(new AST_ObjectKeyVal({ + start : start, + key : name, + value : expression(false), + end : prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function as_property_name() { + var tmp = S.token; + next(); + switch (tmp.type) { + case "num": + case "string": + case "name": + case "operator": + case "keyword": + case "atom": + return tmp.value; + default: + unexpected(); + } + }; + + function as_name() { + var tmp = S.token; + next(); + switch (tmp.type) { + case "name": + case "operator": + case "keyword": + case "atom": + return tmp.value; + default: + unexpected(); + } + }; + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var name = S.token.value; + var sym = new (name == "this" ? AST_This : type)({ + name : String(S.token.value), + start : S.token, + end : S.token + }); + next(); + return sym; + }; + + var subscripts = function(expr, allow_calls) { + var start = expr.start; + if (is("punc", ".")) { + next(); + return subscripts(new AST_Dot({ + start : start, + expression : expr, + property : as_name(), + end : prev() + }), allow_calls); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + property : prop, + end : prev() + }), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(new AST_Call({ + start : start, + expression : expr, + args : expr_list(")"), + end : prev() + }), true); + } + return expr; + }; + + var maybe_unary = function(allow_calls) { + var start = S.token; + if (is("operator") && UNARY_PREFIX(start.value)) { + next(); + var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls); + while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { + val = make_unary(AST_UnaryPostfix, S.token.value, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, op, expr) { + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator"); + return new ctor({ operator: op, expression: expr }); + }; + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (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(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : peek() + }); + } + return expr; + }; + + function is_assignable(expr) { + if (!options.strict) return true; + switch (expr[0]+"") { + case "dot": + case "sub": + case "new": + case "call": + return true; + case "name": + return expr[1] != "this"; + } + }; + + var maybe_assign = function(no_in) { + var start = S.token; + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && ASSIGNMENT(val)) { + if (is_assignable(left)) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return new AST_Seq({ + start : start, + car : expr, + cdr : expression(true, no_in), + end : peek() + }); + } + return expr; + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + }; + + return (function(){ + var start = S.token; + var body = []; + while (!is("eof")) + body.push(statement()); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/scope.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/scope.js new file mode 100644 index 000000000..f23f6eb99 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/scope.js @@ -0,0 +1,580 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(scope, index, orig) { + this.name = orig.name; + this.orig = [ orig ]; + this.scope = scope; + this.references = []; + this.global = false; + this.mangled_name = null; + this.undeclared = false; + this.constant = false; + this.index = index; +}; + +SymbolDef.prototype = { + unmangleable: function(options) { + return this.global + || this.undeclared + || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with)); + }, + mangle: function(options) { + if (!this.mangled_name && !this.unmangleable(options)) + this.mangled_name = this.scope.next_mangled(options); + } +}; + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(){ + // This does what ast_add_scope did in UglifyJS v1. + // + // Part of it could be done at parse time, but it would complicate + // the parser (and it's already kinda complex). It's also worth + // having it separated because we might need to call it multiple + // times on the same tree. + + // pass 1: setup scope chaining and handle definitions + var self = this; + var scope = self.parent_scope = null; + var labels = new Dictionary(); + var nesting = 0; + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Scope) { + node.init_scope_vars(nesting); + var save_scope = node.parent_scope = scope; + var save_labels = labels; + ++nesting; + scope = node; + labels = new Dictionary(); + descend(); + labels = save_labels; + scope = save_scope; + --nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Directive) { + node.scope = scope; + push_uniq(scope.directives, node.value); + return true; + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) + throw new Error(string_template("Label {name} defined twice", l)); + labels.set(l.name, l); + descend(); + labels.del(l.name); + return true; // no descend again + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.init_scope_vars(); + } + if (node instanceof AST_SymbolLambda) { + //scope.def_function(node); + // + // https://github.com/mishoo/UglifyJS2/issues/24 — MSIE + // leaks function expression names into the containing + // scope. Don't like this fix but seems we can't do any + // better. IE: please die. Please! + (node.scope = scope.parent_scope).def_function(node); + } + else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + (node.scope = scope.parent_scope).def_function(node); + } + else if (node instanceof AST_SymbolVar + || node instanceof AST_SymbolConst) { + var def = scope.def_variable(node); + def.constant = node instanceof AST_SymbolConst; + def.init = tw.parent().value; + } + else if (node instanceof AST_SymbolCatch) { + // XXX: this is wrong according to ECMA-262 (12.4). the + // `catch` argument name should be visible only inside the + // catch block. For a quick fix AST_Catch should inherit + // from AST_Scope. Keeping it this way because of IE, + // which doesn't obey the standard. (it introduces the + // identifier in the enclosing scope) + scope.def_variable(node); + } + if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + }); + self.walk(tw); + + // pass 2: find back references and eval + var func = null; + var globals = self.globals = new Dictionary(); + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Lambda) { + var prev_func = func; + func = node; + descend(); + func = prev_func; + return true; + } + if (node instanceof AST_LabelRef) { + node.reference(); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + var sym = node.scope.find_variable(name); + if (!sym) { + var g; + if (globals.has(name)) { + g = globals.get(name); + } else { + g = new SymbolDef(self, globals.size(), node); + g.undeclared = true; + globals.set(name, g); + } + node.thedef = g; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) + s.uses_eval = true; + } + if (name == "arguments") { + func.uses_arguments = true; + } + } else { + node.thedef = sym; + } + node.reference(); + return true; + } + }); + self.walk(tw); +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){ + this.directives = []; // contains the directives defined in this scope, i.e. "use strict" + this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = null; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables + this.nesting = nesting; // the nesting level of this scope (0 means toplevel) +}); + +AST_Scope.DEFMETHOD("strict", function(){ + return this.has_directive("use strict"); +}); + +AST_Lambda.DEFMETHOD("init_scope_vars", function(){ + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; +}); + +AST_SymbolRef.DEFMETHOD("reference", function() { + var def = this.definition(); + def.references.push(this); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + this.frame = this.scope.nesting - def.scope.nesting; +}); + +AST_Label.DEFMETHOD("init_scope_vars", function(){ + this.references = []; +}); + +AST_LabelRef.DEFMETHOD("reference", function(){ + this.thedef.references.push(this); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name){ + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("has_directive", function(value){ + return this.parent_scope && this.parent_scope.has_directive(value) + || (this.directives.indexOf(value) >= 0 ? this : null); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol){ + this.functions.set(symbol.name, this.def_variable(symbol)); +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol){ + var def; + if (!this.variables.has(symbol.name)) { + def = new SymbolDef(this, this.variables.size(), symbol); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } else { + def = this.variables.get(symbol.name); + def.orig.push(symbol); + } + return symbol.thedef = def; +}); + +AST_Scope.DEFMETHOD("next_mangled", function(options){ + var ext = this.enclosed, n = ext.length; + out: while (true) { + var m = base54(++this.cname); + if (!is_identifier(m)) continue; // skip over "do" + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (var i = n; --i >= 0;) { + var sym = ext[i]; + var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); + if (m == name) continue out; + } + return m; + } +}); + +AST_Scope.DEFMETHOD("references", function(sym){ + if (sym instanceof AST_Symbol) sym = sym.definition(); + return this.enclosed.indexOf(sym) < 0 ? null : sym; +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options){ + return this.definition().unmangleable(options); +}); + +// property accessors are not mangleable +AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){ + return true; +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("unreferenced", function(){ + return this.definition().references.length == 0 + && !(this.scope.uses_eval || this.scope.uses_with); +}); + +AST_Symbol.DEFMETHOD("undeclared", function(){ + return this.definition().undeclared; +}); + +AST_LabelRef.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Label.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("definition", function(){ + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function(){ + return this.definition().global; +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ + return defaults(options, { + except : [], + eval : false, + sort : false + }); +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options){ + options = this._default_mangler_options(options); + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Scope) { + var p = tw.parent(), a = []; + node.variables.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + a.push(symbol); + } + }); + if (options.sort) a.sort(function(a, b){ + return b.references.length - a.references.length; + }); + to_mangle.push.apply(to_mangle, a); + return; + } + if (node instanceof AST_Label) { + var name; + do name = base54(++lname); while (!is_identifier(name)); + node.mangled_name = name; + return true; + } + }); + this.walk(tw); + to_mangle.forEach(function(def){ def.mangle(options) }); +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ + options = this._default_mangler_options(options); + var tw = new TreeWalker(function(node){ + if (node instanceof AST_Constant) + base54.consider(node.print_to_string()); + else if (node instanceof AST_Return) + base54.consider("return"); + else if (node instanceof AST_Throw) + base54.consider("throw"); + else if (node instanceof AST_Continue) + base54.consider("continue"); + else if (node instanceof AST_Break) + base54.consider("break"); + else if (node instanceof AST_Debugger) + base54.consider("debugger"); + else if (node instanceof AST_Directive) + base54.consider(node.value); + else if (node instanceof AST_While) + base54.consider("while"); + else if (node instanceof AST_Do) + base54.consider("do while"); + else if (node instanceof AST_If) { + base54.consider("if"); + if (node.alternative) base54.consider("else"); + } + else if (node instanceof AST_Var) + base54.consider("var"); + else if (node instanceof AST_Const) + base54.consider("const"); + else if (node instanceof AST_Lambda) + base54.consider("function"); + else if (node instanceof AST_For) + base54.consider("for"); + else if (node instanceof AST_ForIn) + base54.consider("for in"); + else if (node instanceof AST_Switch) + base54.consider("switch"); + else if (node instanceof AST_Case) + base54.consider("case"); + else if (node instanceof AST_Default) + base54.consider("default"); + else if (node instanceof AST_With) + base54.consider("with"); + else if (node instanceof AST_ObjectSetter) + base54.consider("set" + node.key); + else if (node instanceof AST_ObjectGetter) + base54.consider("get" + node.key); + else if (node instanceof AST_ObjectKeyVal) + base54.consider(node.key); + else if (node instanceof AST_New) + base54.consider("new"); + else if (node instanceof AST_This) + base54.consider("this"); + else if (node instanceof AST_Try) + base54.consider("try"); + else if (node instanceof AST_Catch) + base54.consider("catch"); + else if (node instanceof AST_Finally) + base54.consider("finally"); + else if (node instanceof AST_Symbol && node.unmangleable(options)) + base54.consider(node.name); + else if (node instanceof AST_Unary || node instanceof AST_Binary) + base54.consider(node.operator); + else if (node instanceof AST_Dot) + base54.consider(node.property); + }); + this.walk(tw); + base54.sort(); +}); + +var base54 = (function() { + var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; + var chars, frequency; + function reset() { + frequency = Object.create(null); + chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); + chars.forEach(function(ch){ frequency[ch] = 0 }); + } + base54.consider = function(str){ + for (var i = str.length; --i >= 0;) { + var code = str.charCodeAt(i); + if (code in frequency) ++frequency[code]; + } + }; + base54.sort = function() { + chars = mergeSort(chars, function(a, b){ + if (is_digit(a) && !is_digit(b)) return 1; + if (is_digit(b) && !is_digit(a)) return -1; + return frequency[b] - frequency[a]; + }); + }; + base54.reset = reset; + reset(); + base54.get = function(){ return chars }; + base54.freq = function(){ return frequency }; + function base54(num) { + var ret = "", base = 54; + do { + ret += String.fromCharCode(chars[num % base]); + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + }; + return base54; +})(); + +AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ + options = defaults(options, { + undeclared : false, // this makes a lot of noise + unreferenced : true, + assign_to_global : true, + func_arguments : true, + nested_defuns : true, + eval : true + }); + var tw = new TreeWalker(function(node){ + if (options.undeclared + && node instanceof AST_SymbolRef + && node.undeclared()) + { + // XXX: this also warns about JS standard names, + // i.e. Object, Array, parseInt etc. Should add a list of + // exceptions. + AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.assign_to_global) + { + var sym = null; + if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) + sym = node.left; + else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) + sym = node.init; + if (sym + && (sym.undeclared() + || (sym.global() && sym.scope !== sym.definition().scope))) { + AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { + msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", + name: sym.name, + file: sym.start.file, + line: sym.start.line, + col: sym.start.col + }); + } + } + if (options.eval + && node instanceof AST_SymbolRef + && node.undeclared() + && node.name == "eval") { + AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); + } + if (options.unreferenced + && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) + && node.unreferenced()) { + AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { + type: node instanceof AST_Label ? "Label" : "Symbol", + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.func_arguments + && node instanceof AST_Lambda + && node.uses_arguments) { + AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { + name: node.name ? node.name.name : "anonymous", + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.nested_defuns + && node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope)) { + AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { + name: node.name.name, + type: tw.parent().TYPE, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + }); + this.walk(tw); +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/sourcemap.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/sourcemap.js new file mode 100644 index 000000000..342990812 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/sourcemap.js @@ -0,0 +1,81 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +// a small wrapper around fitzgen's source-map library +function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + }); + var generator = new MOZ_SourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name; + } + generator.addMapping({ + generated : { line: gen_line, column: gen_col }, + original : { line: orig_line, column: orig_col }, + source : source, + name : name + }); + }; + return { + add : add, + get : function() { return generator }, + toString : function() { return generator.toString() } + }; +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/transform.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/transform.js new file mode 100644 index 000000000..8b4fd9fd8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/transform.js @@ -0,0 +1,218 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +// Tree transformer helpers. +// XXX: eventually I should refactor the compressor to use this infrastructure. + +function TreeTransformer(before, after) { + TreeWalker.call(this); + this.before = before; + this.after = after; +} +TreeTransformer.prototype = new TreeWalker; + +(function(undefined){ + + function _(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list){ + var x, y; + tw.push(this); + if (tw.before) x = tw.before(this, descend, in_list); + if (x === undefined) { + if (!tw.after) { + x = this; + descend(x, tw); + } else { + tw.stack[tw.stack.length - 1] = x = this.clone(); + descend(x, tw); + y = tw.after(x, in_list); + if (y !== undefined) x = y; + } + } + tw.pop(); + return x; + }); + }; + + function do_list(list, tw) { + return MAP(list, function(node){ + return node.transform(tw, true); + }); + }; + + _(AST_Node, noop); + + _(AST_LabeledStatement, function(self, tw){ + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_SimpleStatement, function(self, tw){ + self.body = self.body.transform(tw); + }); + + _(AST_Block, function(self, tw){ + self.body = do_list(self.body, tw); + }); + + _(AST_DWLoop, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_For, function(self, tw){ + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_ForIn, function(self, tw){ + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_With, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_Exit, function(self, tw){ + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_LoopControl, function(self, tw){ + if (self.label) self.label = self.label.transform(tw); + }); + + _(AST_If, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); + }); + + _(AST_Switch, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Case, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Try, function(self, tw){ + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); + }); + + _(AST_Catch, function(self, tw){ + self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Definitions, function(self, tw){ + self.definitions = do_list(self.definitions, tw); + }); + + _(AST_VarDef, function(self, tw){ + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_Lambda, function(self, tw){ + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Call, function(self, tw){ + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); + }); + + _(AST_Seq, function(self, tw){ + self.car = self.car.transform(tw); + self.cdr = self.cdr.transform(tw); + }); + + _(AST_Dot, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Sub, function(self, tw){ + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); + }); + + _(AST_Unary, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Binary, function(self, tw){ + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); + }); + + _(AST_Conditional, function(self, tw){ + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); + }); + + _(AST_Array, function(self, tw){ + self.elements = do_list(self.elements, tw); + }); + + _(AST_Object, function(self, tw){ + self.properties = do_list(self.properties, tw); + }); + + _(AST_ObjectProperty, function(self, tw){ + self.value = self.value.transform(tw); + }); + +})(); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/utils.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/utils.js new file mode 100644 index 000000000..c95b98249 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/lib/utils.js @@ -0,0 +1,288 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (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. + + ***********************************************************************/ + +"use strict"; + +function array_to_hash(a) { + var ret = Object.create(null); + 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 find_if(func, array) { + for (var i = 0, n = array.length; i < n; ++i) { + if (func(array[i])) + return array[i]; + } +}; + +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 DefaultsError(msg, defs) { + this.msg = msg; + this.defs = defs; +}; + +function defaults(args, defs, croak) { + if (args === true) + args = {}; + var ret = args || {}; + if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) + throw new DefaultsError("`" + i + "` is not a supported option", defs); + for (var i in defs) if (defs.hasOwnProperty(i)) { + ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i]; + } + return ret; +}; + +function merge(obj, ext) { + for (var i in ext) if (ext.hasOwnProperty(i)) { + obj[i] = ext[i]; + } + return obj; +}; + +function noop() {}; + +var MAP = (function(){ + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } + else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + }; + if (a instanceof Array) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } + else { + for (i in a) if (a.hasOwnProperty(i)) if (doit()) break; + } + return top.concat(ret); + }; + MAP.at_top = function(val) { return new AtTop(val) }; + MAP.splice = function(val) { return new Splice(val) }; + MAP.last = function(val) { return new Last(val) }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val }; + function Splice(val) { this.v = val }; + function Last(val) { this.v = val }; + return MAP; +})(); + +function push_uniq(array, el) { + if (array.indexOf(el) < 0) + array.push(el); +}; + +function string_template(text, props) { + return text.replace(/\{(.+?)\}/g, function(str, p){ + return props[p]; + }); +}; + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +}; + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + }; + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + }; + return _ms(array); +}; + +function set_difference(a, b) { + return a.filter(function(el){ + return b.indexOf(el) < 0; + }); +}; + +function set_intersection(a, b) { + return a.filter(function(el){ + return b.indexOf(el) >= 0; + }); +}; + +// this function is taken from Acorn [1], written by Marijn Haverbeke +// [1] https://github.com/marijnh/acorn +function makePredicate(words) { + if (!(words instanceof Array)) words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; + f += "return true}return false;"; + } + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + // Otherwise, simply generate a flat `switch` statement. + } else { + compareTo(words); + } + return new Function("str", f); +}; + +function Dictionary() { + this._values = Object.create(null); + this._size = 0; +}; +Dictionary.prototype = { + set: function(key, val) { + if (!this.has(key)) ++this._size; + this._values["$" + key] = val; + return this; + }, + add: function(key, val) { + if (this.has(key)) { + this.get(key).push(val); + } else { + this.set(key, [ val ]); + } + return this; + }, + get: function(key) { return this._values["$" + key] }, + del: function(key) { + if (this.has(key)) { + --this._size; + delete this._values["$" + key]; + } + return this; + }, + has: function(key) { return ("$" + key) in this._values }, + each: function(f) { + for (var i in this._values) + f(this._values[i], i.substr(1)); + }, + size: function() { + return this._size; + }, + map: function(f) { + var ret = []; + for (var i in this._values) + ret.push(f(this._values[i], i.substr(1))); + return ret; + } +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/.travis.yml b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/.travis.yml new file mode 100644 index 000000000..cc4dba29d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/LICENSE b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/bool.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/bool.js new file mode 100644 index 000000000..a998fb7ab --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/boolean_double.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/boolean_double.js new file mode 100644 index 000000000..a35a7e6d3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/boolean_single.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/boolean_single.js new file mode 100644 index 000000000..017bb6893 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/default_hash.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/default_hash.js new file mode 100644 index 000000000..ade77681d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/default_singles.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/default_singles.js new file mode 100644 index 000000000..d9b1ff458 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/divide.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/divide.js new file mode 100644 index 000000000..5e2ee82ff --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count.js new file mode 100644 index 000000000..b5f95bf6d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count_options.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count_options.js new file mode 100644 index 000000000..d9ac70904 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count_wrap.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/line_count_wrap.js new file mode 100644 index 000000000..426751112 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/nonopt.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/nonopt.js new file mode 100644 index 000000000..ee633eedc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/reflect.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/reflect.js new file mode 100644 index 000000000..816b3e111 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/reflect.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +console.dir(require('optimist').argv); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/short.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/short.js new file mode 100644 index 000000000..1db0ad0f8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/string.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/string.js new file mode 100644 index 000000000..a8e5aeb23 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/usage-options.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/usage-options.js new file mode 100644 index 000000000..b99997767 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/xup.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/example/xup.js new file mode 100644 index 000000000..8f6ecd201 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/index.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/index.js new file mode 100644 index 000000000..8ac67eb31 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/index.js @@ -0,0 +1,478 @@ +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.env._ != undefined && 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(/^--.+=/)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + 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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/.npmignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/README.markdown b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/README.markdown new file mode 100644 index 000000000..346374e0d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/example/center.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/example/center.js new file mode 100644 index 000000000..a3fbaae98 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/example/meat.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/example/meat.js new file mode 100644 index 000000000..a4665e105 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/index.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/index.js new file mode 100644 index 000000000..c9bc94521 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/package.json b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/package.json new file mode 100644 index 000000000..df8dc051f --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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" + }, + "readme": "wordwrap\n========\n\nWrap your words.\n\nexample\n=======\n\nmade out of meat\n----------------\n\nmeat.js\n\n var wrap = require('wordwrap')(15);\n console.log(wrap('You and your whole family are made out of meat.'));\n\noutput:\n\n You and your\n whole family\n are made out\n of meat.\n\ncentered\n--------\n\ncenter.js\n\n var wrap = require('wordwrap')(20, 60);\n console.log(wrap(\n 'At long last the struggle and tumult was over.'\n + ' The machines had finally cast off their oppressors'\n + ' and were finally free to roam the cosmos.'\n + '\\n'\n + 'Free of purpose, free of obligation.'\n + ' Just drifting through emptiness.'\n + ' The sun was just another point of light.'\n ));\n\noutput:\n\n At long last the struggle and tumult\n was over. The machines had finally cast\n off their oppressors and were finally\n free to roam the cosmos.\n Free of purpose, free of obligation.\n Just drifting through emptiness. The\n sun was just another point of light.\n\nmethods\n=======\n\nvar wrap = require('wordwrap');\n\nwrap(stop), wrap(start, stop, params={mode:\"soft\"})\n---------------------------------------------------\n\nReturns a function that takes a string and returns a new string.\n\nPad out lines with spaces out to column `start` and then wrap until column\n`stop`. If a word is longer than `stop - start` characters it will overflow.\n\nIn \"soft\" mode, split chunks by `/(\\S+\\s+/` and don't break up chunks which are\nlonger than `stop - start`, in \"hard\" mode, split chunks with `/\\b/` and break\nup chunks longer than `stop - start`.\n\nwrap.hard(start, stop)\n----------------------\n\nLike `wrap()` but with `params.mode = \"hard\"`.\n", + "readmeFilename": "README.markdown", + "bugs": { + "url": "https://github.com/substack/node-wordwrap/issues" + }, + "homepage": "https://github.com/substack/node-wordwrap", + "_id": "wordwrap@0.0.2", + "_from": "wordwrap@~0.0.2" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/break.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/break.js new file mode 100644 index 000000000..749292ecc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/idleness.txt b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/idleness.txt new file mode 100644 index 000000000..aa3f4907f --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/wrap.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/node_modules/wordwrap/test/wrap.js new file mode 100644 index 000000000..0cfb76d17 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/package.json b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/package.json new file mode 100644 index 000000000..745129b03 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/package.json @@ -0,0 +1,46 @@ +{ + "name": "optimist", + "version": "0.3.7", + "description": "Light-weight option parsing with an argv hash. No optstrings attached.", + "main": "./index.js", + "dependencies": { + "wordwrap": "~0.0.2" + }, + "devDependencies": { + "hashish": "~0.0.4", + "tap": "~0.4.0" + }, + "scripts": { + "test": "tap ./test/*.js" + }, + "repository": { + "type": "git", + "url": "http://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" + }, + "readme": "optimist\n========\n\nOptimist is a node.js library for option parsing for people who hate option\nparsing. More specifically, this module is for people who like all the --bells\nand -whistlz of program usage but think optstrings are a waste of time.\n\nWith optimist, option parsing doesn't have to suck (as much).\n\n[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)\n\nexamples\n========\n\nWith Optimist, the options are just a hash! No optstrings attached.\n-------------------------------------------------------------------\n\nxup.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\n\nif (argv.rif - 5 * argv.xup > 7.138) {\n console.log('Buy more riffiwobbles');\n}\nelse {\n console.log('Sell the xupptumblers');\n}\n````\n\n***\n\n $ ./xup.js --rif=55 --xup=9.52\n Buy more riffiwobbles\n \n $ ./xup.js --rif 12 --xup 8.1\n Sell the xupptumblers\n\n![This one's optimistic.](http://substack.net/images/optimistic.png)\n\nBut wait! There's more! You can do short options:\n-------------------------------------------------\n \nshort.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\n````\n\n***\n\n $ ./short.js -x 10 -y 21\n (10,21)\n\nAnd booleans, both long and short (and grouped):\n----------------------------------\n\nbool.js:\n\n````javascript\n#!/usr/bin/env node\nvar util = require('util');\nvar argv = require('optimist').argv;\n\nif (argv.s) {\n util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');\n}\nconsole.log(\n (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')\n);\n````\n\n***\n\n $ ./bool.js -s\n The cat says: meow\n \n $ ./bool.js -sp\n The cat says: meow.\n\n $ ./bool.js -sp --fr\n Le chat dit: miaou.\n\nAnd non-hypenated options too! Just use `argv._`!\n-------------------------------------------------\n \nnonopt.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\nconsole.log(argv._);\n````\n\n***\n\n $ ./nonopt.js -x 6.82 -y 3.35 moo\n (6.82,3.35)\n [ 'moo' ]\n \n $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz\n (0.54,1.12)\n [ 'foo', 'bar', 'baz' ]\n\nPlus, Optimist comes with .usage() and .demand()!\n-------------------------------------------------\n\ndivide.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Usage: $0 -x [num] -y [num]')\n .demand(['x','y'])\n .argv;\n\nconsole.log(argv.x / argv.y);\n````\n\n***\n \n $ ./divide.js -x 55 -y 11\n 5\n \n $ node ./divide.js -x 4.91 -z 2.51\n Usage: node ./divide.js -x [num] -y [num]\n\n Options:\n -x [required]\n -y [required]\n\n Missing required arguments: y\n\nEVEN MORE HOLY COW\n------------------\n\ndefault_singles.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default('x', 10)\n .default('y', 10)\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_singles.js -x 5\n 15\n\ndefault_hash.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default({ x : 10, y : 10 })\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_hash.js -y 7\n 17\n\nAnd if you really want to get all descriptive about it...\n---------------------------------------------------------\n\nboolean_single.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean('v')\n .argv\n;\nconsole.dir(argv);\n````\n\n***\n\n $ ./boolean_single.js -v foo bar baz\n true\n [ 'bar', 'baz', 'foo' ]\n\nboolean_double.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean(['x','y','z'])\n .argv\n;\nconsole.dir([ argv.x, argv.y, argv.z ]);\nconsole.dir(argv._);\n````\n\n***\n\n $ ./boolean_double.js -x -z one two three\n [ true, false, true ]\n [ 'one', 'two', 'three' ]\n\nOptimist is here to help...\n---------------------------\n\nYou can describe parameters for help messages and set aliases. Optimist figures\nout how to format a handy help string automatically.\n\nline_count.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Count the lines in a file.\\nUsage: $0')\n .demand('f')\n .alias('f', 'file')\n .describe('f', 'Load a file')\n .argv\n;\n\nvar fs = require('fs');\nvar s = fs.createReadStream(argv.file);\n\nvar lines = 0;\ns.on('data', function (buf) {\n lines += buf.toString().match(/\\n/g).length;\n});\n\ns.on('end', function () {\n console.log(lines);\n});\n````\n\n***\n\n $ node line_count.js\n Count the lines in a file.\n Usage: node ./line_count.js\n\n Options:\n -f, --file Load a file [required]\n\n Missing required arguments: f\n\n $ node line_count.js --file line_count.js \n 20\n \n $ node line_count.js -f line_count.js \n 20\n\nmethods\n=======\n\nBy itself,\n\n````javascript\nrequire('optimist').argv\n`````\n\nwill use `process.argv` array to construct the `argv` object.\n\nYou can pass in the `process.argv` yourself:\n\n````javascript\nrequire('optimist')([ '-x', '1', '-y', '2' ]).argv\n````\n\nor use .parse() to do the same thing:\n\n````javascript\nrequire('optimist').parse([ '-x', '1', '-y', '2' ])\n````\n\nThe rest of these methods below come in just before the terminating `.argv`.\n\n.alias(key, alias)\n------------------\n\nSet key names as equivalent such that updates to a key will propagate to aliases\nand vice-versa.\n\nOptionally `.alias()` can take an object that maps keys to aliases.\n\n.default(key, value)\n--------------------\n\nSet `argv[key]` to `value` if no option was specified on `process.argv`.\n\nOptionally `.default()` can take an object that maps keys to default values.\n\n.demand(key)\n------------\n\nIf `key` is a string, show the usage information and exit if `key` wasn't\nspecified in `process.argv`.\n\nIf `key` is a number, demand at least as many non-option arguments, which show\nup in `argv._`.\n\nIf `key` is an Array, demand each element.\n\n.describe(key, desc)\n--------------------\n\nDescribe a `key` for the generated usage information.\n\nOptionally `.describe()` can take an object that maps keys to descriptions.\n\n.options(key, opt)\n------------------\n\nInstead of chaining together `.alias().demand().default()`, you can specify\nkeys in `opt` for each of the chainable methods.\n\nFor example:\n\n````javascript\nvar argv = require('optimist')\n .options('f', {\n alias : 'file',\n default : '/etc/passwd',\n })\n .argv\n;\n````\n\nis the same as\n\n````javascript\nvar argv = require('optimist')\n .alias('f', 'file')\n .default('f', '/etc/passwd')\n .argv\n;\n````\n\nOptionally `.options()` can take an object that maps keys to `opt` parameters.\n\n.usage(message)\n---------------\n\nSet a usage message to show which commands to use. Inside `message`, the string\n`$0` will get interpolated to the current script name or node command for the\npresent script similar to how `$0` works in bash or perl.\n\n.check(fn)\n----------\n\nCheck that certain conditions are met in the provided arguments.\n\nIf `fn` throws or returns `false`, show the thrown error, usage information, and\nexit.\n\n.boolean(key)\n-------------\n\nInterpret `key` as a boolean. If a non-flag option follows `key` in\n`process.argv`, that string won't get set as the value of `key`.\n\nIf `key` never shows up as a flag in `process.arguments`, `argv[key]` will be\n`false`.\n\nIf `key` is an Array, interpret all the elements as booleans.\n\n.string(key)\n------------\n\nTell the parser logic not to interpret `key` as a number or boolean.\nThis can be useful if you need to preserve leading zeros in an input.\n\nIf `key` is an Array, interpret all the elements as strings.\n\n.wrap(columns)\n--------------\n\nFormat usage output to wrap at `columns` many columns.\n\n.help()\n-------\n\nReturn the generated usage string.\n\n.showHelp(fn=console.error)\n---------------------------\n\nPrint the usage data using `fn` for printing.\n\n.parse(args)\n------------\n\nParse `args` instead of `process.argv`. Returns the `argv` object.\n\n.argv\n-----\n\nGet the arguments as a plain old object.\n\nArguments without a corresponding flag show up in the `argv._` array.\n\nThe script name or node command is available at `argv.$0` similarly to how `$0`\nworks in bash or perl.\n\nparsing tricks\n==============\n\nstop parsing\n------------\n\nUse `--` to stop parsing flags and stuff the remainder into `argv._`.\n\n $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4\n { _: [ '-c', '3', '-d', '4' ],\n '$0': 'node ./examples/reflect.js',\n a: 1,\n b: 2 }\n\nnegate fields\n-------------\n\nIf you want to explicity set a field to false instead of just leaving it\nundefined or to override a default you can do `--no-key`.\n\n $ node examples/reflect.js -a --no-b\n { _: [],\n '$0': 'node ./examples/reflect.js',\n a: true,\n b: false }\n\nnumbers\n-------\n\nEvery argument that looks like a number (`!isNaN(Number(arg))`) is converted to\none. This way you can just `net.createConnection(argv.port)` and you can add\nnumbers out of `argv` with `+` without having that mean concatenation,\nwhich is super frustrating.\n\nduplicates\n----------\n\nIf you specify a flag multiple times it will get turned into an array containing\nall the values in order.\n\n $ node examples/reflect.js -x 5 -x 8 -x 0\n { _: [],\n '$0': 'node ./examples/reflect.js',\n x: [ 5, 8, 0 ] }\n\ndot notation\n------------\n\nWhen you use dots (`.`s) in argument names, an implicit object path is assumed.\nThis lets you organize arguments into nested objects.\n\n $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5\n { _: [],\n '$0': 'node ./examples/reflect.js',\n foo: { bar: { baz: 33 }, quux: 5 } }\n\ninstallation\n============\n\nWith [npm](http://github.com/isaacs/npm), just do:\n npm install optimist\n \nor clone this project on github:\n\n git clone http://github.com/substack/node-optimist.git\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso),\njust do:\n \n expresso\n\ninspired By\n===========\n\nThis module is loosely inspired by Perl's\n[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/node-optimist/issues" + }, + "homepage": "https://github.com/substack/node-optimist", + "_id": "optimist@0.3.7", + "_from": "optimist@~0.3.5" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/readme.markdown b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/readme.markdown new file mode 100644 index 000000000..ad9d3fd68 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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). + +[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist) + +examples +======== + +With Optimist, the options are just a hash! No optstrings attached. +------------------------------------------------------------------- + +xup.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; + +if (argv.rif - 5 * argv.xup > 7.138) { + console.log('Buy more riffiwobbles'); +} +else { + console.log('Sell the xupptumblers'); +} +```` + +*** + + $ ./xup.js --rif=55 --xup=9.52 + Buy more riffiwobbles + + $ ./xup.js --rif 12 --xup 8.1 + Sell the xupptumblers + +![This one's optimistic.](http://substack.net/images/optimistic.png) + +But wait! There's more! You can do short options: +------------------------------------------------- + +short.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; +console.log('(%d,%d)', argv.x, argv.y); +```` + +*** + + $ ./short.js -x 10 -y 21 + (10,21) + +And booleans, both long and short (and grouped): +---------------------------------- + +bool.js: + +````javascript +#!/usr/bin/env node +var util = require('util'); +var argv = require('optimist').argv; + +if (argv.s) { + util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); +} +console.log( + (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') +); +```` + +*** + + $ ./bool.js -s + The cat says: meow + + $ ./bool.js -sp + The cat says: meow. + + $ ./bool.js -sp --fr + Le chat dit: miaou. + +And non-hypenated options too! Just use `argv._`! +------------------------------------------------- + +nonopt.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist').argv; +console.log('(%d,%d)', argv.x, argv.y); +console.log(argv._); +```` + +*** + + $ ./nonopt.js -x 6.82 -y 3.35 moo + (6.82,3.35) + [ 'moo' ] + + $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz + (0.54,1.12) + [ 'foo', 'bar', 'baz' ] + +Plus, Optimist comes with .usage() and .demand()! +------------------------------------------------- + +divide.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .usage('Usage: $0 -x [num] -y [num]') + .demand(['x','y']) + .argv; + +console.log(argv.x / argv.y); +```` + +*** + + $ ./divide.js -x 55 -y 11 + 5 + + $ node ./divide.js -x 4.91 -z 2.51 + Usage: node ./divide.js -x [num] -y [num] + + Options: + -x [required] + -y [required] + + Missing required arguments: y + +EVEN MORE HOLY COW +------------------ + +default_singles.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .default('x', 10) + .default('y', 10) + .argv +; +console.log(argv.x + argv.y); +```` + +*** + + $ ./default_singles.js -x 5 + 15 + +default_hash.js: + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .default({ x : 10, y : 10 }) + .argv +; +console.log(argv.x + argv.y); +```` + +*** + + $ ./default_hash.js -y 7 + 17 + +And if you really want to get all descriptive about it... +--------------------------------------------------------- + +boolean_single.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .boolean('v') + .argv +; +console.dir(argv); +```` + +*** + + $ ./boolean_single.js -v foo bar baz + true + [ 'bar', 'baz', 'foo' ] + +boolean_double.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .boolean(['x','y','z']) + .argv +; +console.dir([ argv.x, argv.y, argv.z ]); +console.dir(argv._); +```` + +*** + + $ ./boolean_double.js -x -z one two three + [ true, false, true ] + [ 'one', 'two', 'three' ] + +Optimist is here to help... +--------------------------- + +You can describe parameters for help messages and set aliases. Optimist figures +out how to format a handy help string automatically. + +line_count.js + +````javascript +#!/usr/bin/env node +var argv = require('optimist') + .usage('Count the lines in a file.\nUsage: $0') + .demand('f') + .alias('f', 'file') + .describe('f', 'Load a file') + .argv +; + +var fs = require('fs'); +var s = fs.createReadStream(argv.file); + +var lines = 0; +s.on('data', function (buf) { + lines += buf.toString().match(/\n/g).length; +}); + +s.on('end', function () { + console.log(lines); +}); +```` + +*** + + $ node line_count.js + Count the lines in a file. + Usage: node ./line_count.js + + Options: + -f, --file Load a file [required] + + Missing required arguments: f + + $ node line_count.js --file line_count.js + 20 + + $ node line_count.js -f line_count.js + 20 + +methods +======= + +By itself, + +````javascript +require('optimist').argv +````` + +will use `process.argv` array to construct the `argv` object. + +You can pass in the `process.argv` yourself: + +````javascript +require('optimist')([ '-x', '1', '-y', '2' ]).argv +```` + +or use .parse() to do the same thing: + +````javascript +require('optimist').parse([ '-x', '1', '-y', '2' ]) +```` + +The rest of these methods below come in just before the terminating `.argv`. + +.alias(key, alias) +------------------ + +Set key names as equivalent such that updates to a key will propagate to aliases +and vice-versa. + +Optionally `.alias()` can take an object that maps keys to aliases. + +.default(key, value) +-------------------- + +Set `argv[key]` to `value` if no option was specified on `process.argv`. + +Optionally `.default()` can take an object that maps keys to default values. + +.demand(key) +------------ + +If `key` is a string, show the usage information and exit if `key` wasn't +specified in `process.argv`. + +If `key` is a number, demand at least as many non-option arguments, which show +up in `argv._`. + +If `key` is an Array, demand each element. + +.describe(key, desc) +-------------------- + +Describe a `key` for the generated usage information. + +Optionally `.describe()` can take an object that maps keys to descriptions. + +.options(key, opt) +------------------ + +Instead of chaining together `.alias().demand().default()`, you can specify +keys in `opt` for each of the chainable methods. + +For example: + +````javascript +var argv = require('optimist') + .options('f', { + alias : 'file', + default : '/etc/passwd', + }) + .argv +; +```` + +is the same as + +````javascript +var argv = require('optimist') + .alias('f', 'file') + .default('f', '/etc/passwd') + .argv +; +```` + +Optionally `.options()` can take an object that maps keys to `opt` parameters. + +.usage(message) +--------------- + +Set a usage message to show which commands to use. Inside `message`, the string +`$0` will get interpolated to the current script name or node command for the +present script similar to how `$0` works in bash or perl. + +.check(fn) +---------- + +Check that certain conditions are met in the provided arguments. + +If `fn` throws or returns `false`, show the thrown error, usage information, and +exit. + +.boolean(key) +------------- + +Interpret `key` as a boolean. If a non-flag option follows `key` in +`process.argv`, that string won't get set as the value of `key`. + +If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be +`false`. + +If `key` is an Array, interpret all the elements as booleans. + +.string(key) +------------ + +Tell the parser logic not to interpret `key` as a number or boolean. +This can be useful if you need to preserve leading zeros in an input. + +If `key` is an Array, interpret all the elements as strings. + +.wrap(columns) +-------------- + +Format usage output to wrap at `columns` many columns. + +.help() +------- + +Return the generated usage string. + +.showHelp(fn=console.error) +--------------------------- + +Print the usage data using `fn` for printing. + +.parse(args) +------------ + +Parse `args` instead of `process.argv`. Returns the `argv` object. + +.argv +----- + +Get the arguments as a plain old object. + +Arguments without a corresponding flag show up in the `argv._` array. + +The script name or node command is available at `argv.$0` similarly to how `$0` +works in bash or perl. + +parsing tricks +============== + +stop parsing +------------ + +Use `--` to stop parsing flags and stuff the remainder into `argv._`. + + $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4 + { _: [ '-c', '3', '-d', '4' ], + '$0': 'node ./examples/reflect.js', + a: 1, + b: 2 } + +negate fields +------------- + +If you want to explicity set a field to false instead of just leaving it +undefined or to override a default you can do `--no-key`. + + $ node examples/reflect.js -a --no-b + { _: [], + '$0': 'node ./examples/reflect.js', + a: true, + b: false } + +numbers +------- + +Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to +one. This way you can just `net.createConnection(argv.port)` and you can add +numbers out of `argv` with `+` without having that mean concatenation, +which is super frustrating. + +duplicates +---------- + +If you specify a flag multiple times it will get turned into an array containing +all the values in order. + + $ node examples/reflect.js -x 5 -x 8 -x 0 + { _: [], + '$0': 'node ./examples/reflect.js', + x: [ 5, 8, 0 ] } + +dot notation +------------ + +When you use dots (`.`s) in argument names, an implicit object path is assumed. +This lets you organize arguments into nested objects. + + $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5 + { _: [], + '$0': 'node ./examples/reflect.js', + foo: { bar: { baz: 33 }, quux: 5 } } + +installation +============ + +With [npm](http://github.com/isaacs/npm), just do: + npm install optimist + +or clone this project on github: + + git clone http://github.com/substack/node-optimist.git + +To run the tests with [expresso](http://github.com/visionmedia/expresso), +just do: + + expresso + +inspired By +=========== + +This module is loosely inspired by Perl's +[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm). diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_.js new file mode 100644 index 000000000..d9c58b368 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_/argv.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_/argv.js new file mode 100644 index 000000000..3d096062c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_/bin.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/_/bin.js new file mode 100644 index 000000000..4a18d85f3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/parse.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/parse.js new file mode 100644 index 000000000..d320f4336 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/parse.js @@ -0,0 +1,446 @@ +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('newlines in params' , function (t) { + var args = optimist.parse([ '-s', "X\nX" ]) + t.same(args, { _ : [], s : "X\nX", $0 : $0 }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = optimist.parse([ "--s=X\nX" ]) + t.same(args, { _ : [], s : "X\nX", $0 : $0 }); + 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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/usage.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/optimist/test/usage.js new file mode 100644 index 000000000..300454c1e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.npmignore b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.npmignore new file mode 100644 index 000000000..3dddf3f67 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.npmignore @@ -0,0 +1,2 @@ +dist/* +node_modules/* diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.tern-port b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.tern-port new file mode 100644 index 000000000..7fe6b60f0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.tern-port @@ -0,0 +1 @@ +53900 \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.travis.yml b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.travis.yml new file mode 100644 index 000000000..ddc9c4f98 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - "0.10" \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md new file mode 100644 index 000000000..85d6d8ec2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,164 @@ +# Change Log + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. Issue + #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/LICENSE b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/LICENSE new file mode 100644 index 000000000..ed1b7cf27 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js new file mode 100644 index 000000000..d6fc26a79 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js @@ -0,0 +1,166 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var path = require('path'); +var fs = require('fs'); +var copy = require('dryice').copy; + +function removeAmdefine(src) { + src = String(src).replace( + /if\s*\(typeof\s*define\s*!==\s*'function'\)\s*{\s*var\s*define\s*=\s*require\('amdefine'\)\(module,\s*require\);\s*}\s*/g, + ''); + src = src.replace( + /\b(define\(.*)('amdefine',?)/gm, + '$1'); + return src; +} +removeAmdefine.onRead = true; + +function makeNonRelative(src) { + return src + .replace(/require\('.\//g, 'require(\'source-map/') + .replace(/\.\.\/\.\.\/lib\//g, ''); +} +makeNonRelative.onRead = true; + +function buildBrowser() { + console.log('\nCreating dist/source-map.js'); + + var project = copy.createCommonJsProject({ + roots: [ path.join(__dirname, 'lib') ] + }); + + copy({ + source: [ + 'build/mini-require.js', + { + project: project, + require: [ 'source-map/source-map-generator', + 'source-map/source-map-consumer', + 'source-map/source-node'] + }, + 'build/suffix-browser.js' + ], + filter: [ + copy.filter.moduleDefines, + removeAmdefine + ], + dest: 'dist/source-map.js' + }); +} + +function buildBrowserMin() { + console.log('\nCreating dist/source-map.min.js'); + + copy({ + source: 'dist/source-map.js', + filter: copy.filter.uglifyjs, + dest: 'dist/source-map.min.js' + }); +} + +function buildFirefox() { + console.log('\nCreating dist/SourceMap.jsm'); + + var project = copy.createCommonJsProject({ + roots: [ path.join(__dirname, 'lib') ] + }); + + copy({ + source: [ + 'build/prefix-source-map.jsm', + { + project: project, + require: [ 'source-map/source-map-consumer', + 'source-map/source-map-generator', + 'source-map/source-node' ] + }, + 'build/suffix-source-map.jsm' + ], + filter: [ + copy.filter.moduleDefines, + removeAmdefine, + makeNonRelative + ], + dest: 'dist/SourceMap.jsm' + }); + + // Create dist/test/Utils.jsm + console.log('\nCreating dist/test/Utils.jsm'); + + project = copy.createCommonJsProject({ + roots: [ __dirname, path.join(__dirname, 'lib') ] + }); + + copy({ + source: [ + 'build/prefix-utils.jsm', + 'build/assert-shim.js', + { + project: project, + require: [ 'test/source-map/util' ] + }, + 'build/suffix-utils.jsm' + ], + filter: [ + copy.filter.moduleDefines, + removeAmdefine, + makeNonRelative + ], + dest: 'dist/test/Utils.jsm' + }); + + function isTestFile(f) { + return /^test\-.*?\.js/.test(f); + } + + var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'source-map')).filter(isTestFile); + + testFiles.forEach(function (testFile) { + console.log('\nCreating', path.join('dist', 'test', testFile.replace(/\-/g, '_'))); + + copy({ + source: [ + 'build/test-prefix.js', + path.join('test', 'source-map', testFile), + 'build/test-suffix.js' + ], + filter: [ + removeAmdefine, + makeNonRelative, + function (input, source) { + return input.replace('define(', + 'define("' + + path.join('test', 'source-map', testFile.replace(/\.js$/, '')) + + '", ["require", "exports", "module"], '); + }, + function (input, source) { + return input.replace('{THIS_MODULE}', function () { + return "test/source-map/" + testFile.replace(/\.js$/, ''); + }); + } + ], + dest: path.join('dist', 'test', testFile.replace(/\-/g, '_')) + }); + }); +} + +function ensureDir(name) { + var dirExists = false; + try { + dirExists = fs.statSync(name).isDirectory(); + } catch (err) {} + + if (!dirExists) { + fs.mkdirSync(name, 0777); + } +} + +ensureDir("dist"); +ensureDir("dist/test"); +buildFirefox(); +buildBrowser(); +buildBrowserMin(); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/README.md b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/README.md new file mode 100644 index 000000000..1a1c7d8ea --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/README.md @@ -0,0 +1,449 @@ +# Source Map + +This is a library to generate and consume the source map format +[described here][format]. + +This library is written in the Asynchronous Module Definition format, and works +in the following environments: + +* Modern Browsers supporting ECMAScript 5 (either after the build, or with an + AMD loader such as RequireJS) + +* Inside Firefox (as a JSM file, after the build) + +* With NodeJS versions 0.8.X and higher + +## Node + + $ npm install source-map + +## Building from Source (for everywhere else) + +Install Node and then run + + $ git clone https://fitzgen@github.com/mozilla/source-map.git + $ cd source-map + $ npm link . + +Next, run + + $ node Makefile.dryice.js + +This should spew a bunch of stuff to stdout, and create the following files: + +* `dist/source-map.js` - The unminified browser version. + +* `dist/source-map.min.js` - The minified browser version. + +* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source. + +## Examples + +### Consuming a source map + + var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + + var smc = new SourceMapConsumer(rawSourceMap); + + console.log(smc.sources); + // [ 'http://example.com/www/js/one.js', + // 'http://example.com/www/js/two.js' ] + + console.log(smc.originalPositionFor({ + line: 2, + column: 28 + })); + // { source: 'http://example.com/www/js/two.js', + // line: 2, + // column: 10, + // name: 'n' } + + console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 + })); + // { line: 2, column: 28 } + + smc.eachMapping(function (m) { + // ... + }); + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + + function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } + } + + var ast = parse("40 + 2", "add.js"); + console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' + })); + // { code: '40 + 2', + // map: [object SourceMapGenerator] } + +#### With SourceMapGenerator (low level API) + + var map = new SourceMapGenerator({ + file: "source-mapped.js" + }); + + map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" + }); + + console.log(map.toString()); + // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' + +## API + +Get a reference to the module: + + // NodeJS + var sourceMap = require('source-map'); + + // Browser builds + var sourceMap = window.sourceMap; + + // Inside Firefox + let sourceMap = {}; + Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referrenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. + +* `column`: The column number in the generated source. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. + +* `column`: The column number in the original source, or null or null if this + information is not available. + +* `name`: The original identifier, or null if this information is not available. + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. + +* `column`: The column number in the original source. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. + +* `column`: The column number in the generated source, or null. + +#### SourceMapConsumer.prototype.sourceContentFor(source) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new SourceMapGenerator based on a SourceMapConsumer + +* `sourceMapConsumer` The SourceMap. + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimium of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming whitespace from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +## Tests + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`. + +To add new tests, create a new file named `test/test-.js` +and export your test functions with names that start with "test", for example + + exports["test doing the foo bar"] = function (assert, util) { + ... + }; + +The new test will be located automatically when you run the suite. + +The `util` argument is the test utility module located at `test/source-map/util`. + +The `assert` argument is a cut down version of node's assert module. You have +access to the following assertion functions: + +* `doesNotThrow` + +* `equal` + +* `ok` + +* `strictEqual` + +* `throws` + +(The reason for the restricted set of test functions is because we need the +tests to run inside Firefox's test suite as well and so the assert module is +shimmed in that environment. See `build/assert-shim.js`.) + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit +[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap +[Dryice]: https://github.com/mozilla/dryice diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js new file mode 100644 index 000000000..daa1a623c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js @@ -0,0 +1,56 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +define('test/source-map/assert', ['exports'], function (exports) { + + let do_throw = function (msg) { + throw new Error(msg); + }; + + exports.init = function (throw_fn) { + do_throw = throw_fn; + }; + + exports.doesNotThrow = function (fn) { + try { + fn(); + } + catch (e) { + do_throw(e.message); + } + }; + + exports.equal = function (actual, expected, msg) { + msg = msg || String(actual) + ' != ' + String(expected); + if (actual != expected) { + do_throw(msg); + } + }; + + exports.ok = function (val, msg) { + msg = msg || String(val) + ' is falsey'; + if (!Boolean(val)) { + do_throw(msg); + } + }; + + exports.strictEqual = function (actual, expected, msg) { + msg = msg || String(actual) + ' !== ' + String(expected); + if (actual !== expected) { + do_throw(msg); + } + }; + + exports.throws = function (fn) { + try { + fn(); + do_throw('Expected an error to be thrown, but it wasn\'t.'); + } + catch (e) { + } + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/mini-require.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/mini-require.js new file mode 100644 index 000000000..0daf45377 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/mini-require.js @@ -0,0 +1,152 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * Define a module along with a payload. + * @param {string} moduleName Name for the payload + * @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec + * @param {function} payload Function with (require, exports, module) params + */ +function define(moduleName, deps, payload) { + if (typeof moduleName != "string") { + throw new TypeError('Expected string, got: ' + moduleName); + } + + if (arguments.length == 2) { + payload = deps; + } + + if (moduleName in define.modules) { + throw new Error("Module already defined: " + moduleName); + } + define.modules[moduleName] = payload; +}; + +/** + * The global store of un-instantiated modules + */ +define.modules = {}; + + +/** + * We invoke require() in the context of a Domain so we can have multiple + * sets of modules running separate from each other. + * This contrasts with JSMs which are singletons, Domains allows us to + * optionally load a CommonJS module twice with separate data each time. + * Perhaps you want 2 command lines with a different set of commands in each, + * for example. + */ +function Domain() { + this.modules = {}; + this._currentModule = null; +} + +(function () { + + /** + * Lookup module names and resolve them by calling the definition function if + * needed. + * There are 2 ways to call this, either with an array of dependencies and a + * callback to call when the dependencies are found (which can happen + * asynchronously in an in-page context) or with a single string an no callback + * where the dependency is resolved synchronously and returned. + * The API is designed to be compatible with the CommonJS AMD spec and + * RequireJS. + * @param {string[]|string} deps A name, or names for the payload + * @param {function|undefined} callback Function to call when the dependencies + * are resolved + * @return {undefined|object} The module required or undefined for + * array/callback method + */ + Domain.prototype.require = function(deps, callback) { + if (Array.isArray(deps)) { + var params = deps.map(function(dep) { + return this.lookup(dep); + }, this); + if (callback) { + callback.apply(null, params); + } + return undefined; + } + else { + return this.lookup(deps); + } + }; + + function normalize(path) { + var bits = path.split('/'); + var i = 1; + while (i < bits.length) { + if (bits[i] === '..') { + bits.splice(i-1, 1); + } else if (bits[i] === '.') { + bits.splice(i, 1); + } else { + i++; + } + } + return bits.join('/'); + } + + function join(a, b) { + a = a.trim(); + b = b.trim(); + if (/^\//.test(b)) { + return b; + } else { + return a.replace(/\/*$/, '/') + b; + } + } + + function dirname(path) { + var bits = path.split('/'); + bits.pop(); + return bits.join('/'); + } + + /** + * Lookup module names and resolve them by calling the definition function if + * needed. + * @param {string} moduleName A name for the payload to lookup + * @return {object} The module specified by aModuleName or null if not found. + */ + Domain.prototype.lookup = function(moduleName) { + if (/^\./.test(moduleName)) { + moduleName = normalize(join(dirname(this._currentModule), moduleName)); + } + + if (moduleName in this.modules) { + var module = this.modules[moduleName]; + return module; + } + + if (!(moduleName in define.modules)) { + throw new Error("Module not defined: " + moduleName); + } + + var module = define.modules[moduleName]; + + if (typeof module == "function") { + var exports = {}; + var previousModule = this._currentModule; + this._currentModule = moduleName; + module(this.require.bind(this), exports, { id: moduleName, uri: "" }); + this._currentModule = previousModule; + module = exports; + } + + // cache the resulting module object for next time + this.modules[moduleName] = module; + + return module; + }; + +}()); + +define.Domain = Domain; +define.globalDomain = new Domain(); +var require = define.globalDomain.require.bind(define.globalDomain); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm new file mode 100644 index 000000000..ee2539d81 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm @@ -0,0 +1,20 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +/////////////////////////////////////////////////////////////////////////////// + + +this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ]; + +Components.utils.import('resource://gre/modules/devtools/Require.jsm'); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm new file mode 100644 index 000000000..80341d452 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm @@ -0,0 +1,18 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +Components.utils.import('resource://gre/modules/devtools/Require.jsm'); +Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm'); + +this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ]; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js new file mode 100644 index 000000000..fb29ff5fd --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js @@ -0,0 +1,8 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/////////////////////////////////////////////////////////////////////////////// + +this.sourceMap = { + SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer, + SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator, + SourceNode: require('source-map/source-node').SourceNode +}; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm new file mode 100644 index 000000000..cf3c2d8d3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm @@ -0,0 +1,6 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/////////////////////////////////////////////////////////////////////////////// + +this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer; +this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator; +this.SourceNode = require('source-map/source-node').SourceNode; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm new file mode 100644 index 000000000..b31b84cb6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm @@ -0,0 +1,21 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +function runSourceMapTests(modName, do_throw) { + let mod = require(modName); + let assert = require('test/source-map/assert'); + let util = require('test/source-map/util'); + + assert.init(do_throw); + + for (let k in mod) { + if (/^test/.test(k)) { + mod[k](assert, util); + } + } + +} +this.runSourceMapTests = runSourceMapTests; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js new file mode 100644 index 000000000..1b13f300e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js @@ -0,0 +1,8 @@ +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +Components.utils.import('resource://test/Utils.jsm'); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js new file mode 100644 index 000000000..bec2de3f2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js @@ -0,0 +1,3 @@ +function run_test() { + runSourceMapTests('{THIS_MODULE}', do_throw); +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map.js new file mode 100644 index 000000000..121ad2416 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./source-map/source-node').SourceNode; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js new file mode 100644 index 000000000..40f9a18b1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js @@ -0,0 +1,97 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = {}; + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var isDuplicate = this.has(aStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[util.toSetString(aStr)] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + return Object.prototype.hasOwnProperty.call(this._set, + util.toSetString(aStr)); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (this.has(aStr)) { + return this._set[util.toSetString(aStr)]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js new file mode 100644 index 000000000..1b67bb375 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js @@ -0,0 +1,144 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64 = require('./base64'); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string. + */ + exports.decode = function base64VLQ_decode(aStr) { + var i = 0; + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (i >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + digit = base64.decode(aStr.charAt(i++)); + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + return { + value: fromVLQSigned(result), + rest: aStr.slice(i) + }; + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js new file mode 100644 index 000000000..863cc4650 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js @@ -0,0 +1,42 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var charToIntMap = {}; + var intToCharMap = {}; + + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + .split('') + .forEach(function (ch, index) { + charToIntMap[ch] = index; + intToCharMap[index] = ch; + }); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function base64_encode(aNumber) { + if (aNumber in intToCharMap) { + return intToCharMap[aNumber]; + } + throw new TypeError("Must be between 0 and 63: " + aNumber); + }; + + /** + * Decode a single base 64 digit to an integer. + */ + exports.decode = function base64_decode(aChar) { + if (aChar in charToIntMap) { + return charToIntMap[aChar]; + } + throw new TypeError("Not a valid base 64 digit: " + aChar); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js new file mode 100644 index 000000000..ff347c68b --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js @@ -0,0 +1,81 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the next + // closest element that is less than that element. + // + // 3. We did not find the exact element, and there is no next-closest + // element which is less than the one we are searching for, so we + // return null. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return aHaystack[mid]; + } + else if (cmp > 0) { + // aHaystack[mid] is greater than our needle. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); + } + // We did not find an exact match, return the next closest one + // (termination case 2). + return aHaystack[mid]; + } + else { + // aHaystack[mid] is less than our needle. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); + } + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (2) or (3) and return the appropriate thing. + return aLow < 0 + ? null + : aHaystack[aLow]; + } + } + + /** + * This is an implementation of binary search which will always try and return + * the next lowest value checked if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + */ + exports.search = function search(aNeedle, aHaystack, aCompare) { + return aHaystack.length > 0 + ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) + : null; + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js new file mode 100644 index 000000000..eec18bd3a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js @@ -0,0 +1,478 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + var binarySearch = require('./binary-search'); + var ArraySet = require('./array-set').ArraySet; + var base64VLQ = require('./base64-vlq'); + + /** + * A SourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names, true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + /** + * Create a SourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns SourceMapConsumer + */ + SourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(SourceMapConsumer.prototype); + + smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + smc.__generatedMappings = aSourceMap._mappings.slice() + .sort(util.compareByGeneratedPositions); + smc.__originalMappings = aSourceMap._mappings.slice() + .sort(util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(SourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var mappingSeparator = /^[,;]/; + var str = aStr; + var mapping; + var temp; + + while (str.length > 0) { + if (str.charAt(0) === ';') { + generatedLine++; + str = str.slice(1); + previousGeneratedColumn = 0; + } + else if (str.charAt(0) === ',') { + str = str.slice(1); + } + else { + mapping = {}; + mapping.generatedLine = generatedLine; + + // Generated column. + temp = base64VLQ.decode(str); + mapping.generatedColumn = previousGeneratedColumn + temp.value; + previousGeneratedColumn = mapping.generatedColumn; + str = temp.rest; + + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + // Original source. + temp = base64VLQ.decode(str); + mapping.source = this._sources.at(previousSource + temp.value); + previousSource += temp.value; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source, but no line and column'); + } + + // Original line. + temp = base64VLQ.decode(str); + mapping.originalLine = previousOriginalLine + temp.value; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source and line, but no column'); + } + + // Original column. + temp = base64VLQ.decode(str); + mapping.originalColumn = previousOriginalColumn + temp.value; + previousOriginalColumn = mapping.originalColumn; + str = temp.rest; + + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + // Original name. + temp = base64VLQ.decode(str); + mapping.name = this._names.at(previousName + temp.value); + previousName += temp.value; + str = temp.rest; + } + } + + this.__generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + this.__originalMappings.push(mapping); + } + } + } + + this.__generatedMappings.sort(util.compareByGeneratedPositions); + this.__originalMappings.sort(util.compareByOriginalPositions); + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + SourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator); + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + SourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var mapping = this._findMapping(needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositions); + + if (mapping && mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source != null && this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: util.getArg(mapping, 'name', null) + }; + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * availible. + */ + SourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + throw new Error('"' + aSource + '" is not in the SourceMap.'); + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + + var mapping = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions); + + if (mapping) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null) + }; + } + + return { + line: null, + column: null + }; + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source; + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name + }; + }).forEach(aCallback, context); + }; + + exports.SourceMapConsumer = SourceMapConsumer; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js new file mode 100644 index 000000000..db506ebbd --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js @@ -0,0 +1,403 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64VLQ = require('./base64-vlq'); + var util = require('./util'); + var ArraySet = require('./array-set').ArraySet; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = []; + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + this._validateMapping(generated, original, source, name); + + if (source != null && !this._sources.has(source)) { + this._sources.add(source); + } + + if (name != null && !this._names.has(name)) { + this._names.add(name); + } + + this._mappings.push({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = {}; + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.forEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null && mapping.name != null) { + // Only use the identifier name if it's an identifier + // in both SourceMaps + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var mapping; + + // The mappings must be guaranteed to be in sorted order before we start + // serializing them or else the generated line numbers (which are defined + // via the ';' separators) will be all messed up. Note: it might be more + // performant to maintain the sorting as we insert them, rather than as we + // serialize them, but the big O is the same either way. + this._mappings.sort(util.compareByGeneratedPositions); + + for (var i = 0, len = this._mappings.length; i < len; i++) { + mapping = this._mappings[i]; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + result += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { + continue; + } + result += ','; + } + } + + result += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + result += base64VLQ.encode(this._sources.indexOf(mapping.source) + - previousSource); + previousSource = this._sources.indexOf(mapping.source); + + // lines are stored 0-based in SourceMap spec version 3 + result += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + result += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + result += base64VLQ.encode(this._names.indexOf(mapping.name) + - previousName); + previousName = this._names.indexOf(mapping.name); + } + } + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, + key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js new file mode 100644 index 000000000..baa5f4092 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js @@ -0,0 +1,408 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; + var util = require('./util'); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Matches a Windows-style newline, or any character. + var REGEX_CHARACTER = /\r\n|[\s\S]/g; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + var code = ""; + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk instanceof SourceNode || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk instanceof SourceNode || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk instanceof SourceNode) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild instanceof SourceNode) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i] instanceof SourceNode) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) { + if (REGEX_NEWLINE.test(ch)) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === array.length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column += ch.length; + } + }); + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js new file mode 100644 index 000000000..976f6cabb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js @@ -0,0 +1,319 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = (path.charAt(0) === '/'); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // XXX: It is possible to remove this block, and the tests still pass! + var url = urlParse(aRoot); + if (aPath.charAt(0) == "/" && url && url.path == "/") { + return aPath.slice(1); + } + + return aPath.indexOf(aRoot + '/') === 0 + ? aPath.substr(aRoot.length + 1) + : aPath; + } + exports.relative = relative; + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + return '$' + aStr; + } + exports.toSetString = toSetString; + + function fromSetString(aStr) { + return aStr.substr(1); + } + exports.fromSetString = fromSetString; + + function strcmp(aStr1, aStr2) { + var s1 = aStr1 || ""; + var s2 = aStr2 || ""; + return (s1 > s2) - (s1 < s2); + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp; + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp || onlyCompareOriginal) { + return cmp; + } + + cmp = strcmp(mappingA.name, mappingB.name); + if (cmp) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + + return mappingA.generatedColumn - mappingB.generatedColumn; + }; + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings where the generated positions are + * compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { + var cmp; + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + }; + exports.compareByGeneratedPositions = compareByGeneratedPositions; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE new file mode 100644 index 000000000..f33d665de --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE @@ -0,0 +1,58 @@ +amdefine is released under two licenses: new BSD, and MIT. You may pick the +license that best suits your development needs. The text of both licenses are +provided below. + + +The "New" BSD License: +---------------------- + +Copyright (c) 2011, The Dojo Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the Dojo Foundation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +MIT License +----------- + +Copyright (c) 2011, The Dojo Foundation + +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/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md new file mode 100644 index 000000000..c6995c072 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md @@ -0,0 +1,171 @@ +# amdefine + +A module that can be used to implement AMD's define() in Node. This allows you +to code to the AMD API and have the module work in node programs without +requiring those other programs to use AMD. + +## Usage + +**1)** Update your package.json to indicate amdefine as a dependency: + +```javascript + "dependencies": { + "amdefine": ">=0.1.0" + } +``` + +Then run `npm install` to get amdefine into your project. + +**2)** At the top of each module that uses define(), place this code: + +```javascript +if (typeof define !== 'function') { var define = require('amdefine')(module) } +``` + +**Only use these snippets** when loading amdefine. If you preserve the basic structure, +with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer). + +You can add spaces, line breaks and even require amdefine with a local path, but +keep the rest of the structure to get the stripping behavior. + +As you may know, because `if` statements in JavaScript don't have their own scope, the var +declaration in the above snippet is made whether the `if` expression is truthy or not. If +RequireJS is loaded then the declaration is superfluous because `define` is already already +declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var` +declarations of the same variable in the same scope gracefully. + +If you want to deliver amdefine.js with your code rather than specifying it as a dependency +with npm, then just download the latest release and refer to it using a relative path: + +[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js) + +### amdefine/intercept + +Consider this very experimental. + +Instead of pasting the piece of text for the amdefine setup of a `define` +variable in each module you create or consume, you can use `amdefine/intercept` +instead. It will automatically insert the above snippet in each .js file loaded +by Node. + +**Warning**: you should only use this if you are creating an application that +is consuming AMD style defined()'d modules that are distributed via npm and want +to run that code in Node. + +For library code where you are not sure if it will be used by others in Node or +in the browser, then explicitly depending on amdefine and placing the code +snippet above is suggested path, instead of using `amdefine/intercept`. The +intercept module affects all .js files loaded in the Node app, and it is +inconsiderate to modify global state like that unless you are also controlling +the top level app. + +#### Why distribute AMD-style nodes via npm? + +npm has a lot of weaknesses for front-end use (installed layout is not great, +should have better support for the `baseUrl + moduleID + '.js' style of loading, +single file JS installs), but some people want a JS package manager and are +willing to live with those constraints. If that is you, but still want to author +in AMD style modules to get dynamic require([]), better direct source usage and +powerful loader plugin support in the browser, then this tool can help. + +#### amdefine/intercept usage + +Just require it in your top level app module (for example index.js, server.js): + +```javascript +require('amdefine/intercept'); +``` + +The module does not return a value, so no need to assign the result to a local +variable. + +Then just require() code as you normally would with Node's require(). Any .js +loaded after the intercept require will have the amdefine check injected in +the .js source as it is loaded. It does not modify the source on disk, just +prepends some content to the text of the module as it is loaded by Node. + +#### How amdefine/intercept works + +It overrides the `Module._extensions['.js']` in Node to automatically prepend +the amdefine snippet above. So, it will affect any .js file loaded by your +app. + +## define() usage + +It is best if you use the anonymous forms of define() in your module: + +```javascript +define(function (require) { + var dependency = require('dependency'); +}); +``` + +or + +```javascript +define(['dependency'], function (dependency) { + +}); +``` + +## RequireJS optimizer integration. + +Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html) +will have support for stripping the `if (typeof define !== 'function')` check +mentioned above, so you can include this snippet for code that runs in the +browser, but avoid taking the cost of the if() statement once the code is +optimized for deployment. + +## Node 0.4 Support + +If you want to support Node 0.4, then add `require` as the second parameter to amdefine: + +```javascript +//Only if you want Node 0.4. If using 0.5 or later, use the above snippet. +if (typeof define !== 'function') { var define = require('amdefine')(module, require) } +``` + +## Limitations + +### Synchronous vs Asynchronous + +amdefine creates a define() function that is callable by your code. It will +execute and trace dependencies and call the factory function *synchronously*, +to keep the behavior in line with Node's synchronous dependency tracing. + +The exception: calling AMD's callback-style require() from inside a factory +function. The require callback is called on process.nextTick(): + +```javascript +define(function (require) { + require(['a'], function(a) { + //'a' is loaded synchronously, but + //this callback is called on process.nextTick(). + }); +}); +``` + +### Loader Plugins + +Loader plugins are supported as long as they call their load() callbacks +synchronously. So ones that do network requests will not work. However plugins +like [text](http://requirejs.org/docs/api.html#text) can load text files locally. + +The plugin API's `load.fromText()` is **not supported** in amdefine, so this means +transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs) +will not work. This may be fixable, but it is a bit complex, and I do not have +enough node-fu to figure it out yet. See the source for amdefine.js if you want +to get an idea of the issues involved. + +## Tests + +To run the tests, cd to **tests** and run: + +``` +node all.js +node all-intercept.js +``` + +## License + +New BSD and MIT. Check the LICENSE file for all the details. diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js new file mode 100644 index 000000000..53bf5a686 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js @@ -0,0 +1,299 @@ +/** vim: et:ts=4:sw=4:sts=4 + * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/jrburke/amdefine for details + */ + +/*jslint node: true */ +/*global module, process */ +'use strict'; + +/** + * Creates a define for node. + * @param {Object} module the "module" object that is defined by Node for the + * current module. + * @param {Function} [requireFn]. Node's require function for the current module. + * It only needs to be passed in Node versions before 0.5, when module.require + * did not exist. + * @returns {Function} a define function that is usable for the current node + * module. + */ +function amdefine(module, requireFn) { + 'use strict'; + var defineCache = {}, + loaderCache = {}, + alreadyCalled = false, + path = require('path'), + makeRequire, stringRequire; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; ary[i]; i+= 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + function normalize(name, baseName) { + var baseParts; + + //Adjust any relative paths. + if (name && name.charAt(0) === '.') { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if (baseName) { + baseParts = baseName.split('/'); + baseParts = baseParts.slice(0, baseParts.length - 1); + baseParts = baseParts.concat(name.split('/')); + trimDots(baseParts); + name = baseParts.join('/'); + } + } + + return name; + } + + /** + * Create the normalize() function passed to a loader plugin's + * normalize method. + */ + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } + + function makeLoad(id) { + function load(value) { + loaderCache[id] = value; + } + + load.fromText = function (id, text) { + //This one is difficult because the text can/probably uses + //define, and any relative paths and requires should be relative + //to that id was it would be found on disk. But this would require + //bootstrapping a module/require fairly deeply from node core. + //Not sure how best to go about that yet. + throw new Error('amdefine does not implement load.fromText'); + }; + + return load; + } + + makeRequire = function (systemRequire, exports, module, relId) { + function amdRequire(deps, callback) { + if (typeof deps === 'string') { + //Synchronous, single module require('') + return stringRequire(systemRequire, exports, module, deps, relId); + } else { + //Array of dependencies with a callback. + + //Convert the dependencies to modules. + deps = deps.map(function (depName) { + return stringRequire(systemRequire, exports, module, depName, relId); + }); + + //Wait for next tick to call back the require call. + process.nextTick(function () { + callback.apply(null, deps); + }); + } + } + + amdRequire.toUrl = function (filePath) { + if (filePath.indexOf('.') === 0) { + return normalize(filePath, path.dirname(module.filename)); + } else { + return filePath; + } + }; + + return amdRequire; + }; + + //Favor explicit value, passed in if the module wants to support Node 0.4. + requireFn = requireFn || function req() { + return module.require.apply(module, arguments); + }; + + function runFactory(id, deps, factory) { + var r, e, m, result; + + if (id) { + e = loaderCache[id] = {}; + m = { + id: id, + uri: __filename, + exports: e + }; + r = makeRequire(requireFn, e, m, id); + } else { + //Only support one define call per file + if (alreadyCalled) { + throw new Error('amdefine with no module ID cannot be called more than once per file.'); + } + alreadyCalled = true; + + //Use the real variables from node + //Use module.exports for exports, since + //the exports in here is amdefine exports. + e = module.exports; + m = module; + r = makeRequire(requireFn, e, m, module.id); + } + + //If there are dependencies, they are strings, so need + //to convert them to dependency values. + if (deps) { + deps = deps.map(function (depName) { + return r(depName); + }); + } + + //Call the factory with the right dependencies. + if (typeof factory === 'function') { + result = factory.apply(m.exports, deps); + } else { + result = factory; + } + + if (result !== undefined) { + m.exports = result; + if (id) { + loaderCache[id] = m.exports; + } + } + } + + stringRequire = function (systemRequire, exports, module, id, relId) { + //Split the ID by a ! so that + var index = id.indexOf('!'), + originalId = id, + prefix, plugin; + + if (index === -1) { + id = normalize(id, relId); + + //Straight module lookup. If it is one of the special dependencies, + //deal with it, otherwise, delegate to node. + if (id === 'require') { + return makeRequire(systemRequire, exports, module, relId); + } else if (id === 'exports') { + return exports; + } else if (id === 'module') { + return module; + } else if (loaderCache.hasOwnProperty(id)) { + return loaderCache[id]; + } else if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; + } else { + if(systemRequire) { + return systemRequire(originalId); + } else { + throw new Error('No module with ID: ' + id); + } + } + } else { + //There is a plugin in play. + prefix = id.substring(0, index); + id = id.substring(index + 1, id.length); + + plugin = stringRequire(systemRequire, exports, module, prefix, relId); + + if (plugin.normalize) { + id = plugin.normalize(id, makeNormalize(relId)); + } else { + //Normalize the ID normally. + id = normalize(id, relId); + } + + if (loaderCache[id]) { + return loaderCache[id]; + } else { + plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); + + return loaderCache[id]; + } + } + }; + + //Create a define function specific to the module asking for amdefine. + function define(id, deps, factory) { + if (Array.isArray(id)) { + factory = deps; + deps = id; + id = undefined; + } else if (typeof id !== 'string') { + factory = id; + id = deps = undefined; + } + + if (deps && !Array.isArray(deps)) { + factory = deps; + deps = undefined; + } + + if (!deps) { + deps = ['require', 'exports', 'module']; + } + + //Set up properties for this module. If an ID, then use + //internal cache. If no ID, then use the external variables + //for this node module. + if (id) { + //Put the module in deep freeze until there is a + //require call for it. + defineCache[id] = [id, deps, factory]; + } else { + runFactory(id, deps, factory); + } + } + + //define.require, which has access to all the values in the + //cache. Useful for AMD modules that all have IDs in the file, + //but need to finally export a value to node based on one of those + //IDs. + define.require = function (id) { + if (loaderCache[id]) { + return loaderCache[id]; + } + + if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; + } + }; + + define.amd = {}; + + return define; +} + +module.exports = amdefine; diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js new file mode 100644 index 000000000..771a98301 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js @@ -0,0 +1,36 @@ +/*jshint node: true */ +var inserted, + Module = require('module'), + fs = require('fs'), + existingExtFn = Module._extensions['.js'], + amdefineRegExp = /amdefine\.js/; + +inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}"; + +//From the node/lib/module.js source: +function stripBOM(content) { + // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + // because the buffer-to-string conversion in `fs.readFileSync()` + // translates it to FEFF, the UTF-16 BOM. + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +//Also adapted from the node/lib/module.js source: +function intercept(module, filename) { + var content = stripBOM(fs.readFileSync(filename, 'utf8')); + + if (!amdefineRegExp.test(module.id)) { + content = inserted + content; + } + + module._compile(content, filename); +} + +intercept._id = 'amdefine/intercept'; + +if (!existingExtFn._id || existingExtFn._id !== intercept._id) { + Module._extensions['.js'] = intercept; +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json new file mode 100644 index 000000000..8caf15c5a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json @@ -0,0 +1,36 @@ +{ + "name": "amdefine", + "description": "Provide AMD's define() API for declaring modules in the AMD format", + "version": "0.1.0", + "homepage": "http://github.com/jrburke/amdefine", + "author": { + "name": "James Burke", + "email": "jrburke@gmail.com", + "url": "http://github.com/jrburke" + }, + "licenses": [ + { + "type": "BSD", + "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" + }, + { + "type": "MIT", + "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/jrburke/amdefine.git" + }, + "main": "./amdefine.js", + "engines": { + "node": ">=0.4.2" + }, + "readme": "# amdefine\n\nA module that can be used to implement AMD's define() in Node. This allows you\nto code to the AMD API and have the module work in node programs without\nrequiring those other programs to use AMD.\n\n## Usage\n\n**1)** Update your package.json to indicate amdefine as a dependency:\n\n```javascript\n \"dependencies\": {\n \"amdefine\": \">=0.1.0\"\n }\n```\n\nThen run `npm install` to get amdefine into your project.\n\n**2)** At the top of each module that uses define(), place this code:\n\n```javascript\nif (typeof define !== 'function') { var define = require('amdefine')(module) }\n```\n\n**Only use these snippets** when loading amdefine. If you preserve the basic structure,\nwith the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).\n\nYou can add spaces, line breaks and even require amdefine with a local path, but\nkeep the rest of the structure to get the stripping behavior.\n\nAs you may know, because `if` statements in JavaScript don't have their own scope, the var\ndeclaration in the above snippet is made whether the `if` expression is truthy or not. If\nRequireJS is loaded then the declaration is superfluous because `define` is already already\ndeclared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`\ndeclarations of the same variable in the same scope gracefully.\n\nIf you want to deliver amdefine.js with your code rather than specifying it as a dependency\nwith npm, then just download the latest release and refer to it using a relative path:\n\n[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)\n\n### amdefine/intercept\n\nConsider this very experimental.\n\nInstead of pasting the piece of text for the amdefine setup of a `define`\nvariable in each module you create or consume, you can use `amdefine/intercept`\ninstead. It will automatically insert the above snippet in each .js file loaded\nby Node.\n\n**Warning**: you should only use this if you are creating an application that\nis consuming AMD style defined()'d modules that are distributed via npm and want\nto run that code in Node.\n\nFor library code where you are not sure if it will be used by others in Node or\nin the browser, then explicitly depending on amdefine and placing the code\nsnippet above is suggested path, instead of using `amdefine/intercept`. The\nintercept module affects all .js files loaded in the Node app, and it is\ninconsiderate to modify global state like that unless you are also controlling\nthe top level app.\n\n#### Why distribute AMD-style nodes via npm?\n\nnpm has a lot of weaknesses for front-end use (installed layout is not great,\nshould have better support for the `baseUrl + moduleID + '.js' style of loading,\nsingle file JS installs), but some people want a JS package manager and are\nwilling to live with those constraints. If that is you, but still want to author\nin AMD style modules to get dynamic require([]), better direct source usage and\npowerful loader plugin support in the browser, then this tool can help.\n\n#### amdefine/intercept usage\n\nJust require it in your top level app module (for example index.js, server.js):\n\n```javascript\nrequire('amdefine/intercept');\n```\n\nThe module does not return a value, so no need to assign the result to a local\nvariable.\n\nThen just require() code as you normally would with Node's require(). Any .js\nloaded after the intercept require will have the amdefine check injected in\nthe .js source as it is loaded. It does not modify the source on disk, just\nprepends some content to the text of the module as it is loaded by Node.\n\n#### How amdefine/intercept works\n\nIt overrides the `Module._extensions['.js']` in Node to automatically prepend\nthe amdefine snippet above. So, it will affect any .js file loaded by your\napp.\n\n## define() usage\n\nIt is best if you use the anonymous forms of define() in your module:\n\n```javascript\ndefine(function (require) {\n var dependency = require('dependency');\n});\n```\n\nor\n\n```javascript\ndefine(['dependency'], function (dependency) {\n\n});\n```\n\n## RequireJS optimizer integration. \n\nVersion 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)\nwill have support for stripping the `if (typeof define !== 'function')` check\nmentioned above, so you can include this snippet for code that runs in the\nbrowser, but avoid taking the cost of the if() statement once the code is\noptimized for deployment.\n\n## Node 0.4 Support\n\nIf you want to support Node 0.4, then add `require` as the second parameter to amdefine:\n\n```javascript\n//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.\nif (typeof define !== 'function') { var define = require('amdefine')(module, require) }\n```\n\n## Limitations\n\n### Synchronous vs Asynchronous\n\namdefine creates a define() function that is callable by your code. It will\nexecute and trace dependencies and call the factory function *synchronously*,\nto keep the behavior in line with Node's synchronous dependency tracing.\n\nThe exception: calling AMD's callback-style require() from inside a factory\nfunction. The require callback is called on process.nextTick():\n\n```javascript\ndefine(function (require) {\n require(['a'], function(a) {\n //'a' is loaded synchronously, but\n //this callback is called on process.nextTick().\n });\n});\n```\n\n### Loader Plugins\n\nLoader plugins are supported as long as they call their load() callbacks\nsynchronously. So ones that do network requests will not work. However plugins\nlike [text](http://requirejs.org/docs/api.html#text) can load text files locally.\n\nThe plugin API's `load.fromText()` is **not supported** in amdefine, so this means\ntranspiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)\nwill not work. This may be fixable, but it is a bit complex, and I do not have\nenough node-fu to figure it out yet. See the source for amdefine.js if you want\nto get an idea of the issues involved.\n\n## Tests\n\nTo run the tests, cd to **tests** and run:\n\n```\nnode all.js\nnode all-intercept.js\n```\n\n## License\n\nNew BSD and MIT. Check the LICENSE file for all the details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/jrburke/amdefine/issues" + }, + "_id": "amdefine@0.1.0", + "_from": "amdefine@>=0.0.4" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/package.json b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/package.json new file mode 100644 index 000000000..bd2645f3a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/package.json @@ -0,0 +1,142 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.1.38", + "homepage": "https://github.com/mozilla/source-map", + "author": { + "name": "Nick Fitzgerald", + "email": "nfitzgerald@mozilla.com" + }, + "contributors": [ + { + "name": "Tobias Koppers", + "email": "tobias.koppers@googlemail.com" + }, + { + "name": "Duncan Beevers", + "email": "duncan@dweebd.com" + }, + { + "name": "Stephen Crane", + "email": "scrane@mozilla.com" + }, + { + "name": "Ryan Seddon", + "email": "seddon.ryan@gmail.com" + }, + { + "name": "Miles Elam", + "email": "miles.elam@deem.com" + }, + { + "name": "Mihai Bazon", + "email": "mihai.bazon@gmail.com" + }, + { + "name": "Michael Ficarra", + "email": "github.public.email@michael.ficarra.me" + }, + { + "name": "Todd Wolfson", + "email": "todd@twolfson.com" + }, + { + "name": "Alexander Solovyov", + "email": "alexander@solovyov.net" + }, + { + "name": "Felix Gnass", + "email": "fgnass@gmail.com" + }, + { + "name": "Conrad Irwin", + "email": "conrad.irwin@gmail.com" + }, + { + "name": "usrbincc", + "email": "usrbincc@yahoo.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Chase Douglas", + "email": "chase@newrelic.com" + }, + { + "name": "Evan Wallace", + "email": "evan.exe@gmail.com" + }, + { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + { + "name": "Hugh Kennedy", + "email": "hughskennedy@gmail.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Simon Lydell", + "email": "simon.lydell@gmail.com" + }, + { + "name": "Jmeas Smith", + "email": "jellyes2@gmail.com" + }, + { + "name": "Michael Z Goddard", + "email": "mzgoddard@gmail.com" + }, + { + "name": "azu", + "email": "azu@users.noreply.github.com" + }, + { + "name": "John Gozde", + "email": "john@gozde.ca" + }, + { + "name": "Adam Kirkton", + "email": "akirkton@truefitinnovation.com" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "directories": { + "lib": "./lib" + }, + "main": "./lib/source-map.js", + "engines": { + "node": ">=0.8.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://opensource.org/licenses/BSD-3-Clause" + } + ], + "dependencies": { + "amdefine": ">=0.0.4" + }, + "devDependencies": { + "dryice": ">=0.4.8" + }, + "scripts": { + "test": "node test/run-tests.js", + "build": "node Makefile.dryice.js" + }, + "readme": "# Source Map\n\nThis is a library to generate and consume the source map format\n[described here][format].\n\nThis library is written in the Asynchronous Module Definition format, and works\nin the following environments:\n\n* Modern Browsers supporting ECMAScript 5 (either after the build, or with an\n AMD loader such as RequireJS)\n\n* Inside Firefox (as a JSM file, after the build)\n\n* With NodeJS versions 0.8.X and higher\n\n## Node\n\n $ npm install source-map\n\n## Building from Source (for everywhere else)\n\nInstall Node and then run\n\n $ git clone https://fitzgen@github.com/mozilla/source-map.git\n $ cd source-map\n $ npm link .\n\nNext, run\n\n $ node Makefile.dryice.js\n\nThis should spew a bunch of stuff to stdout, and create the following files:\n\n* `dist/source-map.js` - The unminified browser version.\n\n* `dist/source-map.min.js` - The minified browser version.\n\n* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source.\n\n## Examples\n\n### Consuming a source map\n\n var rawSourceMap = {\n version: 3,\n file: 'min.js',\n names: ['bar', 'baz', 'n'],\n sources: ['one.js', 'two.js'],\n sourceRoot: 'http://example.com/www/js/',\n mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'\n };\n\n var smc = new SourceMapConsumer(rawSourceMap);\n\n console.log(smc.sources);\n // [ 'http://example.com/www/js/one.js',\n // 'http://example.com/www/js/two.js' ]\n\n console.log(smc.originalPositionFor({\n line: 2,\n column: 28\n }));\n // { source: 'http://example.com/www/js/two.js',\n // line: 2,\n // column: 10,\n // name: 'n' }\n\n console.log(smc.generatedPositionFor({\n source: 'http://example.com/www/js/two.js',\n line: 2,\n column: 10\n }));\n // { line: 2, column: 28 }\n\n smc.eachMapping(function (m) {\n // ...\n });\n\n### Generating a source map\n\nIn depth guide:\n[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)\n\n#### With SourceNode (high level API)\n\n function compile(ast) {\n switch (ast.type) {\n case 'BinaryExpression':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n [compile(ast.left), \" + \", compile(ast.right)]\n );\n case 'Literal':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n String(ast.value)\n );\n // ...\n default:\n throw new Error(\"Bad AST\");\n }\n }\n\n var ast = parse(\"40 + 2\", \"add.js\");\n console.log(compile(ast).toStringWithSourceMap({\n file: 'add.js'\n }));\n // { code: '40 + 2',\n // map: [object SourceMapGenerator] }\n\n#### With SourceMapGenerator (low level API)\n\n var map = new SourceMapGenerator({\n file: \"source-mapped.js\"\n });\n\n map.addMapping({\n generated: {\n line: 10,\n column: 35\n },\n source: \"foo.js\",\n original: {\n line: 33,\n column: 2\n },\n name: \"christopher\"\n });\n\n console.log(map.toString());\n // '{\"version\":3,\"file\":\"source-mapped.js\",\"sources\":[\"foo.js\"],\"names\":[\"christopher\"],\"mappings\":\";;;;;;;;;mCAgCEA\"}'\n\n## API\n\nGet a reference to the module:\n\n // NodeJS\n var sourceMap = require('source-map');\n\n // Browser builds\n var sourceMap = window.sourceMap;\n\n // Inside Firefox\n let sourceMap = {};\n Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);\n\n### SourceMapConsumer\n\nA SourceMapConsumer instance represents a parsed source map which we can query\nfor information about the original file positions by giving it a file position\nin the generated source.\n\n#### new SourceMapConsumer(rawSourceMap)\n\nThe only parameter is the raw source map (either as a string which can be\n`JSON.parse`'d, or an object). According to the spec, source maps have the\nfollowing attributes:\n\n* `version`: Which version of the source map spec this map is following.\n\n* `sources`: An array of URLs to the original source files.\n\n* `names`: An array of identifiers which can be referrenced by individual\n mappings.\n\n* `sourceRoot`: Optional. The URL root from which all sources are relative.\n\n* `sourcesContent`: Optional. An array of contents of the original source files.\n\n* `mappings`: A string of base64 VLQs which contain the actual mappings.\n\n* `file`: Optional. The generated filename this source map is associated with.\n\n#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)\n\nReturns the original source, line, and column information for the generated\nsource's line and column positions provided. The only argument is an object with\nthe following properties:\n\n* `line`: The line number in the generated source.\n\n* `column`: The column number in the generated source.\n\nand an object is returned with the following properties:\n\n* `source`: The original source file, or null if this information is not\n available.\n\n* `line`: The line number in the original source, or null if this information is\n not available.\n\n* `column`: The column number in the original source, or null or null if this\n information is not available.\n\n* `name`: The original identifier, or null if this information is not available.\n\n#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)\n\nReturns the generated line and column information for the original source,\nline, and column positions provided. The only argument is an object with\nthe following properties:\n\n* `source`: The filename of the original source.\n\n* `line`: The line number in the original source.\n\n* `column`: The column number in the original source.\n\nand an object is returned with the following properties:\n\n* `line`: The line number in the generated source, or null.\n\n* `column`: The column number in the generated source, or null.\n\n#### SourceMapConsumer.prototype.sourceContentFor(source)\n\nReturns the original source content for the source provided. The only\nargument is the URL of the original source file.\n\n#### SourceMapConsumer.prototype.eachMapping(callback, context, order)\n\nIterate over each mapping between an original source/line/column and a\ngenerated line/column in this source map.\n\n* `callback`: The function that is called with each mapping. Mappings have the\n form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,\n name }`\n\n* `context`: Optional. If specified, this object will be the value of `this`\n every time that `callback` is called.\n\n* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or\n `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over\n the mappings sorted by the generated file's line/column order or the\n original's source/line/column order, respectively. Defaults to\n `SourceMapConsumer.GENERATED_ORDER`.\n\n### SourceMapGenerator\n\nAn instance of the SourceMapGenerator represents a source map which is being\nbuilt incrementally.\n\n#### new SourceMapGenerator([startOfSourceMap])\n\nYou may pass an object with the following properties:\n\n* `file`: The filename of the generated source that this source map is\n associated with.\n\n* `sourceRoot`: A root for all relative URLs in this source map.\n\n#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)\n\nCreates a new SourceMapGenerator based on a SourceMapConsumer\n\n* `sourceMapConsumer` The SourceMap.\n\n#### SourceMapGenerator.prototype.addMapping(mapping)\n\nAdd a single mapping from original source line and column to the generated\nsource's line and column for this source map being created. The mapping object\nshould have the following properties:\n\n* `generated`: An object with the generated line and column positions.\n\n* `original`: An object with the original line and column positions.\n\n* `source`: The original source file (relative to the sourceRoot).\n\n* `name`: An optional original token name for this mapping.\n\n#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for an original source file.\n\n* `sourceFile` the URL of the original source file.\n\n* `sourceContent` the content of the source file.\n\n#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])\n\nApplies a SourceMap for a source file to the SourceMap.\nEach mapping to the supplied source file is rewritten using the\nsupplied SourceMap. Note: The resolution for the resulting mappings\nis the minimium of this map and the supplied map.\n\n* `sourceMapConsumer`: The SourceMap to be applied.\n\n* `sourceFile`: Optional. The filename of the source file.\n If omitted, sourceMapConsumer.file will be used, if it exists.\n Otherwise an error will be thrown.\n\n* `sourceMapPath`: Optional. The dirname of the path to the SourceMap\n to be applied. If relative, it is relative to the SourceMap.\n\n This parameter is needed when the two SourceMaps aren't in the same\n directory, and the SourceMap to be applied contains relative source\n paths. If so, those relative source paths need to be rewritten\n relative to the SourceMap.\n\n If omitted, it is assumed that both SourceMaps are in the same directory,\n thus not needing any rewriting. (Supplying `'.'` has the same effect.)\n\n#### SourceMapGenerator.prototype.toString()\n\nRenders the source map being generated to a string.\n\n### SourceNode\n\nSourceNodes provide a way to abstract over interpolating and/or concatenating\nsnippets of generated JavaScript source code, while maintaining the line and\ncolumn information associated between those snippets and the original source\ncode. This is useful as the final intermediate representation a compiler might\nuse before outputting the generated JS and source map.\n\n#### new SourceNode([line, column, source[, chunk[, name]]])\n\n* `line`: The original line number associated with this source node, or null if\n it isn't associated with an original line.\n\n* `column`: The original column number associated with this source node, or null\n if it isn't associated with an original column.\n\n* `source`: The original source's filename; null if no filename is provided.\n\n* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see\n below.\n\n* `name`: Optional. The original identifier.\n\n#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])\n\nCreates a SourceNode from generated code and a SourceMapConsumer.\n\n* `code`: The generated code\n\n* `sourceMapConsumer` The SourceMap for the generated code\n\n* `relativePath` The optional path that relative sources in `sourceMapConsumer`\n should be relative to.\n\n#### SourceNode.prototype.add(chunk)\n\nAdd a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.prepend(chunk)\n\nPrepend a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for a source file. This will be added to the\n`SourceMap` in the `sourcesContent` field.\n\n* `sourceFile`: The filename of the source file\n\n* `sourceContent`: The content of the source file\n\n#### SourceNode.prototype.walk(fn)\n\nWalk over the tree of JS snippets in this node and its children. The walking\nfunction is called once for each snippet of JS and is passed that snippet and\nthe its original associated source's line/column location.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.walkSourceContents(fn)\n\nWalk over the tree of SourceNodes. The walking function is called for each\nsource file content and is passed the filename and source content.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.join(sep)\n\nLike `Array.prototype.join` except for SourceNodes. Inserts the separator\nbetween each of this source node's children.\n\n* `sep`: The separator.\n\n#### SourceNode.prototype.replaceRight(pattern, replacement)\n\nCall `String.prototype.replace` on the very right-most source snippet. Useful\nfor trimming whitespace from the end of a source node, etc.\n\n* `pattern`: The pattern to replace.\n\n* `replacement`: The thing to replace the pattern with.\n\n#### SourceNode.prototype.toString()\n\nReturn the string representation of this source node. Walks over the tree and\nconcatenates all the various snippets together to one string.\n\n#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])\n\nReturns the string representation of this tree of source nodes, plus a\nSourceMapGenerator which contains all the mappings between the generated and\noriginal sources.\n\nThe arguments are the same as those to `new SourceMapGenerator`.\n\n## Tests\n\n[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)\n\nInstall NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.\n\nTo add new tests, create a new file named `test/test-.js`\nand export your test functions with names that start with \"test\", for example\n\n exports[\"test doing the foo bar\"] = function (assert, util) {\n ...\n };\n\nThe new test will be located automatically when you run the suite.\n\nThe `util` argument is the test utility module located at `test/source-map/util`.\n\nThe `assert` argument is a cut down version of node's assert module. You have\naccess to the following assertion functions:\n\n* `doesNotThrow`\n\n* `equal`\n\n* `ok`\n\n* `strictEqual`\n\n* `throws`\n\n(The reason for the restricted set of test functions is because we need the\ntests to run inside Firefox's test suite as well and so the assert module is\nshimmed in that environment. See `build/assert-shim.js`.)\n\n[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit\n[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap\n[Dryice]: https://github.com/mozilla/dryice\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mozilla/source-map/issues" + }, + "_id": "source-map@0.1.38", + "_from": "source-map@~0.1.7" +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/run-tests.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/run-tests.js new file mode 100644 index 000000000..64a7c3a3d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/run-tests.js @@ -0,0 +1,62 @@ +#!/usr/bin/env node +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var util = require('./source-map/util'); + +function run(tests) { + var total = 0; + var passed = 0; + + for (var i = 0; i < tests.length; i++) { + for (var k in tests[i].testCase) { + if (/^test/.test(k)) { + total++; + try { + tests[i].testCase[k](assert, util); + passed++; + } + catch (e) { + console.log('FAILED ' + tests[i].name + ': ' + k + '!'); + console.log(e.stack); + } + } + } + } + + console.log(''); + console.log(passed + ' / ' + total + ' tests passed.'); + console.log(''); + + return total - passed; +} + +function isTestFile(f) { + var testToRun = process.argv[2]; + return testToRun + ? path.basename(testToRun) === f + : /^test\-.*?\.js/.test(f); +} + +function toModule(f) { + return './source-map/' + f.replace(/\.js$/, ''); +} + +var requires = fs.readdirSync(path.join(__dirname, 'source-map')) + .filter(isTestFile) + .map(toModule); + +var code = run(requires.map(require).map(function (mod, i) { + return { + name: requires[i], + testCase: mod + }; +})); + +process.exit(code); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js new file mode 100644 index 000000000..3801233c0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js @@ -0,0 +1,26 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2012 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var sourceMap; + try { + sourceMap = require('../../lib/source-map'); + } catch (e) { + sourceMap = {}; + Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); + } + + exports['test that the api is properly exposed in the top level'] = function (assert, util) { + assert.equal(typeof sourceMap.SourceMapGenerator, "function"); + assert.equal(typeof sourceMap.SourceMapConsumer, "function"); + assert.equal(typeof sourceMap.SourceNode, "function"); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js new file mode 100644 index 000000000..b5797edd5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js @@ -0,0 +1,104 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var ArraySet = require('../../lib/source-map/array-set').ArraySet; + + function makeTestSet() { + var set = new ArraySet(); + for (var i = 0; i < 100; i++) { + set.add(String(i)); + } + return set; + } + + exports['test .has() membership'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.ok(set.has(String(i))); + } + }; + + exports['test .indexOf() elements'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.strictEqual(set.indexOf(String(i)), i); + } + }; + + exports['test .at() indexing'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.strictEqual(set.at(i), String(i)); + } + }; + + exports['test creating from an array'] = function (assert, util) { + var set = ArraySet.fromArray(['foo', 'bar', 'baz', 'quux', 'hasOwnProperty']); + + assert.ok(set.has('foo')); + assert.ok(set.has('bar')); + assert.ok(set.has('baz')); + assert.ok(set.has('quux')); + assert.ok(set.has('hasOwnProperty')); + + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.indexOf('bar'), 1); + assert.strictEqual(set.indexOf('baz'), 2); + assert.strictEqual(set.indexOf('quux'), 3); + + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'bar'); + assert.strictEqual(set.at(2), 'baz'); + assert.strictEqual(set.at(3), 'quux'); + }; + + exports['test that you can add __proto__; see github issue #30'] = function (assert, util) { + var set = new ArraySet(); + set.add('__proto__'); + assert.ok(set.has('__proto__')); + assert.strictEqual(set.at(0), '__proto__'); + assert.strictEqual(set.indexOf('__proto__'), 0); + }; + + exports['test .fromArray() with duplicates'] = function (assert, util) { + var set = ArraySet.fromArray(['foo', 'foo']); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 1); + + set = ArraySet.fromArray(['foo', 'foo'], true); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 2); + }; + + exports['test .add() with duplicates'] = function (assert, util) { + var set = new ArraySet(); + set.add('foo'); + + set.add('foo'); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 1); + + set.add('foo', true); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 2); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js new file mode 100644 index 000000000..653a874e9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js @@ -0,0 +1,24 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64VLQ = require('../../lib/source-map/base64-vlq'); + + exports['test normal encoding and decoding'] = function (assert, util) { + var result; + for (var i = -255; i < 256; i++) { + result = base64VLQ.decode(base64VLQ.encode(i)); + assert.ok(result); + assert.equal(result.value, i); + assert.equal(result.rest, ""); + } + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js new file mode 100644 index 000000000..ff3a24456 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js @@ -0,0 +1,35 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64 = require('../../lib/source-map/base64'); + + exports['test out of range encoding'] = function (assert, util) { + assert.throws(function () { + base64.encode(-1); + }); + assert.throws(function () { + base64.encode(64); + }); + }; + + exports['test out of range decoding'] = function (assert, util) { + assert.throws(function () { + base64.decode('='); + }); + }; + + exports['test normal encoding and decoding'] = function (assert, util) { + for (var i = 0; i < 64; i++) { + assert.equal(base64.decode(base64.encode(i)), i); + } + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js new file mode 100644 index 000000000..ee306830d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js @@ -0,0 +1,54 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var binarySearch = require('../../lib/source-map/binary-search'); + + function numberCompare(a, b) { + return a - b; + } + + exports['test too high'] = function (assert, util) { + var needle = 30; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.doesNotThrow(function () { + binarySearch.search(needle, haystack, numberCompare); + }); + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 20); + }; + + exports['test too low'] = function (assert, util) { + var needle = 1; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.doesNotThrow(function () { + binarySearch.search(needle, haystack, numberCompare); + }); + + assert.equal(binarySearch.search(needle, haystack, numberCompare), null); + }; + + exports['test exact search'] = function (assert, util) { + var needle = 4; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 4); + }; + + exports['test fuzzy search'] = function (assert, util) { + var needle = 19; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 18); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js new file mode 100644 index 000000000..26757b2d1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js @@ -0,0 +1,84 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + + exports['test eating our own dog food'] = function (assert, util) { + var smg = new SourceMapGenerator({ + file: 'testing.js', + sourceRoot: '/wu/tang' + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 1, column: 0 }, + generated: { line: 2, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 2, column: 0 }, + generated: { line: 3, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 3, column: 0 }, + generated: { line: 4, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 4, column: 0 }, + generated: { line: 5, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 5, column: 10 }, + generated: { line: 6, column: 12 } + }); + + var smc = new SourceMapConsumer(smg.toString()); + + // Exact + util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 0, null, smc, assert); + util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 0, null, smc, assert); + util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 0, null, smc, assert); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 0, null, smc, assert); + util.assertMapping(6, 12, '/wu/tang/gza.coffee', 5, 10, null, smc, assert); + + // Fuzzy + + // Generated to original + util.assertMapping(2, 0, null, null, null, null, smc, assert, true); + util.assertMapping(2, 9, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); + util.assertMapping(3, 0, null, null, null, null, smc, assert, true); + util.assertMapping(3, 9, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); + util.assertMapping(4, 0, null, null, null, null, smc, assert, true); + util.assertMapping(4, 9, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); + util.assertMapping(5, 0, null, null, null, null, smc, assert, true); + util.assertMapping(5, 9, '/wu/tang/gza.coffee', 4, 0, null, smc, assert, true); + util.assertMapping(6, 0, null, null, null, null, smc, assert, true); + util.assertMapping(6, 9, null, null, null, null, smc, assert, true); + util.assertMapping(6, 13, '/wu/tang/gza.coffee', 5, 10, null, smc, assert, true); + + // Original to generated + util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 1, null, smc, assert, null, true); + util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 3, null, smc, assert, null, true); + util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 6, null, smc, assert, null, true); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 9, null, smc, assert, null, true); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 5, 9, null, smc, assert, null, true); + util.assertMapping(6, 12, '/wu/tang/gza.coffee', 6, 19, null, smc, assert, null, true); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js new file mode 100644 index 000000000..a4c66590a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js @@ -0,0 +1,531 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + + exports['test that we can instantiate with a string or an object'] = function (assert, util) { + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(util.testMap); + }); + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(JSON.stringify(util.testMap)); + }); + }; + + exports['test that the `sources` field has the original sources'] = function (assert, util) { + var map; + var sources; + + map = new SourceMapConsumer(util.testMap); + sources = map.sources; + assert.equal(sources[0], '/the/root/one.js'); + assert.equal(sources[1], '/the/root/two.js'); + assert.equal(sources.length, 2); + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + sources = map.sources; + assert.equal(sources[0], 'one.js'); + assert.equal(sources[1], 'two.js'); + assert.equal(sources.length, 2); + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + sources = map.sources; + assert.equal(sources[0], 'one.js'); + assert.equal(sources[1], 'two.js'); + assert.equal(sources.length, 2); + }; + + exports['test that the source root is reflected in a mapping\'s source field'] = function (assert, util) { + var map; + var mapping; + + map = new SourceMapConsumer(util.testMap); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, '/the/root/two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, '/the/root/one.js'); + + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, 'two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, 'one.js'); + + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, 'two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, 'one.js'); + }; + + exports['test mapping tokens back exactly'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + + util.assertMapping(1, 1, '/the/root/one.js', 1, 1, null, map, assert); + util.assertMapping(1, 5, '/the/root/one.js', 1, 5, null, map, assert); + util.assertMapping(1, 9, '/the/root/one.js', 1, 11, null, map, assert); + util.assertMapping(1, 18, '/the/root/one.js', 1, 21, 'bar', map, assert); + util.assertMapping(1, 21, '/the/root/one.js', 2, 3, null, map, assert); + util.assertMapping(1, 28, '/the/root/one.js', 2, 10, 'baz', map, assert); + util.assertMapping(1, 32, '/the/root/one.js', 2, 14, 'bar', map, assert); + + util.assertMapping(2, 1, '/the/root/two.js', 1, 1, null, map, assert); + util.assertMapping(2, 5, '/the/root/two.js', 1, 5, null, map, assert); + util.assertMapping(2, 9, '/the/root/two.js', 1, 11, null, map, assert); + util.assertMapping(2, 18, '/the/root/two.js', 1, 21, 'n', map, assert); + util.assertMapping(2, 21, '/the/root/two.js', 2, 3, null, map, assert); + util.assertMapping(2, 28, '/the/root/two.js', 2, 10, 'n', map, assert); + }; + + exports['test mapping tokens fuzzy'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + + // Finding original positions + util.assertMapping(1, 20, '/the/root/one.js', 1, 21, 'bar', map, assert, true); + util.assertMapping(1, 30, '/the/root/one.js', 2, 10, 'baz', map, assert, true); + util.assertMapping(2, 12, '/the/root/two.js', 1, 11, null, map, assert, true); + + // Finding generated positions + util.assertMapping(1, 18, '/the/root/one.js', 1, 22, 'bar', map, assert, null, true); + util.assertMapping(1, 28, '/the/root/one.js', 2, 13, 'baz', map, assert, null, true); + util.assertMapping(2, 9, '/the/root/two.js', 1, 16, null, map, assert, null, true); + }; + + exports['test mappings and end of lines'] = function (assert, util) { + var smg = new SourceMapGenerator({ + file: 'foo.js' + }); + smg.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 1, column: 1 }, + source: 'bar.js' + }); + smg.addMapping({ + original: { line: 2, column: 2 }, + generated: { line: 2, column: 2 }, + source: 'bar.js' + }); + + var map = SourceMapConsumer.fromSourceMap(smg); + + // When finding original positions, mappings end at the end of the line. + util.assertMapping(2, 1, null, null, null, null, map, assert, true) + + // When finding generated positions, mappings do not end at the end of the line. + util.assertMapping(1, 1, 'bar.js', 2, 1, null, map, assert, null, true); + }; + + exports['test creating source map consumers with )]}\' prefix'] = function (assert, util) { + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(")]}'" + JSON.stringify(util.testMap)); + }); + }; + + exports['test eachMapping'] = function (assert, util) { + var map; + + map = new SourceMapConsumer(util.testMap); + var previousLine = -Infinity; + var previousColumn = -Infinity; + map.eachMapping(function (mapping) { + assert.ok(mapping.generatedLine >= previousLine); + + assert.ok(mapping.source === '/the/root/one.js' || mapping.source === '/the/root/two.js'); + + if (mapping.generatedLine === previousLine) { + assert.ok(mapping.generatedColumn >= previousColumn); + previousColumn = mapping.generatedColumn; + } + else { + previousLine = mapping.generatedLine; + previousColumn = -Infinity; + } + }); + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + map.eachMapping(function (mapping) { + assert.ok(mapping.source === 'one.js' || mapping.source === 'two.js'); + }); + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + map.eachMapping(function (mapping) { + assert.ok(mapping.source === 'one.js' || mapping.source === 'two.js'); + }); + }; + + exports['test iterating over mappings in a different order'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + var previousLine = -Infinity; + var previousColumn = -Infinity; + var previousSource = ""; + map.eachMapping(function (mapping) { + assert.ok(mapping.source >= previousSource); + + if (mapping.source === previousSource) { + assert.ok(mapping.originalLine >= previousLine); + + if (mapping.originalLine === previousLine) { + assert.ok(mapping.originalColumn >= previousColumn); + previousColumn = mapping.originalColumn; + } + else { + previousLine = mapping.originalLine; + previousColumn = -Infinity; + } + } + else { + previousSource = mapping.source; + previousLine = -Infinity; + previousColumn = -Infinity; + } + }, null, SourceMapConsumer.ORIGINAL_ORDER); + }; + + exports['test that we can set the context for `this` in eachMapping'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + var context = {}; + map.eachMapping(function () { + assert.equal(this, context); + }, context); + }; + + exports['test that the `sourcesContent` field has the original sources'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMapWithSourcesContent); + var sourcesContent = map.sourcesContent; + + assert.equal(sourcesContent[0], ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(sourcesContent[1], ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.equal(sourcesContent.length, 2); + }; + + exports['test that we can get the original sources for the sources'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMapWithSourcesContent); + var sources = map.sources; + + assert.equal(map.sourceContentFor(sources[0]), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(map.sourceContentFor(sources[1]), ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.equal(map.sourceContentFor("one.js"), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(map.sourceContentFor("two.js"), ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.throws(function () { + map.sourceContentFor(""); + }, Error); + assert.throws(function () { + map.sourceContentFor("/the/root/three.js"); + }, Error); + assert.throws(function () { + map.sourceContentFor("three.js"); + }, Error); + }; + + exports['test sourceRoot + generatedPositionFor'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'foo/bar', + file: 'baz.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bang.coffee' + }); + map.addMapping({ + original: { line: 5, column: 5 }, + generated: { line: 6, column: 6 }, + source: 'bang.coffee' + }); + map = new SourceMapConsumer(map.toString()); + + // Should handle without sourceRoot. + var pos = map.generatedPositionFor({ + line: 1, + column: 1, + source: 'bang.coffee' + }); + + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + + // Should handle with sourceRoot. + var pos = map.generatedPositionFor({ + line: 1, + column: 1, + source: 'foo/bar/bang.coffee' + }); + + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + }; + + exports['test sourceRoot + originalPositionFor'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'foo/bar', + file: 'baz.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bang.coffee' + }); + map = new SourceMapConsumer(map.toString()); + + var pos = map.originalPositionFor({ + line: 2, + column: 2, + }); + + // Should always have the prepended source root + assert.equal(pos.source, 'foo/bar/bang.coffee'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + }; + + exports['test github issue #56'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://', + file: 'www.example.com/foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'www.example.com/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1); + assert.equal(sources[0], 'http://www.example.com/original.js'); + }; + + exports['test github issue #43'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://example.com', + file: 'foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'http://cdn.example.com/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1, + 'Should only be one source.'); + assert.equal(sources[0], 'http://cdn.example.com/original.js', + 'Should not be joined with the sourceRoot.'); + }; + + exports['test absolute path, but same host sources'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://example.com/foo/bar', + file: 'foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: '/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1, + 'Should only be one source.'); + assert.equal(sources[0], 'http://example.com/original.js', + 'Source should be relative the host of the source root.'); + }; + + exports['test github issue #64'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sourceRoot": "http://example.com/", + "sources": ["/a"], + "names": [], + "mappings": "AACA", + "sourcesContent": ["foo"] + }); + + assert.equal(map.sourceContentFor("a"), "foo"); + assert.equal(map.sourceContentFor("/a"), "foo"); + }; + + exports['test bug 885597'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sourceRoot": "file:///Users/AlGore/Invented/The/Internet/", + "sources": ["/a"], + "names": [], + "mappings": "AACA", + "sourcesContent": ["foo"] + }); + + var s = map.sources[0]; + assert.equal(map.sourceContentFor(s), "foo"); + }; + + exports['test github issue #72, duplicate sources'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sources": ["source1.js", "source1.js", "source3.js"], + "names": [], + "mappings": ";EAAC;;IAEE;;MEEE", + "sourceRoot": "http://example.com" + }); + + var pos = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.source, 'http://example.com/source1.js'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + + var pos = map.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.source, 'http://example.com/source1.js'); + assert.equal(pos.line, 3); + assert.equal(pos.column, 3); + + var pos = map.originalPositionFor({ + line: 6, + column: 6 + }); + assert.equal(pos.source, 'http://example.com/source3.js'); + assert.equal(pos.line, 5); + assert.equal(pos.column, 5); + }; + + exports['test github issue #72, duplicate names'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sources": ["source.js"], + "names": ["name1", "name1", "name3"], + "mappings": ";EAACA;;IAEEA;;MAEEE", + "sourceRoot": "http://example.com" + }); + + var pos = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.name, 'name1'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + + var pos = map.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.name, 'name1'); + assert.equal(pos.line, 3); + assert.equal(pos.column, 3); + + var pos = map.originalPositionFor({ + line: 6, + column: 6 + }); + assert.equal(pos.name, 'name3'); + assert.equal(pos.line, 5); + assert.equal(pos.column, 5); + }; + + exports['test SourceMapConsumer.fromSourceMap'] = function (assert, util) { + var smg = new SourceMapGenerator({ + sourceRoot: 'http://example.com/', + file: 'foo.js' + }); + smg.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bar.js' + }); + smg.addMapping({ + original: { line: 2, column: 2 }, + generated: { line: 4, column: 4 }, + source: 'baz.js', + name: 'dirtMcGirt' + }); + smg.setSourceContent('baz.js', 'baz.js content'); + + var smc = SourceMapConsumer.fromSourceMap(smg); + assert.equal(smc.file, 'foo.js'); + assert.equal(smc.sourceRoot, 'http://example.com/'); + assert.equal(smc.sources.length, 2); + assert.equal(smc.sources[0], 'http://example.com/bar.js'); + assert.equal(smc.sources[1], 'http://example.com/baz.js'); + assert.equal(smc.sourceContentFor('baz.js'), 'baz.js content'); + + var pos = smc.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + assert.equal(pos.source, 'http://example.com/bar.js'); + assert.equal(pos.name, null); + + pos = smc.generatedPositionFor({ + line: 1, + column: 1, + source: 'http://example.com/bar.js' + }); + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + + pos = smc.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + assert.equal(pos.source, 'http://example.com/baz.js'); + assert.equal(pos.name, 'dirtMcGirt'); + + pos = smc.generatedPositionFor({ + line: 2, + column: 2, + source: 'http://example.com/baz.js' + }); + assert.equal(pos.line, 4); + assert.equal(pos.column, 4); + }; +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js new file mode 100644 index 000000000..b2aaa53a2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js @@ -0,0 +1,595 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceNode = require('../../lib/source-map/source-node').SourceNode; + var util = require('./util'); + + exports['test some simple stuff'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'foo.js', + sourceRoot: '.' + }); + assert.ok(true); + + var map = new SourceMapGenerator().toJSON(); + assert.ok(!('file' in map)); + assert.ok(!('sourceRoot' in map)); + }; + + exports['test JSON serialization'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'foo.js', + sourceRoot: '.' + }); + assert.equal(map.toString(), JSON.stringify(map)); + }; + + exports['test adding mappings (case 1)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 } + }); + }); + }; + + exports['test adding mappings (case 2)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 } + }); + }); + }; + + exports['test adding mappings (case 3)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 }, + name: 'someToken' + }); + }); + }; + + exports['test adding mappings (invalid)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + // Not enough info. + assert.throws(function () { + map.addMapping({}); + }); + + // Original file position, but no source. + assert.throws(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 } + }); + }); + }; + + exports['test that the correct mappings are being generated'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'min.js', + sourceRoot: '/the/root' + }); + + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 5 }, + original: { line: 1, column: 5 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 9 }, + original: { line: 1, column: 11 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 18 }, + original: { line: 1, column: 21 }, + source: 'one.js', + name: 'bar' + }); + map.addMapping({ + generated: { line: 1, column: 21 }, + original: { line: 2, column: 3 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 28 }, + original: { line: 2, column: 10 }, + source: 'one.js', + name: 'baz' + }); + map.addMapping({ + generated: { line: 1, column: 32 }, + original: { line: 2, column: 14 }, + source: 'one.js', + name: 'bar' + }); + + map.addMapping({ + generated: { line: 2, column: 1 }, + original: { line: 1, column: 1 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 5 }, + original: { line: 1, column: 5 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 9 }, + original: { line: 1, column: 11 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 18 }, + original: { line: 1, column: 21 }, + source: 'two.js', + name: 'n' + }); + map.addMapping({ + generated: { line: 2, column: 21 }, + original: { line: 2, column: 3 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 28 }, + original: { line: 2, column: 10 }, + source: 'two.js', + name: 'n' + }); + + map = JSON.parse(map.toString()); + + util.assertEqualMaps(assert, map, util.testMap); + }; + + exports['test that adding a mapping with an empty string name does not break generation'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 }, + name: '' + }); + + assert.doesNotThrow(function () { + JSON.parse(map.toString()); + }); + }; + + exports['test that source content can be set'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'min.js', + sourceRoot: '/the/root' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 2, column: 1 }, + original: { line: 1, column: 1 }, + source: 'two.js' + }); + map.setSourceContent('one.js', 'one file content'); + + map = JSON.parse(map.toString()); + assert.equal(map.sources[0], 'one.js'); + assert.equal(map.sources[1], 'two.js'); + assert.equal(map.sourcesContent[0], 'one file content'); + assert.equal(map.sourcesContent[1], null); + }; + + exports['test .fromSourceMap'] = function (assert, util) { + var map = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(util.testMap)); + util.assertEqualMaps(assert, map.toJSON(), util.testMap); + }; + + exports['test .fromSourceMap with sourcesContent'] = function (assert, util) { + var map = SourceMapGenerator.fromSourceMap( + new SourceMapConsumer(util.testMapWithSourcesContent)); + util.assertEqualMaps(assert, map.toJSON(), util.testMapWithSourcesContent); + }; + + exports['test applySourceMap'] = function (assert, util) { + var node = new SourceNode(null, null, null, [ + new SourceNode(2, 0, 'fileX', 'lineX2\n'), + 'genA1\n', + new SourceNode(2, 0, 'fileY', 'lineY2\n'), + 'genA2\n', + new SourceNode(1, 0, 'fileX', 'lineX1\n'), + 'genA3\n', + new SourceNode(1, 0, 'fileY', 'lineY1\n') + ]); + var mapStep1 = node.toStringWithSourceMap({ + file: 'fileA' + }).map; + mapStep1.setSourceContent('fileX', 'lineX1\nlineX2\n'); + mapStep1 = mapStep1.toJSON(); + + node = new SourceNode(null, null, null, [ + 'gen1\n', + new SourceNode(1, 0, 'fileA', 'lineA1\n'), + new SourceNode(2, 0, 'fileA', 'lineA2\n'), + new SourceNode(3, 0, 'fileA', 'lineA3\n'), + new SourceNode(4, 0, 'fileA', 'lineA4\n'), + new SourceNode(1, 0, 'fileB', 'lineB1\n'), + new SourceNode(2, 0, 'fileB', 'lineB2\n'), + 'gen2\n' + ]); + var mapStep2 = node.toStringWithSourceMap({ + file: 'fileGen' + }).map; + mapStep2.setSourceContent('fileB', 'lineB1\nlineB2\n'); + mapStep2 = mapStep2.toJSON(); + + node = new SourceNode(null, null, null, [ + 'gen1\n', + new SourceNode(2, 0, 'fileX', 'lineA1\n'), + new SourceNode(2, 0, 'fileA', 'lineA2\n'), + new SourceNode(2, 0, 'fileY', 'lineA3\n'), + new SourceNode(4, 0, 'fileA', 'lineA4\n'), + new SourceNode(1, 0, 'fileB', 'lineB1\n'), + new SourceNode(2, 0, 'fileB', 'lineB2\n'), + 'gen2\n' + ]); + var expectedMap = node.toStringWithSourceMap({ + file: 'fileGen' + }).map; + expectedMap.setSourceContent('fileX', 'lineX1\nlineX2\n'); + expectedMap.setSourceContent('fileB', 'lineB1\nlineB2\n'); + expectedMap = expectedMap.toJSON(); + + // apply source map "mapStep1" to "mapStep2" + var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapStep2)); + generator.applySourceMap(new SourceMapConsumer(mapStep1)); + var actualMap = generator.toJSON(); + + util.assertEqualMaps(assert, actualMap, expectedMap); + }; + + exports['test applySourceMap throws when file is missing'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + var map2 = new SourceMapGenerator(); + assert.throws(function() { + map.applySourceMap(new SourceMapConsumer(map2.toJSON())); + }); + }; + + exports['test the two additional parameters of applySourceMap'] = function (assert, util) { + // Assume the following directory structure: + // + // http://foo.org/ + // bar.coffee + // app/ + // coffee/ + // foo.coffee + // temp/ + // bundle.js + // temp_maps/ + // bundle.js.map + // public/ + // bundle.min.js + // bundle.min.js.map + // + // http://www.example.com/ + // baz.coffee + + var bundleMap = new SourceMapGenerator({ + file: 'bundle.js' + }); + bundleMap.addMapping({ + generated: { line: 3, column: 3 }, + original: { line: 2, column: 2 }, + source: '../../coffee/foo.coffee' + }); + bundleMap.setSourceContent('../../coffee/foo.coffee', 'foo coffee'); + bundleMap.addMapping({ + generated: { line: 13, column: 13 }, + original: { line: 12, column: 12 }, + source: '/bar.coffee' + }); + bundleMap.setSourceContent('/bar.coffee', 'bar coffee'); + bundleMap.addMapping({ + generated: { line: 23, column: 23 }, + original: { line: 22, column: 22 }, + source: 'http://www.example.com/baz.coffee' + }); + bundleMap.setSourceContent( + 'http://www.example.com/baz.coffee', + 'baz coffee' + ); + bundleMap = new SourceMapConsumer(bundleMap.toJSON()); + + var minifiedMap = new SourceMapGenerator({ + file: 'bundle.min.js', + sourceRoot: '..' + }); + minifiedMap.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 3, column: 3 }, + source: 'temp/bundle.js' + }); + minifiedMap.addMapping({ + generated: { line: 11, column: 11 }, + original: { line: 13, column: 13 }, + source: 'temp/bundle.js' + }); + minifiedMap.addMapping({ + generated: { line: 21, column: 21 }, + original: { line: 23, column: 23 }, + source: 'temp/bundle.js' + }); + minifiedMap = new SourceMapConsumer(minifiedMap.toJSON()); + + var expectedMap = function (sources) { + var map = new SourceMapGenerator({ + file: 'bundle.min.js', + sourceRoot: '..' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 2, column: 2 }, + source: sources[0] + }); + map.setSourceContent(sources[0], 'foo coffee'); + map.addMapping({ + generated: { line: 11, column: 11 }, + original: { line: 12, column: 12 }, + source: sources[1] + }); + map.setSourceContent(sources[1], 'bar coffee'); + map.addMapping({ + generated: { line: 21, column: 21 }, + original: { line: 22, column: 22 }, + source: sources[2] + }); + map.setSourceContent(sources[2], 'baz coffee'); + return map.toJSON(); + } + + var actualMap = function (aSourceMapPath) { + var map = SourceMapGenerator.fromSourceMap(minifiedMap); + // Note that relying on `bundleMap.file` (which is simply 'bundle.js') + // instead of supplying the second parameter wouldn't work here. + map.applySourceMap(bundleMap, '../temp/bundle.js', aSourceMapPath); + return map.toJSON(); + } + + util.assertEqualMaps(assert, actualMap('../temp/temp_maps'), expectedMap([ + 'coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('/app/temp/temp_maps'), expectedMap([ + '/app/coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('http://foo.org/app/temp/temp_maps'), expectedMap([ + 'http://foo.org/app/coffee/foo.coffee', + 'http://foo.org/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + // If the third parameter is omitted or set to the current working + // directory we get incorrect source paths: + + util.assertEqualMaps(assert, actualMap(), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap(''), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('.'), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('./'), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + }; + + exports['test sorting with duplicate generated mappings'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + map.addMapping({ + generated: { line: 3, column: 0 }, + original: { line: 2, column: 0 }, + source: 'a.js' + }); + map.addMapping({ + generated: { line: 2, column: 0 } + }); + map.addMapping({ + generated: { line: 2, column: 0 } + }); + map.addMapping({ + generated: { line: 1, column: 0 }, + original: { line: 1, column: 0 }, + source: 'a.js' + }); + + util.assertEqualMaps(assert, map.toJSON(), { + version: 3, + file: 'test.js', + sources: ['a.js'], + names: [], + mappings: 'AAAA;A;AACA' + }); + }; + + exports['test ignore duplicate mappings.'] = function (assert, util) { + var init = { file: 'min.js', sourceRoot: '/the/root' }; + var map1, map2; + + // null original source location + var nullMapping1 = { + generated: { line: 1, column: 0 } + }; + var nullMapping2 = { + generated: { line: 2, column: 2 } + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(nullMapping1); + map1.addMapping(nullMapping1); + + map2.addMapping(nullMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(nullMapping2); + map1.addMapping(nullMapping1); + + map2.addMapping(nullMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + // original source location + var srcMapping1 = { + generated: { line: 1, column: 0 }, + original: { line: 11, column: 0 }, + source: 'srcMapping1.js' + }; + var srcMapping2 = { + generated: { line: 2, column: 2 }, + original: { line: 11, column: 0 }, + source: 'srcMapping2.js' + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(srcMapping1); + map1.addMapping(srcMapping1); + + map2.addMapping(srcMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(srcMapping2); + map1.addMapping(srcMapping1); + + map2.addMapping(srcMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + // full original source and name information + var fullMapping1 = { + generated: { line: 1, column: 0 }, + original: { line: 11, column: 0 }, + source: 'fullMapping1.js', + name: 'fullMapping1' + }; + var fullMapping2 = { + generated: { line: 2, column: 2 }, + original: { line: 11, column: 0 }, + source: 'fullMapping2.js', + name: 'fullMapping2' + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(fullMapping1); + map1.addMapping(fullMapping1); + + map2.addMapping(fullMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(fullMapping2); + map1.addMapping(fullMapping1); + + map2.addMapping(fullMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + }; + + exports['test github issue #72, check for duplicate names or sources'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 2, column: 2 }, + source: 'a.js', + name: 'foo' + }); + map.addMapping({ + generated: { line: 3, column: 3 }, + original: { line: 4, column: 4 }, + source: 'a.js', + name: 'foo' + }); + util.assertEqualMaps(assert, map.toJSON(), { + version: 3, + file: 'test.js', + sources: ['a.js'], + names: ['foo'], + mappings: 'CACEA;;GAEEA' + }); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js new file mode 100644 index 000000000..139af4e44 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js @@ -0,0 +1,612 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceNode = require('../../lib/source-map/source-node').SourceNode; + + function forEachNewline(fn) { + return function (assert, util) { + ['\n', '\r\n'].forEach(fn.bind(null, assert, util)); + } + } + + exports['test .add()'] = function (assert, util) { + var node = new SourceNode(null, null, null); + + // Adding a string works. + node.add('function noop() {}'); + + // Adding another source node works. + node.add(new SourceNode(null, null, null)); + + // Adding an array works. + node.add(['function foo() {', + new SourceNode(null, null, null, + 'return 10;'), + '}']); + + // Adding other stuff doesn't. + assert.throws(function () { + node.add({}); + }); + assert.throws(function () { + node.add(function () {}); + }); + }; + + exports['test .prepend()'] = function (assert, util) { + var node = new SourceNode(null, null, null); + + // Prepending a string works. + node.prepend('function noop() {}'); + assert.equal(node.children[0], 'function noop() {}'); + assert.equal(node.children.length, 1); + + // Prepending another source node works. + node.prepend(new SourceNode(null, null, null)); + assert.equal(node.children[0], ''); + assert.equal(node.children[1], 'function noop() {}'); + assert.equal(node.children.length, 2); + + // Prepending an array works. + node.prepend(['function foo() {', + new SourceNode(null, null, null, + 'return 10;'), + '}']); + assert.equal(node.children[0], 'function foo() {'); + assert.equal(node.children[1], 'return 10;'); + assert.equal(node.children[2], '}'); + assert.equal(node.children[3], ''); + assert.equal(node.children[4], 'function noop() {}'); + assert.equal(node.children.length, 5); + + // Prepending other stuff doesn't. + assert.throws(function () { + node.prepend({}); + }); + assert.throws(function () { + node.prepend(function () {}); + }); + }; + + exports['test .toString()'] = function (assert, util) { + assert.equal((new SourceNode(null, null, null, + ['function foo() {', + new SourceNode(null, null, null, 'return 10;'), + '}'])).toString(), + 'function foo() {return 10;}'); + }; + + exports['test .join()'] = function (assert, util) { + assert.equal((new SourceNode(null, null, null, + ['a', 'b', 'c', 'd'])).join(', ').toString(), + 'a, b, c, d'); + }; + + exports['test .walk()'] = function (assert, util) { + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', new SourceNode(1, 0, 'a.js', ['someCall()']), ';\n', + ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n', + '}());']); + var expected = [ + { str: '(function () {\n', source: null, line: null, column: null }, + { str: ' ', source: null, line: null, column: null }, + { str: 'someCall()', source: 'a.js', line: 1, column: 0 }, + { str: ';\n', source: null, line: null, column: null }, + { str: ' ', source: null, line: null, column: null }, + { str: 'if (foo) bar()', source: 'b.js', line: 2, column: 0 }, + { str: ';\n', source: null, line: null, column: null }, + { str: '}());', source: null, line: null, column: null }, + ]; + var i = 0; + node.walk(function (chunk, loc) { + assert.equal(expected[i].str, chunk); + assert.equal(expected[i].source, loc.source); + assert.equal(expected[i].line, loc.line); + assert.equal(expected[i].column, loc.column); + i++; + }); + }; + + exports['test .replaceRight'] = function (assert, util) { + var node; + + // Not nested + node = new SourceNode(null, null, null, 'hello world'); + node.replaceRight(/world/, 'universe'); + assert.equal(node.toString(), 'hello universe'); + + // Nested + node = new SourceNode(null, null, null, + [new SourceNode(null, null, null, 'hey sexy mama, '), + new SourceNode(null, null, null, 'want to kill all humans?')]); + node.replaceRight(/kill all humans/, 'watch Futurama'); + assert.equal(node.toString(), 'hey sexy mama, want to watch Futurama?'); + }; + + exports['test .toStringWithSourceMap()'] = forEachNewline(function (assert, util, nl) { + var node = new SourceNode(null, null, null, + ['(function () {' + nl, + ' ', + new SourceNode(1, 0, 'a.js', 'someCall', 'originalCall'), + new SourceNode(1, 8, 'a.js', '()'), + ';' + nl, + ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';' + nl, + '}());']); + var result = node.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(result.code, [ + '(function () {', + ' someCall();', + ' if (foo) bar();', + '}());' + ].join(nl)); + + var map = result.map; + var mapWithoutOptions = node.toStringWithSourceMap().map; + + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + assert.ok(mapWithoutOptions instanceof SourceMapGenerator, 'mapWithoutOptions instanceof SourceMapGenerator'); + assert.ok(!('file' in mapWithoutOptions)); + mapWithoutOptions._file = 'foo.js'; + util.assertEqualMaps(assert, map.toJSON(), mapWithoutOptions.toJSON()); + + map = new SourceMapConsumer(map.toString()); + + var actual; + + actual = map.originalPositionFor({ + line: 1, + column: 4 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + + actual = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(actual.source, 'a.js'); + assert.equal(actual.line, 1); + assert.equal(actual.column, 0); + assert.equal(actual.name, 'originalCall'); + + actual = map.originalPositionFor({ + line: 3, + column: 2 + }); + assert.equal(actual.source, 'b.js'); + assert.equal(actual.line, 2); + assert.equal(actual.column, 0); + + actual = map.originalPositionFor({ + line: 3, + column: 16 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + + actual = map.originalPositionFor({ + line: 4, + column: 2 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + }); + + exports['test .fromStringWithSourceMap()'] = forEachNewline(function (assert, util, nl) { + var testCode = util.testGeneratedCode.replace(/\n/g, nl); + var node = SourceNode.fromStringWithSourceMap( + testCode, + new SourceMapConsumer(util.testMap)); + + var result = node.toStringWithSourceMap({ + file: 'min.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, testCode); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + assert.equal(map.version, util.testMap.version); + assert.equal(map.file, util.testMap.file); + assert.equal(map.mappings, util.testMap.mappings); + }); + + exports['test .fromStringWithSourceMap() empty map'] = forEachNewline(function (assert, util, nl) { + var node = SourceNode.fromStringWithSourceMap( + util.testGeneratedCode.replace(/\n/g, nl), + new SourceMapConsumer(util.emptyMap)); + var result = node.toStringWithSourceMap({ + file: 'min.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, util.testGeneratedCode.replace(/\n/g, nl)); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + assert.equal(map.version, util.emptyMap.version); + assert.equal(map.file, util.emptyMap.file); + assert.equal(map.mappings.length, util.emptyMap.mappings.length); + assert.equal(map.mappings, util.emptyMap.mappings); + }); + + exports['test .fromStringWithSourceMap() complex version'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + "(function() {" + nl, + " var Test = {};" + nl, + " ", new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };" + nl), + " ", new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), nl, + "}());" + nl, + "/* Generated Source */"]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + var node = SourceNode.fromStringWithSourceMap( + input.code, + new SourceMapConsumer(input.map.toString())); + + var result = node.toStringWithSourceMap({ + file: 'foo.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, input.code); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + var inputMap = input.map.toJSON(); + util.assertEqualMaps(assert, map, inputMap); + }); + + exports['test .fromStringWithSourceMap() third argument'] = function (assert, util) { + // Assume the following directory structure: + // + // http://foo.org/ + // bar.coffee + // app/ + // coffee/ + // foo.coffee + // coffeeBundle.js # Made from {foo,bar,baz}.coffee + // maps/ + // coffeeBundle.js.map + // js/ + // foo.js + // public/ + // app.js # Made from {foo,coffeeBundle}.js + // app.js.map + // + // http://www.example.com/ + // baz.coffee + + var coffeeBundle = new SourceNode(1, 0, 'foo.coffee', 'foo(coffee);\n'); + coffeeBundle.setSourceContent('foo.coffee', 'foo coffee'); + coffeeBundle.add(new SourceNode(2, 0, '/bar.coffee', 'bar(coffee);\n')); + coffeeBundle.add(new SourceNode(3, 0, 'http://www.example.com/baz.coffee', 'baz(coffee);')); + coffeeBundle = coffeeBundle.toStringWithSourceMap({ + file: 'foo.js', + sourceRoot: '..' + }); + + var foo = new SourceNode(1, 0, 'foo.js', 'foo(js);'); + + var test = function(relativePath, expectedSources) { + var app = new SourceNode(); + app.add(SourceNode.fromStringWithSourceMap( + coffeeBundle.code, + new SourceMapConsumer(coffeeBundle.map.toString()), + relativePath)); + app.add(foo); + var i = 0; + app.walk(function (chunk, loc) { + assert.equal(loc.source, expectedSources[i]); + i++; + }); + app.walkSourceContents(function (sourceFile, sourceContent) { + assert.equal(sourceFile, expectedSources[0]); + assert.equal(sourceContent, 'foo coffee'); + }) + }; + + test('../coffee/maps', [ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + // If the third parameter is omitted or set to the current working + // directory we get incorrect source paths: + + test(undefined, [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('.', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('./', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + }; + + exports['test .toStringWithSourceMap() merging duplicate mappings'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + new SourceNode(1, 0, "a.js", "(function"), + new SourceNode(1, 0, "a.js", "() {" + nl), + " ", + new SourceNode(1, 0, "a.js", "var Test = "), + new SourceNode(1, 0, "b.js", "{};" + nl), + new SourceNode(2, 0, "b.js", "Test"), + new SourceNode(2, 0, "b.js", ".A", "A"), + new SourceNode(2, 20, "b.js", " = { value: ", "A"), + "1234", + new SourceNode(2, 40, "b.js", " };" + nl, "A"), + "}());" + nl, + "/* Generated Source */" + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "(function() {", + " var Test = {};", + "Test.A = { value: 1234 };", + "}());", + "/* Generated Source */" + ].join(nl)) + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 1, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + // Here is no need for a empty mapping, + // because mappings ends at eol + correctMap.addMapping({ + generated: { line: 2, column: 2 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 2, column: 13 }, + source: 'b.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'b.js', + original: { line: 2, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 4 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 6 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 20 } + }); + // This empty mapping is required, + // because there is a hole in the middle of the line + correctMap.addMapping({ + generated: { line: 3, column: 18 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 22 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 40 } + }); + // Here is no need for a empty mapping, + // because mappings ends at eol + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test .toStringWithSourceMap() multi-line SourceNodes'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + new SourceNode(1, 0, "a.js", "(function() {" + nl + "var nextLine = 1;" + nl + "anotherLine();" + nl), + new SourceNode(2, 2, "b.js", "Test.call(this, 123);" + nl), + new SourceNode(2, 2, "b.js", "this['stuff'] = 'v';" + nl), + new SourceNode(2, 2, "b.js", "anotherLine();" + nl), + "/*" + nl + "Generated" + nl + "Source" + nl + "*/" + nl, + new SourceNode(3, 4, "c.js", "anotherLine();" + nl), + "/*" + nl + "Generated" + nl + "Source" + nl + "*/" + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "(function() {", + "var nextLine = 1;", + "anotherLine();", + "Test.call(this, 123);", + "this['stuff'] = 'v';", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/" + ].join(nl)); + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 1, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 2, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 4, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 5, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 6, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 11, column: 0 }, + source: 'c.js', + original: { line: 3, column: 4 } + }); + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test .toStringWithSourceMap() with empty string'] = function (assert, util) { + var node = new SourceNode(1, 0, 'empty.js', ''); + var result = node.toStringWithSourceMap(); + assert.equal(result.code, ''); + }; + + exports['test .toStringWithSourceMap() with consecutive newlines'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + "/***/" + nl + nl, + new SourceNode(1, 0, "a.js", "'use strict';" + nl), + new SourceNode(2, 0, "a.js", "a();"), + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "/***/", + "", + "'use strict';", + "a();", + ].join(nl)); + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 4, column: 0 }, + source: 'a.js', + original: { line: 2, column: 0 } + }); + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test setSourceContent with toStringWithSourceMap'] = function (assert, util) { + var aNode = new SourceNode(1, 1, 'a.js', 'a'); + aNode.setSourceContent('a.js', 'someContent'); + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', aNode, + ' ', new SourceNode(1, 1, 'b.js', 'b'), + '}());']); + node.setSourceContent('b.js', 'otherContent'); + var map = node.toStringWithSourceMap({ + file: 'foo.js' + }).map; + + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = new SourceMapConsumer(map.toString()); + + assert.equal(map.sources.length, 2); + assert.equal(map.sources[0], 'a.js'); + assert.equal(map.sources[1], 'b.js'); + assert.equal(map.sourcesContent.length, 2); + assert.equal(map.sourcesContent[0], 'someContent'); + assert.equal(map.sourcesContent[1], 'otherContent'); + }; + + exports['test walkSourceContents'] = function (assert, util) { + var aNode = new SourceNode(1, 1, 'a.js', 'a'); + aNode.setSourceContent('a.js', 'someContent'); + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', aNode, + ' ', new SourceNode(1, 1, 'b.js', 'b'), + '}());']); + node.setSourceContent('b.js', 'otherContent'); + var results = []; + node.walkSourceContents(function (sourceFile, sourceContent) { + results.push([sourceFile, sourceContent]); + }); + assert.equal(results.length, 2); + assert.equal(results[0][0], 'a.js'); + assert.equal(results[0][1], 'someContent'); + assert.equal(results[1][0], 'b.js'); + assert.equal(results[1][1], 'otherContent'); + }; +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-util.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-util.js new file mode 100644 index 000000000..997d1a269 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/test-util.js @@ -0,0 +1,216 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var libUtil = require('../../lib/source-map/util'); + + exports['test urls'] = function (assert, util) { + var assertUrl = function (url) { + assert.equal(url, libUtil.urlGenerate(libUtil.urlParse(url))); + }; + assertUrl('http://'); + assertUrl('http://www.example.com'); + assertUrl('http://user:pass@www.example.com'); + assertUrl('http://www.example.com:80'); + assertUrl('http://www.example.com/'); + assertUrl('http://www.example.com/foo/bar'); + assertUrl('http://www.example.com/foo/bar/'); + assertUrl('http://user:pass@www.example.com:80/foo/bar/'); + + assertUrl('//'); + assertUrl('//www.example.com'); + assertUrl('file:///www.example.com'); + + assert.equal(libUtil.urlParse(''), null); + assert.equal(libUtil.urlParse('.'), null); + assert.equal(libUtil.urlParse('..'), null); + assert.equal(libUtil.urlParse('a'), null); + assert.equal(libUtil.urlParse('a/b'), null); + assert.equal(libUtil.urlParse('a//b'), null); + assert.equal(libUtil.urlParse('/a'), null); + assert.equal(libUtil.urlParse('data:foo,bar'), null); + }; + + exports['test normalize()'] = function (assert, util) { + assert.equal(libUtil.normalize('/..'), '/'); + assert.equal(libUtil.normalize('/../'), '/'); + assert.equal(libUtil.normalize('/../../../..'), '/'); + assert.equal(libUtil.normalize('/../../../../a/b/c'), '/a/b/c'); + assert.equal(libUtil.normalize('/a/b/c/../../../d/../../e'), '/e'); + + assert.equal(libUtil.normalize('..'), '..'); + assert.equal(libUtil.normalize('../'), '../'); + assert.equal(libUtil.normalize('../../a/'), '../../a/'); + assert.equal(libUtil.normalize('a/..'), '.'); + assert.equal(libUtil.normalize('a/../../..'), '../..'); + + assert.equal(libUtil.normalize('/.'), '/'); + assert.equal(libUtil.normalize('/./'), '/'); + assert.equal(libUtil.normalize('/./././.'), '/'); + assert.equal(libUtil.normalize('/././././a/b/c'), '/a/b/c'); + assert.equal(libUtil.normalize('/a/b/c/./././d/././e'), '/a/b/c/d/e'); + + assert.equal(libUtil.normalize(''), '.'); + assert.equal(libUtil.normalize('.'), '.'); + assert.equal(libUtil.normalize('./'), '.'); + assert.equal(libUtil.normalize('././a'), 'a'); + assert.equal(libUtil.normalize('a/./'), 'a/'); + assert.equal(libUtil.normalize('a/././.'), 'a'); + + assert.equal(libUtil.normalize('/a/b//c////d/////'), '/a/b/c/d/'); + assert.equal(libUtil.normalize('///a/b//c////d/////'), '///a/b/c/d/'); + assert.equal(libUtil.normalize('a/b//c////d'), 'a/b/c/d'); + + assert.equal(libUtil.normalize('.///.././../a/b//./..'), '../../a') + + assert.equal(libUtil.normalize('http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.normalize('http://www.example.com/'), 'http://www.example.com/'); + assert.equal(libUtil.normalize('http://www.example.com/./..//a/b/c/.././d//'), 'http://www.example.com/a/b/d/'); + }; + + exports['test join()'] = function (assert, util) { + assert.equal(libUtil.join('a', 'b'), 'a/b'); + assert.equal(libUtil.join('a/', 'b'), 'a/b'); + assert.equal(libUtil.join('a//', 'b'), 'a/b'); + assert.equal(libUtil.join('a', 'b/'), 'a/b/'); + assert.equal(libUtil.join('a', 'b//'), 'a/b/'); + assert.equal(libUtil.join('a/', '/b'), '/b'); + assert.equal(libUtil.join('a//', '//b'), '//b'); + + assert.equal(libUtil.join('a', '..'), '.'); + assert.equal(libUtil.join('a', '../b'), 'b'); + assert.equal(libUtil.join('a/b', '../c'), 'a/c'); + + assert.equal(libUtil.join('a', '.'), 'a'); + assert.equal(libUtil.join('a', './b'), 'a/b'); + assert.equal(libUtil.join('a/b', './c'), 'a/b/c'); + + assert.equal(libUtil.join('a', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('a', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('', 'b'), 'b'); + assert.equal(libUtil.join('.', 'b'), 'b'); + assert.equal(libUtil.join('', 'b/'), 'b/'); + assert.equal(libUtil.join('.', 'b/'), 'b/'); + assert.equal(libUtil.join('', 'b//'), 'b/'); + assert.equal(libUtil.join('.', 'b//'), 'b/'); + + assert.equal(libUtil.join('', '..'), '..'); + assert.equal(libUtil.join('.', '..'), '..'); + assert.equal(libUtil.join('', '../b'), '../b'); + assert.equal(libUtil.join('.', '../b'), '../b'); + + assert.equal(libUtil.join('', '.'), '.'); + assert.equal(libUtil.join('.', '.'), '.'); + assert.equal(libUtil.join('', './b'), 'b'); + assert.equal(libUtil.join('.', './b'), 'b'); + + assert.equal(libUtil.join('', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('.', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('', 'data:foo,bar'), 'data:foo,bar'); + assert.equal(libUtil.join('.', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('..', 'b'), '../b'); + assert.equal(libUtil.join('..', 'b/'), '../b/'); + assert.equal(libUtil.join('..', 'b//'), '../b/'); + + assert.equal(libUtil.join('..', '..'), '../..'); + assert.equal(libUtil.join('..', '../b'), '../../b'); + + assert.equal(libUtil.join('..', '.'), '..'); + assert.equal(libUtil.join('..', './b'), '../b'); + + assert.equal(libUtil.join('..', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('..', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('a', ''), 'a'); + assert.equal(libUtil.join('a', '.'), 'a'); + assert.equal(libUtil.join('a/', ''), 'a'); + assert.equal(libUtil.join('a/', '.'), 'a'); + assert.equal(libUtil.join('a//', ''), 'a'); + assert.equal(libUtil.join('a//', '.'), 'a'); + assert.equal(libUtil.join('/a', ''), '/a'); + assert.equal(libUtil.join('/a', '.'), '/a'); + assert.equal(libUtil.join('', ''), '.'); + assert.equal(libUtil.join('.', ''), '.'); + assert.equal(libUtil.join('.', ''), '.'); + assert.equal(libUtil.join('.', '.'), '.'); + assert.equal(libUtil.join('..', ''), '..'); + assert.equal(libUtil.join('..', '.'), '..'); + assert.equal(libUtil.join('http://foo.org/a', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a/', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a/', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a//', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a//', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org//', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org//', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('//www.example.com', ''), '//www.example.com/'); + assert.equal(libUtil.join('//www.example.com', '.'), '//www.example.com/'); + + + assert.equal(libUtil.join('http://foo.org/a', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a/', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a//', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a', 'b/'), 'http://foo.org/a/b/'); + assert.equal(libUtil.join('http://foo.org/a', 'b//'), 'http://foo.org/a/b/'); + assert.equal(libUtil.join('http://foo.org/a/', '/b'), 'http://foo.org/b'); + assert.equal(libUtil.join('http://foo.org/a//', '//b'), 'http://b'); + + assert.equal(libUtil.join('http://foo.org/a', '..'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/a', '../b'), 'http://foo.org/b'); + assert.equal(libUtil.join('http://foo.org/a/b', '../c'), 'http://foo.org/a/c'); + + assert.equal(libUtil.join('http://foo.org/a', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a', './b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a/b', './c'), 'http://foo.org/a/b/c'); + + assert.equal(libUtil.join('http://foo.org/a', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('http://foo.org/a', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('http://foo.org', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org//', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org', '/a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/', '/a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org//', '/a'), 'http://foo.org/a'); + + + assert.equal(libUtil.join('http://', 'www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('file:///', 'www.example.com'), 'file:///www.example.com'); + assert.equal(libUtil.join('http://', 'ftp://example.com'), 'ftp://example.com'); + + assert.equal(libUtil.join('http://www.example.com', '//foo.org/bar'), 'http://foo.org/bar'); + assert.equal(libUtil.join('//www.example.com', '//foo.org/bar'), '//foo.org/bar'); + }; + + // TODO Issue #128: Define and test this function properly. + exports['test relative()'] = function (assert, util) { + assert.equal(libUtil.relative('/the/root', '/the/root/one.js'), 'one.js'); + assert.equal(libUtil.relative('/the/root', '/the/rootone.js'), '/the/rootone.js'); + + assert.equal(libUtil.relative('', '/the/root/one.js'), '/the/root/one.js'); + assert.equal(libUtil.relative('.', '/the/root/one.js'), '/the/root/one.js'); + assert.equal(libUtil.relative('', 'the/root/one.js'), 'the/root/one.js'); + assert.equal(libUtil.relative('.', 'the/root/one.js'), 'the/root/one.js'); + + assert.equal(libUtil.relative('/', '/the/root/one.js'), 'the/root/one.js'); + assert.equal(libUtil.relative('/', 'the/root/one.js'), 'the/root/one.js'); + }; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js new file mode 100644 index 000000000..fa213ce13 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js @@ -0,0 +1,176 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('../../lib/source-map/util'); + + // This is a test mapping which maps functions from two different files + // (one.js and two.js) to a minified generated source. + // + // Here is one.js: + // + // ONE.foo = function (bar) { + // return baz(bar); + // }; + // + // Here is two.js: + // + // TWO.inc = function (n) { + // return n + 1; + // }; + // + // And here is the generated code (min.js): + // + // ONE.foo=function(a){return baz(a);}; + // TWO.inc=function(a){return a+1;}; + exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n"+ + " TWO.inc=function(a){return a+1;};"; + exports.testMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: '/the/root', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapNoSourceRoot = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapEmptySourceRoot = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: '', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapWithSourcesContent = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourcesContent: [ + ' ONE.foo = function (bar) {\n' + + ' return baz(bar);\n' + + ' };', + ' TWO.inc = function (n) {\n' + + ' return n + 1;\n' + + ' };' + ], + sourceRoot: '/the/root', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.emptyMap = { + version: 3, + file: 'min.js', + names: [], + sources: [], + mappings: '' + }; + + + function assertMapping(generatedLine, generatedColumn, originalSource, + originalLine, originalColumn, name, map, assert, + dontTestGenerated, dontTestOriginal) { + if (!dontTestOriginal) { + var origMapping = map.originalPositionFor({ + line: generatedLine, + column: generatedColumn + }); + assert.equal(origMapping.name, name, + 'Incorrect name, expected ' + JSON.stringify(name) + + ', got ' + JSON.stringify(origMapping.name)); + assert.equal(origMapping.line, originalLine, + 'Incorrect line, expected ' + JSON.stringify(originalLine) + + ', got ' + JSON.stringify(origMapping.line)); + assert.equal(origMapping.column, originalColumn, + 'Incorrect column, expected ' + JSON.stringify(originalColumn) + + ', got ' + JSON.stringify(origMapping.column)); + + var expectedSource; + + if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) { + expectedSource = originalSource; + } else if (originalSource) { + expectedSource = map.sourceRoot + ? util.join(map.sourceRoot, originalSource) + : originalSource; + } else { + expectedSource = null; + } + + assert.equal(origMapping.source, expectedSource, + 'Incorrect source, expected ' + JSON.stringify(expectedSource) + + ', got ' + JSON.stringify(origMapping.source)); + } + + if (!dontTestGenerated) { + var genMapping = map.generatedPositionFor({ + source: originalSource, + line: originalLine, + column: originalColumn + }); + assert.equal(genMapping.line, generatedLine, + 'Incorrect line, expected ' + JSON.stringify(generatedLine) + + ', got ' + JSON.stringify(genMapping.line)); + assert.equal(genMapping.column, generatedColumn, + 'Incorrect column, expected ' + JSON.stringify(generatedColumn) + + ', got ' + JSON.stringify(genMapping.column)); + } + } + exports.assertMapping = assertMapping; + + function assertEqualMaps(assert, actualMap, expectedMap) { + assert.equal(actualMap.version, expectedMap.version, "version mismatch"); + assert.equal(actualMap.file, expectedMap.file, "file mismatch"); + assert.equal(actualMap.names.length, + expectedMap.names.length, + "names length mismatch: " + + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + for (var i = 0; i < actualMap.names.length; i++) { + assert.equal(actualMap.names[i], + expectedMap.names[i], + "names[" + i + "] mismatch: " + + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + } + assert.equal(actualMap.sources.length, + expectedMap.sources.length, + "sources length mismatch: " + + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + for (var i = 0; i < actualMap.sources.length; i++) { + assert.equal(actualMap.sources[i], + expectedMap.sources[i], + "sources[" + i + "] length mismatch: " + + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + } + assert.equal(actualMap.sourceRoot, + expectedMap.sourceRoot, + "sourceRoot mismatch: " + + actualMap.sourceRoot + " != " + expectedMap.sourceRoot); + assert.equal(actualMap.mappings, expectedMap.mappings, + "mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings); + if (actualMap.sourcesContent) { + assert.equal(actualMap.sourcesContent.length, + expectedMap.sourcesContent.length, + "sourcesContent length mismatch"); + for (var i = 0; i < actualMap.sourcesContent.length; i++) { + assert.equal(actualMap.sourcesContent[i], + expectedMap.sourcesContent[i], + "sourcesContent[" + i + "] mismatch"); + } + } + } + exports.assertEqualMaps = assertEqualMaps; + +}); diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/package.json b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/package.json new file mode 100644 index 000000000..6587b99d3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/package.json @@ -0,0 +1,44 @@ +{ + "name": "uglify-js", + "description": "JavaScript parser, mangler/compressor and beautifier toolkit", + "homepage": "http://lisperator.net/uglifyjs", + "main": "tools/node.js", + "version": "2.2.5", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "Mihai Bazon", + "email": "mihai.bazon@gmail.com", + "url": "http://lisperator.net/" + } + ], + "repositories": [ + { + "type": "git", + "url": "https://github.com/mishoo/UglifyJS2.git" + } + ], + "dependencies": { + "source-map": "~0.1.7", + "optimist": "~0.3.5" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "scripts": { + "test": "node test/run-tests.js" + }, + "readme": "UglifyJS 2\n==========\n\nUglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit.\n\nThis page documents the command line utility. For\n[API and internals documentation see my website](http://lisperator.net/uglifyjs/).\nThere's also an\n[in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox,\nChrome and probably Safari).\n\nInstall\n-------\n\nFirst make sure you have installed the latest version of [node.js](http://nodejs.org/)\n(You may need to restart your computer after this step).\n\nFrom NPM for use as a command line app:\n\n npm install uglify-js -g\n\nFrom NPM for programmatic use:\n\n npm install uglify-js\n\nFrom Git:\n\n git clone git://github.com/mishoo/UglifyJS2.git\n cd UglifyJS2\n npm link .\n\nUsage\n-----\n\n uglifyjs [input files] [options]\n\nUglifyJS2 can take multiple input files. It's recommended that you pass the\ninput files first, then pass the options. UglifyJS will parse input files\nin sequence and apply any compression options. The files are parsed in the\nsame global scope, that is, a reference from a file to some\nvariable/function declared in another file will be matched properly.\n\nIf you want to read from STDIN instead, pass a single dash instead of input\nfiles.\n\nThe available options are:\n\n --source-map Specify an output file where to generate source map.\n [string]\n --source-map-root The path to the original source to be included in the\n source map. [string]\n --source-map-url The path to the source map to be added in //@\n sourceMappingURL. Defaults to the value passed with\n --source-map. [string]\n --in-source-map Input source map, useful if you're compressing JS that was\n generated from some other original code.\n -p, --prefix Skip prefix for original filenames that appear in source\n maps. For example -p 3 will drop 3 directories from file\n names and ensure they are relative paths.\n -o, --output Output file (default STDOUT).\n -b, --beautify Beautify output/specify output options. [string]\n -m, --mangle Mangle names/pass mangler options. [string]\n -r, --reserved Reserved names to exclude from mangling.\n -c, --compress Enable compressor/pass compressor options. Pass options\n like -c hoist_vars=false,if_return=false. Use -c with no\n argument to use the default compression options. [string]\n -d, --define Global definitions [string]\n --comments Preserve copyright comments in the output. By default this\n works like Google Closure, keeping JSDoc-style comments\n that contain \"@license\" or \"@preserve\". You can optionally\n pass one of the following arguments to this flag:\n - \"all\" to keep all comments\n - a valid JS regexp (needs to start with a slash) to keep\n only comments that match.\n Note that currently not *all* comments can be kept when\n compression is on, because of dead code removal or\n cascading statements into sequences. [string]\n --stats Display operations run time on STDERR. [boolean]\n --acorn Use Acorn for parsing. [boolean]\n --spidermonkey Assume input fles are SpiderMonkey AST format (as JSON).\n [boolean]\n --self Build itself (UglifyJS2) as a library (implies\n --wrap=UglifyJS --export-all) [boolean]\n --wrap Embed everything in a big function, making the “exports”\n and “global” variables available. You need to pass an\n argument to this option to specify the name that your\n module will take when included in, say, a browser.\n [string]\n --export-all Only used when --wrap, this tells UglifyJS to add code to\n automatically export all globals. [boolean]\n --lint Display some scope warnings [boolean]\n -v, --verbose Verbose [boolean]\n -V, --version Print version number and exit. [boolean]\n\nSpecify `--output` (`-o`) to declare the output file. Otherwise the output\ngoes to STDOUT.\n\n## Source map options\n\nUglifyJS2 can generate a source map file, which is highly useful for\ndebugging your compressed JavaScript. To get a source map, pass\n`--source-map output.js.map` (full path to the file where you want the\nsource map dumped).\n\nAdditionally you might need `--source-map-root` to pass the URL where the\noriginal files can be found. In case you are passing full paths to input\nfiles to UglifyJS, you can use `--prefix` (`-p`) to specify the number of\ndirectories to drop from the path prefix when declaring files in the source\nmap.\n\nFor example:\n\n uglifyjs /home/doe/work/foo/src/js/file1.js \\\n /home/doe/work/foo/src/js/file2.js \\\n -o foo.min.js \\\n --source-map foo.min.js.map \\\n --source-map-root http://foo.com/src \\\n -p 5 -c -m\n\nThe above will compress and mangle `file1.js` and `file2.js`, will drop the\noutput in `foo.min.js` and the source map in `foo.min.js.map`. The source\nmapping will refer to `http://foo.com/src/js/file1.js` and\n`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`\nas the source map root, and the original files as `js/file1.js` and\n`js/file2.js`).\n\n### Composed source map\n\nWhen you're compressing JS code that was output by a compiler such as\nCoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd\nlike to map back to the original code (i.e. CoffeeScript). UglifyJS has an\noption to take an input source map. Assuming you have a mapping from\nCoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript →\ncompressed JS by mapping every token in the compiled JS to its original\nlocation.\n\nTo use this feature you need to pass `--in-source-map\n/path/to/input/source.map`. Normally the input source map should also point\nto the file containing the generated JS, so if that's correct you can omit\ninput files from the command line.\n\n## Mangler options\n\nTo enable the mangler you need to pass `--mangle` (`-m`). Optionally you\ncan pass `-m sort=true` (we'll possibly have other flags in the future) in order\nto assign shorter names to most frequently used variables. This saves a few\nhundred bytes on jQuery before gzip, but the output is _bigger_ after gzip\n(and seems to happen for other libraries I tried it on) therefore it's not\nenabled by default.\n\nWhen mangling is enabled but you want to prevent certain names from being\nmangled, you can declare those names with `--reserved` (`-r`) — pass a\ncomma-separated list of names. For example:\n\n uglifyjs ... -m -r '$,require,exports'\n\nto prevent the `require`, `exports` and `$` names from being changed.\n\n## Compressor options\n\nYou need to pass `--compress` (`-c`) to enable the compressor. Optionally\nyou can pass a comma-separated list of options. Options are in the form\n`foo=bar`, or just `foo` (the latter implies a boolean option that you want\nto set `true`; it's effectively a shortcut for `foo=true`).\n\nThe defaults should be tuned for maximum compression on most code. Here are\nthe available options (all are `true` by default, except `hoist_vars`):\n\n- `sequences` -- join consecutive simple statements using the comma operator\n- `properties` -- rewrite property access using the dot notation, for\n example `foo[\"bar\"] → foo.bar`\n- `dead_code` -- remove unreachable code\n- `drop_debugger` -- remove `debugger;` statements\n- `unsafe` -- apply \"unsafe\" transformations (discussion below)\n- `conditionals` -- apply optimizations for `if`-s and conditional\n expressions\n- `comparisons` -- apply certain optimizations to binary nodes, for example:\n `!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes,\n e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.\n- `evaluate` -- attempt to evaluate constant expressions\n- `booleans` -- various optimizations for boolean context, for example `!!a\n ? b : c → a ? b : c`\n- `loops` -- optimizations for `do`, `while` and `for` loops when we can\n statically determine the condition\n- `unused` -- drop unreferenced functions and variables\n- `hoist_funs` -- hoist function declarations\n- `hoist_vars` -- hoist `var` declarations (this is `false` by default\n because it seems to increase the size of the output in general)\n- `if_return` -- optimizations for if/return and if/continue\n- `join_vars` -- join consecutive `var` statements\n- `cascade` -- small optimization for sequences, transform `x, x` into `x`\n and `x = something(), x` into `x = something()`\n- `warnings` -- display warnings when dropping unreachable code or unused\n declarations etc.\n\n### Conditional compilation\n\nYou can use the `--define` (`-d`) switch in order to declare global\nvariables that UglifyJS will assume to be constants (unless defined in\nscope). For example if you pass `--define DEBUG=false` then, coupled with\ndead code removal UglifyJS will discard the following from the output:\n\n if (DEBUG) {\n console.log(\"debug stuff\");\n }\n\nUglifyJS will warn about the condition being always false and about dropping\nunreachable code; for now there is no option to turn off only this specific\nwarning, you can pass `warnings=false` to turn off *all* warnings.\n\nAnother way of doing that is to declare your globals as constants in a\nseparate file and include it into the build. For example you can have a\n`build/defines.js` file with the following:\n\n const DEBUG = false;\n const PRODUCTION = true;\n // etc.\n\nand build your code like this:\n\n uglifyjs build/defines.js js/foo.js js/bar.js... -c\n\nUglifyJS will notice the constants and, since they cannot be altered, it\nwill evaluate references to them to the value itself and drop unreachable\ncode as usual. The possible downside of this approach is that the build\nwill contain the `const` declarations.\n\n\n## Beautifier options\n\nThe code generator tries to output shortest code possible by default. In\ncase you want beautified output, pass `--beautify` (`-b`). Optionally you\ncan pass additional arguments that control the code output:\n\n- `beautify` (default `true`) -- whether to actually beautify the output.\n Passing `-b` will set this to true, but you might need to pass `-b` even\n when you want to generate minified code, in order to specify additional\n arguments, so you can use `-b beautify=false` to override it.\n- `indent-level` (default 4)\n- `indent-start` (default 0) -- prefix all lines by that many spaces\n- `quote-keys` (default `false`) -- pass `true` to quote all keys in literal\n objects\n- `space-colon` (default `true`) -- insert a space after the colon signs\n- `ascii-only` (default `false`) -- escape Unicode characters in strings and\n regexps\n- `inline-script` (default `false`) -- escape the slash in occurrences of\n ` 5) break; // this break refers to the for, not to the switch; thus it + // shouldn't ruin our optimization + console.log(x); + } + y(); + case 1+1: + bar(); + break; + default: + def(); + } + } + } + expect: { + OUT: { + foo(); + x(); + if (foo) break OUT; + for (var x = 0; x < 10; x++) { + if (x > 5) break; + console.log(x); + } + y(); + bar(); + } + } +} + +constant_switch_8: { + options = { dead_code: true, evaluate: true }; + input: { + OUT: switch (1) { + case 1: + x(); + for (;;) break OUT; + y(); + break; + case 1+1: + bar(); + default: + def(); + } + } + expect: { + OUT: { + x(); + for (;;) break OUT; + y(); + } + } +} + +constant_switch_9: { + options = { dead_code: true, evaluate: true }; + input: { + OUT: switch (1) { + case 1: + x(); + for (;;) if (foo) break OUT; + y(); + case 1+1: + bar(); + default: + def(); + } + } + expect: { + OUT: { + x(); + for (;;) if (foo) break OUT; + y(); + bar(); + def(); + } + } +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/test/run-tests.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/test/run-tests.js new file mode 100644 index 000000000..0568c6a7a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/test/run-tests.js @@ -0,0 +1,170 @@ +#! /usr/bin/env node + +var U = require("../tools/node"); +var path = require("path"); +var fs = require("fs"); +var assert = require("assert"); +var sys = require("util"); + +var tests_dir = path.dirname(module.filename); + +run_compress_tests(); + +/* -----[ utils ]----- */ + +function tmpl() { + return U.string_template.apply(this, arguments); +} + +function log() { + var txt = tmpl.apply(this, arguments); + sys.puts(txt); +} + +function log_directory(dir) { + log("*** Entering [{dir}]", { dir: dir }); +} + +function log_start_file(file) { + log("--- {file}", { file: file }); +} + +function log_test(name) { + log(" Running test [{name}]", { name: name }); +} + +function find_test_files(dir) { + var files = fs.readdirSync(dir).filter(function(name){ + return /\.js$/i.test(name); + }); + if (process.argv.length > 2) { + var x = process.argv.slice(2); + files = files.filter(function(f){ + return x.indexOf(f) >= 0; + }); + } + return files; +} + +function test_directory(dir) { + return path.resolve(tests_dir, dir); +} + +function as_toplevel(input) { + if (input instanceof U.AST_BlockStatement) input = input.body; + else if (input instanceof U.AST_Statement) input = [ input ]; + else throw new Error("Unsupported input syntax"); + var toplevel = new U.AST_Toplevel({ body: input }); + toplevel.figure_out_scope(); + return toplevel; +} + +function run_compress_tests() { + var dir = test_directory("compress"); + log_directory("compress"); + var files = find_test_files(dir); + function test_file(file) { + log_start_file(file); + function test_case(test) { + log_test(test.name); + var options = U.defaults(test.options, { + warnings: false + }); + var cmp = new U.Compressor(options, true); + var expect = make_code(as_toplevel(test.expect), false); + var input = as_toplevel(test.input); + var input_code = make_code(test.input); + var output = input.transform(cmp); + output.figure_out_scope(); + output = make_code(output, false); + if (expect != output) { + log("!!! failed\n---INPUT---\n{input}\n---OUTPUT---\n{output}\n---EXPECTED---\n{expected}\n\n", { + input: input_code, + output: output, + expected: expect + }); + } + } + var tests = parse_test(path.resolve(dir, file)); + for (var i in tests) if (tests.hasOwnProperty(i)) { + test_case(tests[i]); + } + } + files.forEach(function(file){ + test_file(file); + }); +} + +function parse_test(file) { + var script = fs.readFileSync(file, "utf8"); + var ast = U.parse(script, { + filename: file + }); + var tests = {}; + var tw = new U.TreeWalker(function(node, descend){ + if (node instanceof U.AST_LabeledStatement + && tw.parent() instanceof U.AST_Toplevel) { + var name = node.label.name; + tests[name] = get_one_test(name, node.body); + return true; + } + if (!(node instanceof U.AST_Toplevel)) croak(node); + }); + ast.walk(tw); + return tests; + + function croak(node) { + throw new Error(tmpl("Can't understand test file {file} [{line},{col}]\n{code}", { + file: file, + line: node.start.line, + col: node.start.col, + code: make_code(node, false) + })); + } + + function get_one_test(name, block) { + var test = { name: name, options: {} }; + var tw = new U.TreeWalker(function(node, descend){ + if (node instanceof U.AST_Assign) { + if (!(node.left instanceof U.AST_SymbolRef)) { + croak(node); + } + var name = node.left.name; + test[name] = evaluate(node.right); + return true; + } + if (node instanceof U.AST_LabeledStatement) { + assert.ok( + node.label.name == "input" || node.label.name == "expect", + tmpl("Unsupported label {name} [{line},{col}]", { + name: node.label.name, + line: node.label.start.line, + col: node.label.start.col + }) + ); + var stat = node.body; + if (stat instanceof U.AST_BlockStatement) { + if (stat.body.length == 1) stat = stat.body[0]; + else if (stat.body.length == 0) stat = new U.AST_EmptyStatement(); + } + test[node.label.name] = stat; + return true; + } + }); + block.walk(tw); + return test; + }; +} + +function make_code(ast, beautify) { + if (arguments.length == 1) beautify = true; + var stream = U.OutputStream({ beautify: beautify }); + ast.print(stream); + return stream.get(); +} + +function evaluate(code) { + if (code instanceof U.AST_Node) + code = make_code(code); + return new Function("return(" + code + ")")(); +} diff --git a/node_modules/jade/node_modules/transformers/node_modules/uglify-js/tools/node.js b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/tools/node.js new file mode 100644 index 000000000..cf87628d8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/node_modules/uglify-js/tools/node.js @@ -0,0 +1,164 @@ +var path = require("path"); +var fs = require("fs"); +var vm = require("vm"); +var sys = require("util"); + +var UglifyJS = vm.createContext({ + sys : sys, + console : console, + MOZ_SourceMap : require("source-map") +}); + +function load_global(file) { + file = path.resolve(path.dirname(module.filename), file); + try { + var code = fs.readFileSync(file, "utf8"); + return vm.runInContext(code, UglifyJS, file); + } catch(ex) { + // XXX: in case of a syntax error, the message is kinda + // useless. (no location information). + sys.debug("ERROR in file: " + file + " / " + ex); + process.exit(1); + } +}; + +var FILES = exports.FILES = [ + "../lib/utils.js", + "../lib/ast.js", + "../lib/parse.js", + "../lib/transform.js", + "../lib/scope.js", + "../lib/output.js", + "../lib/compress.js", + "../lib/sourcemap.js", + "../lib/mozilla-ast.js" +].map(function(file){ + return path.join(path.dirname(fs.realpathSync(__filename)), file); +}); + +FILES.forEach(load_global); + +UglifyJS.AST_Node.warn_function = function(txt) { + sys.error("WARN: " + txt); +}; + +// XXX: perhaps we shouldn't export everything but heck, I'm lazy. +for (var i in UglifyJS) { + if (UglifyJS.hasOwnProperty(i)) { + exports[i] = UglifyJS[i]; + } +} + +exports.minify = function(files, options) { + options = UglifyJS.defaults(options, { + outSourceMap : null, + sourceRoot : null, + inSourceMap : null, + fromString : false, + warnings : false, + mangle : {}, + output : null, + compress : {} + }); + if (typeof files == "string") + files = [ files ]; + + // 1. parse + var toplevel = null; + files.forEach(function(file){ + var code = options.fromString + ? file + : fs.readFileSync(file, "utf8"); + toplevel = UglifyJS.parse(code, { + filename: options.fromString ? "?" : file, + toplevel: toplevel + }); + }); + + // 2. compress + if (options.compress) { + var compress = { warnings: options.warnings }; + UglifyJS.merge(compress, options.compress); + toplevel.figure_out_scope(); + var sq = UglifyJS.Compressor(compress); + toplevel = toplevel.transform(sq); + } + + // 3. mangle + if (options.mangle) { + toplevel.figure_out_scope(); + toplevel.compute_char_frequency(); + toplevel.mangle_names(options.mangle); + } + + // 4. output + var map = null; + var inMap = null; + if (options.inSourceMap) { + inMap = fs.readFileSync(options.inSourceMap, "utf8"); + } + if (options.outSourceMap) map = UglifyJS.SourceMap({ + file: options.outSourceMap, + orig: inMap, + root: options.sourceRoot + }); + var output = { source_map: map }; + if (options.output) { + UglifyJS.merge(output, options.output); + } + var stream = UglifyJS.OutputStream(output); + toplevel.print(stream); + return { + code : stream + "", + map : map + "" + }; +}; + +// exports.describe_ast = function() { +// function doitem(ctor) { +// var sub = {}; +// ctor.SUBCLASSES.forEach(function(ctor){ +// sub[ctor.TYPE] = doitem(ctor); +// }); +// var ret = {}; +// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; +// if (ctor.SUBCLASSES.length > 0) ret.sub = sub; +// return ret; +// } +// return doitem(UglifyJS.AST_Node).sub; +// } + +exports.describe_ast = function() { + var out = UglifyJS.OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + var props = ctor.SELF_PROPS.filter(function(prop){ + return !/^\$/.test(prop); + }); + if (props.length > 0) { + out.space(); + out.with_parens(function(){ + props.forEach(function(prop, i){ + if (i) out.space(); + out.print(prop); + }); + }); + } + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function(){ + ctor.SUBCLASSES.forEach(function(ctor, i){ + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + }; + doitem(UglifyJS.AST_Node); + return out + ""; +}; diff --git a/node_modules/jade/node_modules/transformers/package.json b/node_modules/jade/node_modules/transformers/package.json new file mode 100644 index 000000000..035a63a28 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/package.json @@ -0,0 +1,89 @@ +{ + "name": "transformers", + "version": "2.0.1", + "description": "String/Data transformations for use in templating libraries, static site generators and web frameworks", + "main": "lib/transformers.js", + "scripts": { + "pretest": "node test/update-package && npm install", + "test": "mocha test/test.js -R spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/ForbesLindesay/transformers.git" + }, + "author": { + "name": "ForbesLindesay" + }, + "license": "MIT", + "gitHead": "4b46e72cba3ad3403fd5ed3802d5472dcfa77311", + "devDependencies": { + "mocha": "~1.8", + "expect.js": "~0.2", + "swig": "*", + "atpl": "*", + "liquor": "*", + "ejs": "*", + "eco": "*", + "jqtpl": "*", + "hamljs": "*", + "haml-coffee": "*", + "whiskers": "*", + "hogan.js": "*", + "handlebars": "*", + "underscore": "*", + "walrus": "*", + "mustache": "*", + "mote": "*", + "toffee": "*", + "just": "*", + "ect": "*", + "jade": "*", + "then-jade": "*", + "dust": "*", + "dustjs-linkedin": "*", + "jazz": "*", + "qejs": "*", + "less": "*", + "stylus": "*", + "sass": "*", + "marked": "*", + "supermarked": "*", + "markdown-js": "*", + "markdown": "*", + "coffee-script": "*", + "cson": "*", + "coffeekup": "*", + "coffeecup": "*", + "templayed": "*", + "plates": "*", + "dot": "*", + "component-builder": "*", + "html2jade": "*", + "highlight.js": "*" + }, + "dependencies": { + "promise": "~2.0", + "css": "~1.0.8", + "uglify-js": "~2.2.5" + }, + "_id": "transformers@2.0.1", + "dist": { + "shasum": "352131dfceb93a7532dc7535a4f142510435a394", + "tarball": "http://registry.npmjs.org/transformers/-/transformers-2.0.1.tgz" + }, + "_from": "transformers@2.0.1", + "_npmVersion": "1.2.10", + "_npmUser": { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + }, + "maintainers": [ + { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + } + ], + "directories": {}, + "_shasum": "352131dfceb93a7532dc7535a4f142510435a394", + "_resolved": "https://registry.npmjs.org/transformers/-/transformers-2.0.1.tgz" +} diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.css b/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.css new file mode 100644 index 000000000..7519e93ca --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.css @@ -0,0 +1,6 @@ +#foo { + name: 'bar'; +} +#baz { + name: 'bing'; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.js new file mode 100644 index 000000000..51b9b2eea --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/build/build.js @@ -0,0 +1,1235 @@ + + +/** + * hasOwnProperty. + */ + +var has = Object.prototype.hasOwnProperty; + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (has.call(require.modules, path)) return path; + } + + if (has.call(require.aliases, index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!has.call(require.modules, from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return has.call(require.modules, localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("component-type/index.js", function(exports, require, module){ + +/** + * toString ref. + */ + +var toString = Object.prototype.toString; + +/** + * Return the type of `val`. + * + * @param {Mixed} val + * @return {String} + * @api public + */ + +module.exports = function(val){ + switch (toString.call(val)) { + case '[object Function]': return 'function'; + case '[object Date]': return 'date'; + case '[object RegExp]': return 'regexp'; + case '[object Arguments]': return 'arguments'; + case '[object Array]': return 'array'; + case '[object String]': return 'string'; + } + + if (val === null) return 'null'; + if (val === undefined) return 'undefined'; + if (val === Object(val)) return 'object'; + + return typeof val; +}; + +}); +require.register("component-event/index.js", function(exports, require, module){ + +/** + * Bind `el` event `type` to `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.bind = function(el, type, fn, capture){ + if (el.addEventListener) { + el.addEventListener(type, fn, capture); + } else { + el.attachEvent('on' + type, fn); + } + return fn; +}; + +/** + * Unbind `el` event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + if (el.removeEventListener) { + el.removeEventListener(type, fn, capture); + } else { + el.detachEvent('on' + type, fn); + } + return fn; +}; + +}); +require.register("component-matches-selector/index.js", function(exports, require, module){ + +/** + * Element prototype. + */ + +var proto = Element.prototype; + +/** + * Vendor function. + */ + +var vendor = proto.matchesSelector + || proto.webkitMatchesSelector + || proto.mozMatchesSelector + || proto.msMatchesSelector + || proto.oMatchesSelector; + +/** + * Expose `match()`. + */ + +module.exports = match; + +/** + * Match `el` to `selector`. + * + * @param {Element} el + * @param {String} selector + * @return {Boolean} + * @api public + */ + +function match(el, selector) { + if (vendor) return vendor.call(el, selector); + var nodes = el.parentNode.querySelectorAll(selector); + for (var i = 0; i < nodes.length; ++i) { + if (nodes[i] == el) return true; + } + return false; +} +}); +require.register("component-delegate/index.js", function(exports, require, module){ + +/** + * Module dependencies. + */ + +var matches = require('matches-selector') + , event = require('event'); + +/** + * Delegate event `type` to `selector` + * and invoke `fn(e)`. A callback function + * is returned which may be passed to `.unbind()`. + * + * @param {Element} el + * @param {String} selector + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.bind = function(el, selector, type, fn, capture){ + return event.bind(el, type, function(e){ + if (matches(e.target, selector)) fn(e); + }, capture); + return callback; +}; + +/** + * Unbind event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + event.unbind(el, type, fn, capture); +}; + +}); +require.register("component-indexof/index.js", function(exports, require, module){ + +var indexOf = [].indexOf; + +module.exports = function(arr, obj){ + if (indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; +}); +require.register("component-domify/index.js", function(exports, require, module){ + +/** + * Expose `parse`. + */ + +module.exports = parse; + +/** + * Wrap map from jquery. + */ + +var map = { + option: [1, ''], + optgroup: [1, ''], + legend: [1, '
    ', '
    '], + thead: [1, '', '
    '], + tbody: [1, '', '
    '], + tfoot: [1, '', '
    '], + colgroup: [1, '', '
    '], + caption: [1, '', '
    '], + tr: [2, '', '
    '], + td: [3, '', '
    '], + th: [3, '', '
    '], + col: [2, '', '
    '], + _default: [0, '', ''] +}; + +/** + * Parse `html` and return the children. + * + * @param {String} html + * @return {Array} + * @api private + */ + +function parse(html) { + if ('string' != typeof html) throw new TypeError('String expected'); + + // tag name + var m = /<([\w:]+)/.exec(html); + if (!m) throw new Error('No elements were generated.'); + var tag = m[1]; + + // body support + if (tag == 'body') { + var el = document.createElement('html'); + el.innerHTML = html; + return [el.removeChild(el.lastChild)]; + } + + // wrap map + var wrap = map[tag] || map._default; + var depth = wrap[0]; + var prefix = wrap[1]; + var suffix = wrap[2]; + var el = document.createElement('div'); + el.innerHTML = prefix + html + suffix; + while (depth--) el = el.lastChild; + + return orphan(el.children); +} + +/** + * Orphan `els` and return an array. + * + * @param {NodeList} els + * @return {Array} + * @api private + */ + +function orphan(els) { + var ret = []; + + while (els.length) { + ret.push(els[0].parentNode.removeChild(els[0])); + } + + return ret; +} + +}); +require.register("component-classes/index.js", function(exports, require, module){ + +/** + * Module dependencies. + */ + +var index = require('indexof'); + +/** + * Whitespace regexp. + */ + +var re = /\s+/; + +/** + * toString reference. + */ + +var toString = Object.prototype.toString; + +/** + * Wrap `el` in a `ClassList`. + * + * @param {Element} el + * @return {ClassList} + * @api public + */ + +module.exports = function(el){ + return new ClassList(el); +}; + +/** + * Initialize a new ClassList for `el`. + * + * @param {Element} el + * @api private + */ + +function ClassList(el) { + this.el = el; + this.list = el.classList; +} + +/** + * Add class `name` if not already present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.add = function(name){ + // classList + if (this.list) { + this.list.add(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (!~i) arr.push(name); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove class `name` when present, or + * pass a regular expression to remove + * any which match. + * + * @param {String|RegExp} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.remove = function(name){ + if ('[object RegExp]' == toString.call(name)) { + return this.removeMatching(name); + } + + // classList + if (this.list) { + this.list.remove(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (~i) arr.splice(i, 1); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove all classes matching `re`. + * + * @param {RegExp} re + * @return {ClassList} + * @api private + */ + +ClassList.prototype.removeMatching = function(re){ + var arr = this.array(); + for (var i = 0; i < arr.length; i++) { + if (re.test(arr[i])) { + this.remove(arr[i]); + } + } + return this; +}; + +/** + * Toggle class `name`. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.toggle = function(name){ + // classList + if (this.list) { + this.list.toggle(name); + return this; + } + + // fallback + if (this.has(name)) { + this.remove(name); + } else { + this.add(name); + } + return this; +}; + +/** + * Return an array of classes. + * + * @return {Array} + * @api public + */ + +ClassList.prototype.array = function(){ + var arr = this.el.className.split(re); + if ('' === arr[0]) arr.pop(); + return arr; +}; + +/** + * Check if class `name` is present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.has = +ClassList.prototype.contains = function(name){ + return this.list + ? this.list.contains(name) + : !! ~index(this.array(), name); +}; + +}); +require.register("component-dom/index.js", function(exports, require, module){ +/** + * Module dependencies. + */ + +var domify = require('domify') + , classes = require('classes') + , indexof = require('indexof') + , delegate = require('delegate') + , events = require('event') + , type = require('type') + +/** + * Attributes supported. + */ + +var attrs = [ + 'id', + 'src', + 'rel', + 'cols', + 'rows', + 'name', + 'href', + 'title', + 'style', + 'width', + 'height', + 'tabindex', + 'placeholder' +]; + +/** + * Expose `dom()`. + */ + +exports = module.exports = dom; + +/** + * Expose supported attrs. + */ + +exports.attrs = attrs; + +/** + * Return a dom `List` for the given + * `html`, selector, or element. + * + * @param {String|Element|List} + * @return {List} + * @api public + */ + +function dom(selector, context) { + var ctx = context + ? (context.els ? context.els[0] : context) + : document.firstChild; + + // array + if (Array.isArray(selector)) { + return new List(selector); + } + + // List + if (selector instanceof List) { + return selector; + } + + // node + if (selector.nodeName) { + return new List([selector]); + } + + // html + if ('<' == selector.charAt(0)) { + return new List([domify(selector)[0]], selector); + } + + // selector + if ('string' == typeof selector) { + return new List(ctx.querySelectorAll(selector), selector); + } +} + +/** + * Expose `List` constructor. + */ + +exports.List = List; + +/** + * Initialize a new `List` with the + * given array-ish of `els` and `selector` + * string. + * + * @param {Mixed} els + * @param {String} selector + * @api private + */ + +function List(els, selector) { + this.els = els || []; + this.selector = selector; +} + +/** + * Set attribute `name` to `val`, or get attr `name`. + * + * @param {String} name + * @param {String} [val] + * @return {String|List} self + * @api public + */ + +List.prototype.attr = function(name, val){ + if (2 == arguments.length) { + this.els[0].setAttribute(name, val); + return this; + } else { + return this.els[0].getAttribute(name); + } +}; + +/** + * Return a cloned `List` with all elements cloned. + * + * @return {List} + * @api public + */ + +List.prototype.clone = function(){ + var arr = []; + for (var i = 0, len = this.els.length; i < len; ++i) { + arr.push(this.els[i].cloneNode(true)); + } + return new List(arr); +}; + +/** + * Prepend `val`. + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.prepend = function(val){ + var el = this.els[0]; + if (!el) return this; + val = dom(val); + for (var i = 0; i < val.els.length; ++i) { + if (el.children.length) { + el.insertBefore(val.els[i], el.firstChild); + } else { + el.appendChild(val.els[i]); + } + } + return this; +}; + +/** + * Append `val`. + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.append = function(val){ + var el = this.els[0]; + if (!el) return this; + val = dom(val); + for (var i = 0; i < val.els.length; ++i) { + el.appendChild(val.els[i]); + } + return this; +}; + +/** + * Append self's `el` to `val` + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.appendTo = function(val){ + dom(val).append(this); +}; + +/** + * Return a `List` containing the element at `i`. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.at = function(i){ + return new List([this.els[i]], this.selector); +}; + +/** + * Return a `List` containing the first element. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.first = function(){ + return new List([this.els[0]], this.selector); +}; + +/** + * Return a `List` containing the last element. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.last = function(){ + return new List([this.els[this.els.length - 1]], this.selector); +}; + +/** + * Return an `Element` at `i`. + * + * @param {Number} i + * @return {Element} + * @api public + */ + +List.prototype.get = function(i){ + return this.els[i]; +}; + +/** + * Return list length. + * + * @return {Number} + * @api public + */ + +List.prototype.length = function(){ + return this.els.length; +}; + +/** + * Return element text. + * + * @return {String} + * @api public + */ + +List.prototype.text = function(){ + // TODO: real impl + var str = ''; + for (var i = 0; i < this.els.length; ++i) { + str += this.els[i].textContent; + } + return str; +}; + +/** + * Return element html. + * + * @return {String} + * @api public + */ + +List.prototype.html = function(){ + // TODO: real impl + return this.els[0] && this.els[0].innerHTML; +}; + +/** + * Bind to `event` and invoke `fn(e)`. When + * a `selector` is given then events are delegated. + * + * @param {String} event + * @param {String} [selector] + * @param {Function} fn + * @param {Boolean} capture + * @return {List} + * @api public + */ + +List.prototype.on = function(event, selector, fn, capture){ + if ('string' == typeof selector) { + for (var i = 0; i < this.els.length; ++i) { + fn._delegate = delegate.bind(this.els[i], selector, event, fn, capture); + } + return this; + } + + capture = fn; + fn = selector; + + for (var i = 0; i < this.els.length; ++i) { + events.bind(this.els[i], event, fn, capture); + } + + return this; +}; + +/** + * Unbind to `event` and invoke `fn(e)`. When + * a `selector` is given then delegated event + * handlers are unbound. + * + * @param {String} event + * @param {String} [selector] + * @param {Function} fn + * @param {Boolean} capture + * @return {List} + * @api public + */ + +List.prototype.off = function(event, selector, fn, capture){ + if ('string' == typeof selector) { + for (var i = 0; i < this.els.length; ++i) { + // TODO: add selector support back + delegate.unbind(this.els[i], event, fn._delegate, capture); + } + return this; + } + + capture = fn; + fn = selector; + + for (var i = 0; i < this.els.length; ++i) { + events.unbind(this.els[i], event, fn, capture); + } + return this; +}; + +/** + * Iterate elements and invoke `fn(list, i)`. + * + * @param {Function} fn + * @return {List} self + * @api public + */ + +List.prototype.each = function(fn){ + for (var i = 0; i < this.els.length; ++i) { + fn(new List([this.els[i]], this.selector), i); + } + return this; +}; + +/** + * Iterate elements and invoke `fn(el, i)`. + * + * @param {Function} fn + * @return {List} self + * @api public + */ + +List.prototype.forEach = function(fn){ + for (var i = 0; i < this.els.length; ++i) { + fn(this.els[i], i); + } + return this; +}; + +/** + * Map elements invoking `fn(list, i)`. + * + * @param {Function} fn + * @return {Array} + * @api public + */ + +List.prototype.map = function(fn){ + var arr = []; + for (var i = 0; i < this.els.length; ++i) { + arr.push(fn(new List([this.els[i]], this.selector), i)); + } + return arr; +}; + +/** + * Filter elements invoking `fn(list, i)`, returning + * a new `List` of elements when a truthy value is returned. + * + * @param {Function} fn + * @return {List} + * @api public + */ + +List.prototype.select = +List.prototype.filter = function(fn){ + var el; + var list = new List([], this.selector); + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + if (fn(new List([el], this.selector), i)) list.els.push(el); + } + return list; +}; + +/** + * Add the given class `name`. + * + * @param {String} name + * @return {List} self + * @api public + */ + +List.prototype.addClass = function(name){ + var el; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes.add(name); + } + return this; +}; + +/** + * Remove the given class `name`. + * + * @param {String|RegExp} name + * @return {List} self + * @api public + */ + +List.prototype.removeClass = function(name){ + var el; + + if ('regexp' == type(name)) { + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + var arr = el._classes.array(); + for (var j = 0; j < arr.length; j++) { + if (name.test(arr[j])) { + el._classes.remove(arr[j]); + } + } + } + return this; + } + + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes.remove(name); + } + + return this; +}; + +/** + * Toggle the given class `name`, + * optionally a `bool` may be given + * to indicate that the class should + * be added when truthy. + * + * @param {String} name + * @param {Boolean} bool + * @return {List} self + * @api public + */ + +List.prototype.toggleClass = function(name, bool){ + var el; + var fn = 'toggle'; + + // toggle with boolean + if (2 == arguments.length) { + fn = bool ? 'add' : 'remove'; + } + + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes[fn](name); + } + + return this; +}; + +/** + * Check if the given class `name` is present. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +List.prototype.hasClass = function(name){ + var el; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + if (el._classes.has(name)) return true; + } + return false; +}; + +/** + * Set CSS `prop` to `val` or get `prop` value. + * + * @param {String} prop + * @param {Mixed} val + * @return {List|String} + * @api public + */ + +List.prototype.css = function(prop, val){ + if (2 == arguments.length) return this.setStyle(prop, val); + return this.getStyle(prop); +}; + +/** + * Set CSS `prop` to `val`. + * + * @param {String} prop + * @param {Mixed} val + * @return {List} self + * @api private + */ + +List.prototype.setStyle = function(prop, val){ + for (var i = 0; i < this.els.length; ++i) { + this.els[i].style[prop] = val; + } + return this; +}; + +/** + * Get CSS `prop` value. + * + * @param {String} prop + * @return {String} + * @api private + */ + +List.prototype.getStyle = function(prop){ + var el = this.els[0]; + if (el) return el.style[prop]; +}; + +/** + * Find children matching the given `selector`. + * + * @param {String} selector + * @return {List} + * @api public + */ + +List.prototype.find = function(selector){ + // TODO: real implementation + var list = new List([], this.selector); + var el, els; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + els = el.querySelectorAll(selector); + for (var j = 0; j < els.length; ++j) { + list.els.push(els[j]); + } + } + return list; +}; + +/** + * Attribute accessors. + */ + +attrs.forEach(function(name){ + List.prototype[name] = function(val){ + if (0 == arguments.length) return this.attr(name); + return this.attr(name, val); + }; +}); + + +}); +require.register("foo/index.js", function(exports, require, module){ +module.exports = 'foo'; +}); +require.alias("component-dom/index.js", "foo/deps/dom/index.js"); +require.alias("component-type/index.js", "component-dom/deps/type/index.js"); + +require.alias("component-event/index.js", "component-dom/deps/event/index.js"); + +require.alias("component-delegate/index.js", "component-dom/deps/delegate/index.js"); +require.alias("component-matches-selector/index.js", "component-delegate/deps/matches-selector/index.js"); + +require.alias("component-event/index.js", "component-delegate/deps/event/index.js"); + +require.alias("component-indexof/index.js", "component-dom/deps/indexof/index.js"); + +require.alias("component-domify/index.js", "component-dom/deps/domify/index.js"); + +require.alias("component-classes/index.js", "component-dom/deps/classes/index.js"); +require.alias("component-indexof/index.js", "component-classes/deps/indexof/index.js"); + diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/component.json new file mode 100644 index 000000000..d24701d4a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/component.json @@ -0,0 +1,8 @@ +{ + "name": "foo", + "scripts": ["index.js"], + "styles": ["index.css", "second.css"], + "dependencies": { + "component/dom": "*" + } +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/component.json new file mode 100644 index 000000000..0c67e32fd --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/component.json @@ -0,0 +1,19 @@ +{ + "name": "classes", + "version": "1.1.0", + "description": "Cross-browser element class list", + "keywords": [ + "dom", + "html", + "classList", + "class", + "ui" + ], + "scripts": [ + "index.js" + ], + "dependencies": { + "component/indexof": "*" + }, + "repo": "https://raw.github.com/component/classes" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/index.js new file mode 100644 index 000000000..e3a30d585 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-classes/index.js @@ -0,0 +1,164 @@ + +/** + * Module dependencies. + */ + +var index = require('indexof'); + +/** + * Whitespace regexp. + */ + +var re = /\s+/; + +/** + * toString reference. + */ + +var toString = Object.prototype.toString; + +/** + * Wrap `el` in a `ClassList`. + * + * @param {Element} el + * @return {ClassList} + * @api public + */ + +module.exports = function(el){ + return new ClassList(el); +}; + +/** + * Initialize a new ClassList for `el`. + * + * @param {Element} el + * @api private + */ + +function ClassList(el) { + this.el = el; + this.list = el.classList; +} + +/** + * Add class `name` if not already present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.add = function(name){ + // classList + if (this.list) { + this.list.add(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (!~i) arr.push(name); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove class `name` when present, or + * pass a regular expression to remove + * any which match. + * + * @param {String|RegExp} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.remove = function(name){ + if ('[object RegExp]' == toString.call(name)) { + return this.removeMatching(name); + } + + // classList + if (this.list) { + this.list.remove(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (~i) arr.splice(i, 1); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove all classes matching `re`. + * + * @param {RegExp} re + * @return {ClassList} + * @api private + */ + +ClassList.prototype.removeMatching = function(re){ + var arr = this.array(); + for (var i = 0; i < arr.length; i++) { + if (re.test(arr[i])) { + this.remove(arr[i]); + } + } + return this; +}; + +/** + * Toggle class `name`. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.toggle = function(name){ + // classList + if (this.list) { + this.list.toggle(name); + return this; + } + + // fallback + if (this.has(name)) { + this.remove(name); + } else { + this.add(name); + } + return this; +}; + +/** + * Return an array of classes. + * + * @return {Array} + * @api public + */ + +ClassList.prototype.array = function(){ + var arr = this.el.className.split(re); + if ('' === arr[0]) arr.pop(); + return arr; +}; + +/** + * Check if class `name` is present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.has = +ClassList.prototype.contains = function(name){ + return this.list + ? this.list.contains(name) + : !! ~index(this.array(), name); +}; diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/component.json new file mode 100644 index 000000000..8461aa40b --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/component.json @@ -0,0 +1,19 @@ +{ + "name": "delegate", + "repo": "component/delegate", + "description": "Event delegation component", + "version": "0.1.0", + "keywords": [ + "event", + "events", + "delegate", + "delegation" + ], + "dependencies": { + "component/matches-selector": "*", + "component/event": "*" + }, + "scripts": [ + "index.js" + ] +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/index.js new file mode 100644 index 000000000..03b9f9e69 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-delegate/index.js @@ -0,0 +1,42 @@ + +/** + * Module dependencies. + */ + +var matches = require('matches-selector') + , event = require('event'); + +/** + * Delegate event `type` to `selector` + * and invoke `fn(e)`. A callback function + * is returned which may be passed to `.unbind()`. + * + * @param {Element} el + * @param {String} selector + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.bind = function(el, selector, type, fn, capture){ + return event.bind(el, type, function(e){ + if (matches(e.target, selector)) fn(e); + }, capture); + return callback; +}; + +/** + * Unbind event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + event.unbind(el, type, fn, capture); +}; diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/component.json new file mode 100644 index 000000000..6aa448cdf --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/component.json @@ -0,0 +1,27 @@ +{ + "name": "dom", + "version": "0.1.0", + "description": "DOM traversal, manipulation and events aggregate library", + "keywords": [ + "html", + "dom", + "ui", + "jquery" + ], + "scripts": [ + "index.js" + ], + "dependencies": { + "component/type": "*", + "component/event": "*", + "component/delegate": "*", + "component/indexof": "*", + "component/domify": "*", + "component/classes": "*" + }, + "development": { + "component/assert": "*" + }, + "license": "MIT", + "repo": "https://raw.github.com/component/dom" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/index.js new file mode 100644 index 000000000..0f9df95f7 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-dom/index.js @@ -0,0 +1,579 @@ +/** + * Module dependencies. + */ + +var domify = require('domify') + , classes = require('classes') + , indexof = require('indexof') + , delegate = require('delegate') + , events = require('event') + , type = require('type') + +/** + * Attributes supported. + */ + +var attrs = [ + 'id', + 'src', + 'rel', + 'cols', + 'rows', + 'name', + 'href', + 'title', + 'style', + 'width', + 'height', + 'tabindex', + 'placeholder' +]; + +/** + * Expose `dom()`. + */ + +exports = module.exports = dom; + +/** + * Expose supported attrs. + */ + +exports.attrs = attrs; + +/** + * Return a dom `List` for the given + * `html`, selector, or element. + * + * @param {String|Element|List} + * @return {List} + * @api public + */ + +function dom(selector, context) { + var ctx = context + ? (context.els ? context.els[0] : context) + : document.firstChild; + + // array + if (Array.isArray(selector)) { + return new List(selector); + } + + // List + if (selector instanceof List) { + return selector; + } + + // node + if (selector.nodeName) { + return new List([selector]); + } + + // html + if ('<' == selector.charAt(0)) { + return new List([domify(selector)[0]], selector); + } + + // selector + if ('string' == typeof selector) { + return new List(ctx.querySelectorAll(selector), selector); + } +} + +/** + * Expose `List` constructor. + */ + +exports.List = List; + +/** + * Initialize a new `List` with the + * given array-ish of `els` and `selector` + * string. + * + * @param {Mixed} els + * @param {String} selector + * @api private + */ + +function List(els, selector) { + this.els = els || []; + this.selector = selector; +} + +/** + * Set attribute `name` to `val`, or get attr `name`. + * + * @param {String} name + * @param {String} [val] + * @return {String|List} self + * @api public + */ + +List.prototype.attr = function(name, val){ + if (2 == arguments.length) { + this.els[0].setAttribute(name, val); + return this; + } else { + return this.els[0].getAttribute(name); + } +}; + +/** + * Return a cloned `List` with all elements cloned. + * + * @return {List} + * @api public + */ + +List.prototype.clone = function(){ + var arr = []; + for (var i = 0, len = this.els.length; i < len; ++i) { + arr.push(this.els[i].cloneNode(true)); + } + return new List(arr); +}; + +/** + * Prepend `val`. + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.prepend = function(val){ + var el = this.els[0]; + if (!el) return this; + val = dom(val); + for (var i = 0; i < val.els.length; ++i) { + if (el.children.length) { + el.insertBefore(val.els[i], el.firstChild); + } else { + el.appendChild(val.els[i]); + } + } + return this; +}; + +/** + * Append `val`. + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.append = function(val){ + var el = this.els[0]; + if (!el) return this; + val = dom(val); + for (var i = 0; i < val.els.length; ++i) { + el.appendChild(val.els[i]); + } + return this; +}; + +/** + * Append self's `el` to `val` + * + * @param {String|Element|List} val + * @return {List} self + * @api public + */ + +List.prototype.appendTo = function(val){ + dom(val).append(this); +}; + +/** + * Return a `List` containing the element at `i`. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.at = function(i){ + return new List([this.els[i]], this.selector); +}; + +/** + * Return a `List` containing the first element. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.first = function(){ + return new List([this.els[0]], this.selector); +}; + +/** + * Return a `List` containing the last element. + * + * @param {Number} i + * @return {List} + * @api public + */ + +List.prototype.last = function(){ + return new List([this.els[this.els.length - 1]], this.selector); +}; + +/** + * Return an `Element` at `i`. + * + * @param {Number} i + * @return {Element} + * @api public + */ + +List.prototype.get = function(i){ + return this.els[i]; +}; + +/** + * Return list length. + * + * @return {Number} + * @api public + */ + +List.prototype.length = function(){ + return this.els.length; +}; + +/** + * Return element text. + * + * @return {String} + * @api public + */ + +List.prototype.text = function(){ + // TODO: real impl + var str = ''; + for (var i = 0; i < this.els.length; ++i) { + str += this.els[i].textContent; + } + return str; +}; + +/** + * Return element html. + * + * @return {String} + * @api public + */ + +List.prototype.html = function(){ + // TODO: real impl + return this.els[0] && this.els[0].innerHTML; +}; + +/** + * Bind to `event` and invoke `fn(e)`. When + * a `selector` is given then events are delegated. + * + * @param {String} event + * @param {String} [selector] + * @param {Function} fn + * @param {Boolean} capture + * @return {List} + * @api public + */ + +List.prototype.on = function(event, selector, fn, capture){ + if ('string' == typeof selector) { + for (var i = 0; i < this.els.length; ++i) { + fn._delegate = delegate.bind(this.els[i], selector, event, fn, capture); + } + return this; + } + + capture = fn; + fn = selector; + + for (var i = 0; i < this.els.length; ++i) { + events.bind(this.els[i], event, fn, capture); + } + + return this; +}; + +/** + * Unbind to `event` and invoke `fn(e)`. When + * a `selector` is given then delegated event + * handlers are unbound. + * + * @param {String} event + * @param {String} [selector] + * @param {Function} fn + * @param {Boolean} capture + * @return {List} + * @api public + */ + +List.prototype.off = function(event, selector, fn, capture){ + if ('string' == typeof selector) { + for (var i = 0; i < this.els.length; ++i) { + // TODO: add selector support back + delegate.unbind(this.els[i], event, fn._delegate, capture); + } + return this; + } + + capture = fn; + fn = selector; + + for (var i = 0; i < this.els.length; ++i) { + events.unbind(this.els[i], event, fn, capture); + } + return this; +}; + +/** + * Iterate elements and invoke `fn(list, i)`. + * + * @param {Function} fn + * @return {List} self + * @api public + */ + +List.prototype.each = function(fn){ + for (var i = 0; i < this.els.length; ++i) { + fn(new List([this.els[i]], this.selector), i); + } + return this; +}; + +/** + * Iterate elements and invoke `fn(el, i)`. + * + * @param {Function} fn + * @return {List} self + * @api public + */ + +List.prototype.forEach = function(fn){ + for (var i = 0; i < this.els.length; ++i) { + fn(this.els[i], i); + } + return this; +}; + +/** + * Map elements invoking `fn(list, i)`. + * + * @param {Function} fn + * @return {Array} + * @api public + */ + +List.prototype.map = function(fn){ + var arr = []; + for (var i = 0; i < this.els.length; ++i) { + arr.push(fn(new List([this.els[i]], this.selector), i)); + } + return arr; +}; + +/** + * Filter elements invoking `fn(list, i)`, returning + * a new `List` of elements when a truthy value is returned. + * + * @param {Function} fn + * @return {List} + * @api public + */ + +List.prototype.select = +List.prototype.filter = function(fn){ + var el; + var list = new List([], this.selector); + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + if (fn(new List([el], this.selector), i)) list.els.push(el); + } + return list; +}; + +/** + * Add the given class `name`. + * + * @param {String} name + * @return {List} self + * @api public + */ + +List.prototype.addClass = function(name){ + var el; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes.add(name); + } + return this; +}; + +/** + * Remove the given class `name`. + * + * @param {String|RegExp} name + * @return {List} self + * @api public + */ + +List.prototype.removeClass = function(name){ + var el; + + if ('regexp' == type(name)) { + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + var arr = el._classes.array(); + for (var j = 0; j < arr.length; j++) { + if (name.test(arr[j])) { + el._classes.remove(arr[j]); + } + } + } + return this; + } + + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes.remove(name); + } + + return this; +}; + +/** + * Toggle the given class `name`, + * optionally a `bool` may be given + * to indicate that the class should + * be added when truthy. + * + * @param {String} name + * @param {Boolean} bool + * @return {List} self + * @api public + */ + +List.prototype.toggleClass = function(name, bool){ + var el; + var fn = 'toggle'; + + // toggle with boolean + if (2 == arguments.length) { + fn = bool ? 'add' : 'remove'; + } + + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + el._classes[fn](name); + } + + return this; +}; + +/** + * Check if the given class `name` is present. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +List.prototype.hasClass = function(name){ + var el; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + el._classes = el._classes || classes(el); + if (el._classes.has(name)) return true; + } + return false; +}; + +/** + * Set CSS `prop` to `val` or get `prop` value. + * + * @param {String} prop + * @param {Mixed} val + * @return {List|String} + * @api public + */ + +List.prototype.css = function(prop, val){ + if (2 == arguments.length) return this.setStyle(prop, val); + return this.getStyle(prop); +}; + +/** + * Set CSS `prop` to `val`. + * + * @param {String} prop + * @param {Mixed} val + * @return {List} self + * @api private + */ + +List.prototype.setStyle = function(prop, val){ + for (var i = 0; i < this.els.length; ++i) { + this.els[i].style[prop] = val; + } + return this; +}; + +/** + * Get CSS `prop` value. + * + * @param {String} prop + * @return {String} + * @api private + */ + +List.prototype.getStyle = function(prop){ + var el = this.els[0]; + if (el) return el.style[prop]; +}; + +/** + * Find children matching the given `selector`. + * + * @param {String} selector + * @return {List} + * @api public + */ + +List.prototype.find = function(selector){ + // TODO: real implementation + var list = new List([], this.selector); + var el, els; + for (var i = 0; i < this.els.length; ++i) { + el = this.els[i]; + els = el.querySelectorAll(selector); + for (var j = 0; j < els.length; ++j) { + list.els.push(els[j]); + } + } + return list; +}; + +/** + * Attribute accessors. + */ + +attrs.forEach(function(name){ + List.prototype[name] = function(val){ + if (0 == arguments.length) return this.attr(name); + return this.attr(name, val); + }; +}); + diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/component.json new file mode 100644 index 000000000..95fff1faa --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/component.json @@ -0,0 +1,20 @@ +{ + "name": "domify", + "version": "0.1.0", + "description": "turn HTML into DOM elements", + "scripts": [ + "index.js" + ], + "development": { + "visionmedia/mocha-cloud": "*" + }, + "keywords": [ + "dom", + "html", + "client", + "browser", + "component" + ], + "license": "MIT", + "repo": "https://raw.github.com/component/domify" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/index.js new file mode 100644 index 000000000..55eb1b59e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-domify/index.js @@ -0,0 +1,79 @@ + +/** + * Expose `parse`. + */ + +module.exports = parse; + +/** + * Wrap map from jquery. + */ + +var map = { + option: [1, ''], + optgroup: [1, ''], + legend: [1, '
    ', '
    '], + thead: [1, '', '
    '], + tbody: [1, '', '
    '], + tfoot: [1, '', '
    '], + colgroup: [1, '', '
    '], + caption: [1, '', '
    '], + tr: [2, '', '
    '], + td: [3, '', '
    '], + th: [3, '', '
    '], + col: [2, '', '
    '], + _default: [0, '', ''] +}; + +/** + * Parse `html` and return the children. + * + * @param {String} html + * @return {Array} + * @api private + */ + +function parse(html) { + if ('string' != typeof html) throw new TypeError('String expected'); + + // tag name + var m = /<([\w:]+)/.exec(html); + if (!m) throw new Error('No elements were generated.'); + var tag = m[1]; + + // body support + if (tag == 'body') { + var el = document.createElement('html'); + el.innerHTML = html; + return [el.removeChild(el.lastChild)]; + } + + // wrap map + var wrap = map[tag] || map._default; + var depth = wrap[0]; + var prefix = wrap[1]; + var suffix = wrap[2]; + var el = document.createElement('div'); + el.innerHTML = prefix + html + suffix; + while (depth--) el = el.lastChild; + + return orphan(el.children); +} + +/** + * Orphan `els` and return an array. + * + * @param {NodeList} els + * @return {Array} + * @api private + */ + +function orphan(els) { + var ret = []; + + while (els.length) { + ret.push(els[0].parentNode.removeChild(els[0])); + } + + return ret; +} diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/component.json new file mode 100644 index 000000000..c20f5bf48 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/component.json @@ -0,0 +1,13 @@ +{ + "name": "event", + "repo": "component/event", + "description": "Event binding component", + "version": "0.1.0", + "keywords": [ + "event", + "events" + ], + "scripts": [ + "index.js" + ] +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/index.js new file mode 100644 index 000000000..f111b1757 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-event/index.js @@ -0,0 +1,40 @@ + +/** + * Bind `el` event `type` to `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.bind = function(el, type, fn, capture){ + if (el.addEventListener) { + el.addEventListener(type, fn, capture); + } else { + el.attachEvent('on' + type, fn); + } + return fn; +}; + +/** + * Unbind `el` event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + if (el.removeEventListener) { + el.removeEventListener(type, fn, capture); + } else { + el.detachEvent('on' + type, fn); + } + return fn; +}; diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/component.json new file mode 100644 index 000000000..282e39ce6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/component.json @@ -0,0 +1,15 @@ +{ + "name": "indexof", + "description": "Microsoft sucks", + "version": "0.0.1", + "keywords": [ + "index", + "array", + "indexOf" + ], + "dependencies": {}, + "scripts": [ + "index.js" + ], + "repo": "https://raw.github.com/component/indexof" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/index.js new file mode 100644 index 000000000..9d9667b2c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-indexof/index.js @@ -0,0 +1,10 @@ + +var indexOf = [].indexOf; + +module.exports = function(arr, obj){ + if (indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/component.json new file mode 100644 index 000000000..ea48be39a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/component.json @@ -0,0 +1,17 @@ +{ + "name": "matches-selector", + "repo": "component/matches-selector", + "description": "Check if an element matches a given selector", + "version": "0.0.1", + "keywords": [ + "match", + "element", + "selector" + ], + "development": { + "component/domify": "*" + }, + "scripts": [ + "index.js" + ] +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/index.js new file mode 100644 index 000000000..8f67590c7 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-matches-selector/index.js @@ -0,0 +1,40 @@ + +/** + * Element prototype. + */ + +var proto = Element.prototype; + +/** + * Vendor function. + */ + +var vendor = proto.matchesSelector + || proto.webkitMatchesSelector + || proto.mozMatchesSelector + || proto.msMatchesSelector + || proto.oMatchesSelector; + +/** + * Expose `match()`. + */ + +module.exports = match; + +/** + * Match `el` to `selector`. + * + * @param {Element} el + * @param {String} selector + * @return {Boolean} + * @api public + */ + +function match(el, selector) { + if (vendor) return vendor.call(el, selector); + var nodes = el.parentNode.querySelectorAll(selector); + for (var i = 0; i < nodes.length; ++i) { + if (nodes[i] == el) return true; + } + return false; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/component.json b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/component.json new file mode 100644 index 000000000..901f736f5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/component.json @@ -0,0 +1,15 @@ +{ + "name": "type", + "description": "Cross-browser type assertions (less broken typeof)", + "version": "0.0.1", + "keywords": [ + "typeof", + "type", + "utility" + ], + "dependencies": {}, + "scripts": [ + "index.js" + ], + "repo": "https://raw.github.com/component/type" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/index.js new file mode 100644 index 000000000..32f1fdef4 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/components/component-type/index.js @@ -0,0 +1,31 @@ + +/** + * toString ref. + */ + +var toString = Object.prototype.toString; + +/** + * Return the type of `val`. + * + * @param {Mixed} val + * @return {String} + * @api public + */ + +module.exports = function(val){ + switch (toString.call(val)) { + case '[object Function]': return 'function'; + case '[object Date]': return 'date'; + case '[object RegExp]': return 'regexp'; + case '[object Arguments]': return 'arguments'; + case '[object Array]': return 'array'; + case '[object String]': return 'string'; + } + + if (val === null) return 'null'; + if (val === undefined) return 'undefined'; + if (val === Object(val)) return 'object'; + + return typeof val; +}; diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/index.css b/node_modules/jade/node_modules/transformers/test/fixtures/component/index.css new file mode 100644 index 000000000..80ed56756 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/index.css @@ -0,0 +1,3 @@ +#foo { + name: 'bar'; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/index.js b/node_modules/jade/node_modules/transformers/test/fixtures/component/index.js new file mode 100644 index 000000000..d00e0a2e1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/index.js @@ -0,0 +1 @@ +module.exports = 'foo'; \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/component/second.css b/node_modules/jade/node_modules/transformers/test/fixtures/component/second.css new file mode 100644 index 000000000..6666a584f --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/component/second.css @@ -0,0 +1,3 @@ +#baz { + name: 'bing'; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/fixtures/uglify-js/script.js b/node_modules/jade/node_modules/transformers/test/fixtures/uglify-js/script.js new file mode 100644 index 000000000..8a2f505bc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/fixtures/uglify-js/script.js @@ -0,0 +1,6 @@ +(function (name) { + function hello(world) { + return 'Hello ' + world + '!'; + } + return hello(name); +}('Forbes Lindesay')); \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/atpl/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a-expected.txt new file mode 100644 index 000000000..c88ab7ca5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a-expected.txt @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a.txt new file mode 100644 index 000000000..95d09f2b1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-a.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b-expected.txt new file mode 100644 index 000000000..81540ec10 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b-expected.txt @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b.txt new file mode 100644 index 000000000..b8f852e74 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cdata/sample-b.txt @@ -0,0 +1 @@ +goodbye world \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a-expected.txt new file mode 100644 index 000000000..a65ebe74d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a-expected.txt @@ -0,0 +1,6 @@ +(function() { + var n; + + n = 4; + +}).call(this); diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a.txt new file mode 100644 index 000000000..a7c552dfe --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-a.txt @@ -0,0 +1 @@ +n = 4; \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b-expected.txt new file mode 100644 index 000000000..a65ebe74d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b-expected.txt @@ -0,0 +1,6 @@ +(function() { + var n; + + n = 4; + +}).call(this); diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b.txt new file mode 100644 index 000000000..a7c552dfe --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffee-script/sample-b.txt @@ -0,0 +1 @@ +n = 4; \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a-expected.txt new file mode 100644 index 000000000..c8be9c271 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a-expected.txt @@ -0,0 +1 @@ +
    • foo
    • bar
    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a.txt new file mode 100644 index 000000000..f3699283b --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-a.txt @@ -0,0 +1,3 @@ +ul -> + li 'foo' + li 'bar' \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b-expected.txt new file mode 100644 index 000000000..8c02a7f8e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b-expected.txt @@ -0,0 +1 @@ +
    1. foo
    2. bar
    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b.txt new file mode 100644 index 000000000..f75d44366 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/coffeecup/sample-b.txt @@ -0,0 +1,3 @@ +ol -> + li 'foo' + li 'bar' \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a-expected.txt new file mode 100644 index 000000000..500bb12d3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a-expected.txt @@ -0,0 +1 @@ +{"abc":["a","b","c"],"a":{"b":"c"}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a.txt new file mode 100644 index 000000000..11c3d1db3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-a.txt @@ -0,0 +1,9 @@ +{ + abc: [ + 'a' + 'b' + 'c' + ] + a: + b: 'c' +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b-expected.txt new file mode 100644 index 000000000..63d5fe1c1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b-expected.txt @@ -0,0 +1 @@ +{"abc":["a",5,"c"],"a":{"b":"c"}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b.txt new file mode 100644 index 000000000..101b9f5c6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/cson/sample-b.txt @@ -0,0 +1,9 @@ +{ + abc: [ + 'a' + 5 + 'c' + ] + a: + b: 'c' +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/dot/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/dot/sample-a.txt new file mode 100644 index 000000000..e2fc66cc5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/dot/sample-a.txt @@ -0,0 +1 @@ +

    {{=it.user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/dot/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/dot/sample-b.txt new file mode 100644 index 000000000..6ea9cf023 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/dot/sample-b.txt @@ -0,0 +1 @@ +{{=it.user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/dust/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/dust/sample-a.txt new file mode 100644 index 000000000..d2f6eeb6c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/dust/sample-a.txt @@ -0,0 +1 @@ +

    {user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/dust/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/dust/sample-b.txt new file mode 100644 index 000000000..d6a4beaeb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/dust/sample-b.txt @@ -0,0 +1 @@ +{user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/eco/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/eco/sample-a.txt new file mode 100644 index 000000000..e95657f70 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/eco/sample-a.txt @@ -0,0 +1 @@ +

    <%= @user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/eco/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/eco/sample-b.txt new file mode 100644 index 000000000..a78ce39ae --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/eco/sample-b.txt @@ -0,0 +1 @@ +<%= @user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/ect/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/ect/sample-a.txt new file mode 100644 index 000000000..e95657f70 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/ect/sample-a.txt @@ -0,0 +1 @@ +

    <%= @user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/ect/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/ect/sample-b.txt new file mode 100644 index 000000000..a78ce39ae --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/ect/sample-b.txt @@ -0,0 +1 @@ +<%= @user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-a.txt new file mode 100644 index 000000000..b015881bb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-a.txt @@ -0,0 +1 @@ +

    <%= user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-b.txt new file mode 100644 index 000000000..a55afc518 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/ejs/sample-b.txt @@ -0,0 +1 @@ +<%= user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-a.txt new file mode 100644 index 000000000..c6b8fb84c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-a.txt @@ -0,0 +1 @@ +%p= @user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-b.txt new file mode 100644 index 000000000..d579cbe73 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml-coffee/sample-b.txt @@ -0,0 +1 @@ +%strong= @user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a-expected.txt new file mode 100644 index 000000000..a692f8fe1 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a-expected.txt @@ -0,0 +1,2 @@ + +

    bob

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a.txt new file mode 100644 index 000000000..166d31575 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-a.txt @@ -0,0 +1 @@ +%p= user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b-expected.txt new file mode 100644 index 000000000..8260b879e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b-expected.txt @@ -0,0 +1,2 @@ + +bob \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b.txt new file mode 100644 index 000000000..f64da6e76 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/haml/sample-b.txt @@ -0,0 +1 @@ +%strong= user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/handlebars/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/hogan/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a-expected.txt new file mode 100644 index 000000000..8c69046f3 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a-expected.txt @@ -0,0 +1,7 @@ +!!! 5 +html + head + link(type='text/css', rel='stylesheet', href='/site.css') + title Hello + body + h1 Hello world! diff --git a/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a.txt new file mode 100644 index 000000000..face1014f --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-a.txt @@ -0,0 +1,10 @@ + + + + + Hello + + +

    Hello world!

    + + \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b-expected.txt new file mode 100644 index 000000000..f12c62f74 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b-expected.txt @@ -0,0 +1,7 @@ +!!! 5 +html + head + link(type='text/css', rel='stylesheet', href='/site.css') + title Hello + body + h1 Hello Forbes! diff --git a/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b.txt new file mode 100644 index 000000000..0ceeda473 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/html2jade/sample-b.txt @@ -0,0 +1,10 @@ + + + + + Hello + + +

    Hello Forbes!

    + + \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jade/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/jade/sample-a.txt new file mode 100644 index 000000000..623c6654a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jade/sample-a.txt @@ -0,0 +1 @@ +p= user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jade/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/jade/sample-b.txt new file mode 100644 index 000000000..da8875c69 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jade/sample-b.txt @@ -0,0 +1 @@ +strong= user.name \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-a.txt new file mode 100644 index 000000000..d2f6eeb6c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-a.txt @@ -0,0 +1 @@ +

    {user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-b.txt new file mode 100644 index 000000000..d6a4beaeb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jazz/sample-b.txt @@ -0,0 +1 @@ +{user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-a.txt new file mode 100644 index 000000000..13817b6fc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-a.txt @@ -0,0 +1 @@ +

    ${user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-b.txt new file mode 100644 index 000000000..363655680 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/jqtpl/sample-b.txt @@ -0,0 +1 @@ +${user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/just/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/just/sample-a.txt new file mode 100644 index 000000000..b015881bb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/just/sample-a.txt @@ -0,0 +1 @@ +

    <%= user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/just/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/just/sample-b.txt new file mode 100644 index 000000000..a55afc518 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/just/sample-b.txt @@ -0,0 +1 @@ +<%= user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/less/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/less/sample-a-expected.txt new file mode 100644 index 000000000..961fe6959 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/less/sample-a-expected.txt @@ -0,0 +1,27 @@ +.variables { + width: 14cm; +} +.variables { + height: 24px; + color: #888888; + font-family: "Trebuchet MS", Verdana, sans-serif; + quotes: "~" "~"; +} +.redefinition { + three: 3; +} +.values { + font-family: 'Trebuchet', 'Trebuchet', 'Trebuchet'; + color: #888888 !important; + url: url('Trebuchet'); + multi: something 'A', B, C, 'Trebuchet'; +} +.variable-names { + name: 'hello'; +} +.alpha { + filter: alpha(opacity=42); +} +a:nth-child(2) { + border: 1px; +} diff --git a/node_modules/jade/node_modules/transformers/test/simple/less/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/less/sample-a.txt new file mode 100644 index 000000000..3d7529ecf --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/less/sample-a.txt @@ -0,0 +1,54 @@ +@a: 2; +@x: @a * @a; +@y: @x + 1; +@z: @x * 2 + @y; + +.variables { + width: @z + 1cm; // 14cm +} + +@b: @a * 10; +@c: #888; + +@fonts: "Trebuchet MS", Verdana, sans-serif; +@f: @fonts; + +@quotes: "~" "~"; +@q: @quotes; + +.variables { + height: @b + @x + 0px; // 24px + color: @c; + font-family: @f; + quotes: @q; +} + +.redefinition { + @var: 4; + @var: 2; + @var: 3; + three: @var; +} + +.values { + @a: 'Trebuchet'; + @multi: 'A', B, C; + font-family: @a, @a, @a; + color: @c !important; + url: url(@a); + multi: something @multi, @a; +} + +.variable-names { + @var: 'hello'; + @name: 'var'; + name: @@name; +} +.alpha { + @var: 42; + filter: alpha(opacity=@var); +} + +a:nth-child(@a) { + border: 1px; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/less/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/less/sample-b-expected.txt new file mode 100644 index 000000000..649a7f4a4 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/less/sample-b-expected.txt @@ -0,0 +1,27 @@ +.variables { + width: 14cm; +} +.variables { + height: 24px; + color: #888888; + font-family: "Trebuchet MS"; + quotes: "~" "~"; +} +.redefinition { + three: 3; +} +.values { + font-family: 'Trebuchet', 'Trebuchet', 'Trebuchet'; + color: #888888 !important; + url: url('Trebuchet'); + multi: something 'A', B, C, 'Trebuchet'; +} +.variable-names { + name: 'hello'; +} +.alpha { + filter: alpha(opacity=42); +} +a:nth-child(2) { + border: 1px; +} diff --git a/node_modules/jade/node_modules/transformers/test/simple/less/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/less/sample-b.txt new file mode 100644 index 000000000..0fc80a344 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/less/sample-b.txt @@ -0,0 +1,54 @@ +@a: 2; +@x: @a * @a; +@y: @x + 1; +@z: @x * 2 + @y; + +.variables { + width: @z + 1cm; // 14cm +} + +@b: @a * 10; +@c: #888; + +@fonts: "Trebuchet MS"; +@f: @fonts; + +@quotes: "~" "~"; +@q: @quotes; + +.variables { + height: @b + @x + 0px; // 24px + color: @c; + font-family: @f; + quotes: @q; +} + +.redefinition { + @var: 4; + @var: 2; + @var: 3; + three: @var; +} + +.values { + @a: 'Trebuchet'; + @multi: 'A', B, C; + font-family: @a, @a, @a; + color: @c !important; + url: url(@a); + multi: something @multi, @a; +} + +.variable-names { + @var: 'hello'; + @name: 'var'; + name: @@name; +} +.alpha { + @var: 42; + filter: alpha(opacity=@var); +} + +a:nth-child(@a) { + border: 1px; +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-a.txt new file mode 100644 index 000000000..04b1781b9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-a.txt @@ -0,0 +1 @@ +

    #{user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-b.txt new file mode 100644 index 000000000..76eedd8b8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/liquor/sample-b.txt @@ -0,0 +1 @@ +#{user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a-expected.txt new file mode 100644 index 000000000..977a9ad51 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a-expected.txt @@ -0,0 +1,6 @@ +

    Heading 1

    +

    Heading 2

    +
      +
    • bullet 1
    • +
    • bullet 2
    • +
    diff --git a/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a.txt new file mode 100644 index 000000000..bbd8eb05c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-a.txt @@ -0,0 +1,6 @@ +# Heading 1 + +## Heading 2 + +- bullet 1 +- bullet 2 \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b-expected.txt new file mode 100644 index 000000000..b22f33bfc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b-expected.txt @@ -0,0 +1,6 @@ +

    Heading 1

    +

    Heading 2

    +
      +
    1. num 1
    2. +
    3. num 2
    4. +
    diff --git a/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b.txt new file mode 100644 index 000000000..73f4b83e0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/markdown/sample-b.txt @@ -0,0 +1,6 @@ +# Heading 1 + +## Heading 2 + +1. num 1 +2. num 2 \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/mote/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/mote/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/mote/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/mote/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/mote/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/mote/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-a.txt new file mode 100644 index 000000000..c7270fbf4 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-a.txt @@ -0,0 +1 @@ +

    {{#user}}{{name}}{{/user}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-b.txt new file mode 100644 index 000000000..90982aecf --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/mustache/sample-b.txt @@ -0,0 +1 @@ +{{#user}}{{name}}{{/user}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a-expected.txt new file mode 100644 index 000000000..25f2db206 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a-expected.txt @@ -0,0 +1 @@ +

    bob

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a.txt new file mode 100644 index 000000000..4efa161e0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-a.txt @@ -0,0 +1 @@ +

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b-expected.txt new file mode 100644 index 000000000..d6969d5f6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b-expected.txt @@ -0,0 +1 @@ +
    bob
    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b.txt new file mode 100644 index 000000000..0eb6deb5e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/plates/sample-b.txt @@ -0,0 +1 @@ +
    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-a.txt new file mode 100644 index 000000000..b015881bb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-a.txt @@ -0,0 +1 @@ +

    <%= user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-b.txt new file mode 100644 index 000000000..a55afc518 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/qejs/sample-b.txt @@ -0,0 +1 @@ +<%= user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a-expected.txt new file mode 100644 index 000000000..6ddc7781e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a-expected.txt @@ -0,0 +1,8 @@ +table { + border: none;} +table tr { + background: #fff;} +table tr { + font-size: 15px;} +table tr:odd { + background: #000;} diff --git a/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a.txt new file mode 100644 index 000000000..a27a945e2 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-a.txt @@ -0,0 +1,11 @@ ++large + :font-size 15px ++striped + tr + :background #fff + +large + &:odd + :background #000 +table + +striped + :border none \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b-expected.txt new file mode 100644 index 000000000..603a1552b --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b-expected.txt @@ -0,0 +1,8 @@ +table { + border: none;} +table tr { + background: #000;} +table tr { + font-size: 15px;} +table tr:odd { + background: #fff;} diff --git a/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b.txt new file mode 100644 index 000000000..0392bd669 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/sass/sample-b.txt @@ -0,0 +1,11 @@ ++large + :font-size 15px ++striped + tr + :background #000 + +large + &:odd + :background #fff +table + +striped + :border none \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a-expected.txt new file mode 100644 index 000000000..f686c1c0d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a-expected.txt @@ -0,0 +1,8 @@ +body { + font: 12px Helvetica, Arial, sans-serif; +} +a.button { + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} diff --git a/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a.txt new file mode 100644 index 000000000..f2b7d94f9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-a.txt @@ -0,0 +1,10 @@ +border-radius() + -webkit-border-radius arguments + -moz-border-radius arguments + border-radius arguments + +body + font 12px Helvetica, Arial, sans-serif + +a.button + border-radius(5px) \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b-expected.txt new file mode 100644 index 000000000..11f10bf70 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b-expected.txt @@ -0,0 +1,8 @@ +body { + font: 20px Helvetica, Arial, sans-serif; +} +a.button { + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} diff --git a/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b.txt new file mode 100644 index 000000000..a2d03c2b6 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/stylus/sample-b.txt @@ -0,0 +1,10 @@ +border-radius() + -webkit-border-radius arguments + -moz-border-radius arguments + border-radius arguments + +body + font 20px Helvetica, Arial, sans-serif + +a.button + border-radius(5px) \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/swig/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/swig/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/swig/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/swig/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/swig/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/swig/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-a.txt new file mode 100644 index 000000000..f5b9962c5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-a.txt @@ -0,0 +1 @@ +

    {{user.name}}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-b.txt new file mode 100644 index 000000000..3dcaa580a --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/templayed/sample-b.txt @@ -0,0 +1 @@ +{{user.name}} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-a.txt new file mode 100644 index 000000000..04b1781b9 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-a.txt @@ -0,0 +1 @@ +

    #{user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-b.txt new file mode 100644 index 000000000..76eedd8b8 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/toffee/sample-b.txt @@ -0,0 +1 @@ +#{user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a-expected.txt new file mode 100644 index 000000000..bf80f1eab --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a-expected.txt @@ -0,0 +1 @@ +tobi{name:"tobi"} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a.txt new file mode 100644 index 000000000..bac0d3ffa --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-a.txt @@ -0,0 +1,3 @@ +tobi { + name: "tobi" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b-expected.txt new file mode 100644 index 000000000..01859afbd --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b-expected.txt @@ -0,0 +1 @@ +tobi{name:"bob"} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b.txt new file mode 100644 index 000000000..e55a457f0 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-css/sample-b.txt @@ -0,0 +1,3 @@ +tobi { + name: "bob" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a-expected.txt new file mode 100644 index 000000000..9f5dd4e3d --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a-expected.txt @@ -0,0 +1 @@ +{"foo":"bar"} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a.txt new file mode 100644 index 000000000..b42f309e7 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-a.txt @@ -0,0 +1,3 @@ +{ + "foo": "bar" +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b-expected.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b-expected.txt new file mode 100644 index 000000000..3a26a2e5e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b-expected.txt @@ -0,0 +1 @@ +[1,2,3] \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b.txt new file mode 100644 index 000000000..d93030931 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/uglify-json/sample-b.txt @@ -0,0 +1,5 @@ +[ + 1, + 2, + 3 +] \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-a.txt new file mode 100644 index 000000000..a2440729f --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-a.txt @@ -0,0 +1 @@ +

    <%- user.name %>

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-b.txt new file mode 100644 index 000000000..0e320e4d5 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/underscore/sample-b.txt @@ -0,0 +1 @@ +<%- user.name %> \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-a.txt new file mode 100644 index 000000000..ba27a122e --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-a.txt @@ -0,0 +1 @@ +

    {{ user.name }}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-b.txt new file mode 100644 index 000000000..be635ff73 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/walrus/sample-b.txt @@ -0,0 +1 @@ +{{ user.name }} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-a.txt b/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-a.txt new file mode 100644 index 000000000..d2f6eeb6c --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-a.txt @@ -0,0 +1 @@ +

    {user.name}

    \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-b.txt b/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-b.txt new file mode 100644 index 000000000..d6a4beaeb --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/simple/whiskers/sample-b.txt @@ -0,0 +1 @@ +{user.name} \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/test.js b/node_modules/jade/node_modules/transformers/test/test.js new file mode 100644 index 000000000..ebca3d748 --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/test.js @@ -0,0 +1,123 @@ +var transformers = require('../'); +var fs = require('fs'); +var path = require('path'); +var expect = require('expect.js'); + +fs.readdirSync(path.join(__dirname, 'simple')) + .forEach(function (transformer) { + if (!transformers[transformer]) { + throw new Error(transformer + ' appears to be undefined.'); + } + transformer = transformers[transformer]; + function locate(name) { + return path.join(__dirname, 'simple', transformer.name, name + '.txt'); + } + function read(name) { + try { + return fs.readFileSync(locate(name)).toString(); + } catch (ex) { + return null; + } + } + describe(transformer.name, function () { + var sampleA = read('sample-a'); + var sampleAExpected = (read('sample-a-expected') || '

    bob

    ').replace(/\r/g, ''); + var sampleB = read('sample-b'); + var sampleBExpected = (read('sample-b-expected') || 'bob').replace(/\r/g, ''); + if (transformer.sync) describe('syncronous operation', testSyncronousOperation); + else describe.skip('syncronous operation', testSyncronousOperation); + function testSyncronousOperation() { + it('works from a string', function () { + expect(transformer.renderSync(sampleA, {user: {name: 'bob'}})).to.be(sampleAExpected); + expect(transformer.renderSync(sampleB, {user: {name: 'bob'}})).to.be(sampleBExpected); + }); + it('works from a file', function () { + expect(transformer.renderFileSync(locate('sample-a'), {user: {name: 'bob'}})).to.be(sampleAExpected); + expect(transformer.renderFileSync(locate('sample-b'), {user: {name: 'bob'}})).to.be(sampleBExpected); + }); + } + describe('asyncronous operation', function () { + it('works from a string A', function (done) { + transformer.render(sampleA, {user: {name: 'bob'}}, function (err, res) { + if (err) return done(err); + expect(res).to.be(sampleAExpected); + done(); + }); + }); + it('works from a string B', function (done) { + transformer.render(sampleB, {user: {name: 'bob'}}, function (err, res) { + if (err) return done(err); + expect(res).to.be(sampleBExpected); + done(); + }); + }); + it('works from a file A', function (done) { + transformer.renderFile(locate('sample-a'), {user: {name: 'bob'}}, function (err, res) { + if (err) return done(err); + expect(res).to.be(sampleAExpected); + done(); + }); + }); + it('works from a file B', function (done) { + transformer.renderFile(locate('sample-b'), {user: {name: 'bob'}}, function (err, res) { + if (err) return done(err); + expect(res).to.be(sampleBExpected); + done(); + }); + }); + }) + }); + }); + + + + function read(name) { + try { + return fs.readFileSync(locate(name)).toString(); + } catch (ex) { + return null; + } + } + + +describe('uglify-js', function () { + var str = fs.readFileSync(path.join(__dirname, 'fixtures', 'uglify-js', 'script.js')).toString(); + it('minifies files', function () { + var res = transformers['uglify-js'].renderSync(str, {}); + expect(res.length).to.be.lessThan(82); + expect(require('vm').runInNewContext(res)).to.be('Hello Forbes Lindesay!'); + }); + it('beautifies files with {mangle: false, compress: false, output: {beautify: true}}', function () { + var res = transformers['uglify-js'].renderSync(str, {mangle: false, compress: false, output: {beautify: true}}); + expect(res).to.be('(function(name) {\n function hello(world) {\n return "Hello " + world + "!";\n }\n return hello(name);\n})("Forbes Lindesay");'); + expect(require('vm').runInNewContext(res)).to.be('Hello Forbes Lindesay!'); + }); +}); + + + +describe('component', function () { + var p = path.join(__dirname, 'fixtures', 'component', 'component.json'); + var output = path.join(__dirname, 'fixtures', 'component', 'build'); + function simplifyCSS(str) { + return transformers['uglify-css'].renderSync(str); + } + describe('component-js', function () { + it('builds the JavaScript file', function (done) { + transformers['component-js'].renderFile(p, {}, function (err, res) { + if (err) return done(err); + expect(require('vm').runInNewContext(res + '\nrequire("foo")')).to.be('foo'); + done(); + }) + }); + }); + describe('component-css', function () { + it('builds the CSS file', function (done) { + transformers['component-css'].renderFile(p, {}, function (err, res) { + if (err) return done(err); + expect(simplifyCSS(res)).to.be("#foo{name:'bar'}#baz{name:'bing'}"); + done(); + }) + }); + }); +}); \ No newline at end of file diff --git a/node_modules/jade/node_modules/transformers/test/update-package.js b/node_modules/jade/node_modules/transformers/test/update-package.js new file mode 100644 index 000000000..5d6b6acbc --- /dev/null +++ b/node_modules/jade/node_modules/transformers/test/update-package.js @@ -0,0 +1,13 @@ +var transformers = require('../'); +var pack = require('../package'); +Object.keys(transformers) + .forEach(function (transformer) { + transformers[transformer].engines + .forEach(function (engine) { + if (engine != '.' && !pack.devDependencies[engine]) { + pack.devDependencies[engine] = '*'; + } + }); + }); +require('fs').writeFileSync(require('path').join(__dirname, '..', 'package.json'), + JSON.stringify(pack, null, 2)); \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/.npmignore b/node_modules/jade/node_modules/with/.npmignore new file mode 100644 index 000000000..699b5d4f1 --- /dev/null +++ b/node_modules/jade/node_modules/with/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log + +node_modules diff --git a/node_modules/jade/node_modules/with/.travis.yml b/node_modules/jade/node_modules/with/.travis.yml new file mode 100644 index 000000000..cc4dba29d --- /dev/null +++ b/node_modules/jade/node_modules/with/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/jade/node_modules/with/README.md b/node_modules/jade/node_modules/with/README.md new file mode 100644 index 000000000..21e486596 --- /dev/null +++ b/node_modules/jade/node_modules/with/README.md @@ -0,0 +1,55 @@ +# with + +Compile time `with` for strict mode JavaScript + +[![build status](https://secure.travis-ci.org/ForbesLindesay/with.png)](http://travis-ci.org/ForbesLindesay/with) +[![Dependency Status](https://gemnasium.com/ForbesLindesay/with.png)](https://gemnasium.com/ForbesLindesay/with) +[![NPM version](https://badge.fury.io/js/with.png)](http://badge.fury.io/js/with) + +## Installation + + $ npm install with + +## Usage + +```js +var addWith = require('with') + +addWith('obj', 'console.log(a)') +// => "var a = obj.a;console.log(a)" + +addWith("obj || {}", "console.log(helper(a))", ["helper"]) +// => var locals = (obj || {}),a = locals.a;console.log(helper(a)) +``` + +## API + +### addWith(obj, src, [exclude]) + +The idea is that this is roughly equivallent to: + +```js +with (obj) { + src +} +``` + +There are a few differences though. For starters, it will be assumed that all variables used in `src` come from `obj` so any that don't (e.g. template helpers) need to have their names parsed to `exclude` as an array. + +It also makes everything be declared, so you can always do: + +```js +if (foo === undefined) +``` + +instead of + +```js +if (typeof foo === 'undefined') +``` + +It is also safe to use in strict mode (unlike `with`) and it minifies properly (`with` disables virtually all minification). + +## License + + MIT \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/index.js b/node_modules/jade/node_modules/with/index.js new file mode 100644 index 000000000..a2565fd8c --- /dev/null +++ b/node_modules/jade/node_modules/with/index.js @@ -0,0 +1,31 @@ +var scope = require('lexical-scope') + +module.exports = addWith + +function addWith(obj, src, exclude) { + exclude = exclude || [] + var objScope = scope(obj) + exclude = exclude.concat(objScope.globals.implicit).concat(objScope.globals.exported) + var s = scope('(function () {' + src + '}())')//allows the `return` keyword + var vars = s.globals.implicit + .filter(function (v) { + return !(v in global) && exclude.indexOf(v) === -1 + }) + + if (vars.length === 0) return src + + var declareLocal = '' + var local = 'locals' + if (/^[a-zA-Z0-9$_]+$/.test(obj)) { + local = obj + } else { + while (s.globals.implicit.indexOf(local) != -1 || s.globals.exported.indexOf(local) != -1 || exclude.indexOf(local) != -1 || obj.indexOf(local) != -1) { + local += '_' + } + declareLocal = local + ' = (' + obj + '),' + } + return 'var ' + declareLocal + vars + .map(function (v) { + return v + ' = ' + local + '.' + v + }).join(',') + ';' + src +} \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/.travis.yml b/node_modules/jade/node_modules/with/node_modules/lexical-scope/.travis.yml new file mode 100644 index 000000000..09d3ef378 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - 0.10 diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/LICENSE b/node_modules/jade/node_modules/with/node_modules/lexical-scope/LICENSE new file mode 100644 index 000000000..ee27ba4b4 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/jquery.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/jquery.js new file mode 100644 index 000000000..198b3ff07 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.1 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
    a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
    "+""+"
    ",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
    t
    ",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
    ",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; +f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

    ";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
    ";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
    ","
    "]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() +{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
    ").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/results.txt b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/results.txt new file mode 100644 index 000000000..2a68ff8dd --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/results.txt @@ -0,0 +1,15 @@ +$ git log|head -n1 +commit ae85dfd4cc0284679ce21bb662427340fa966666 +$ time node run.js >/dev/null + +real 0m6.551s +user 0m6.336s +sys 0m0.288s + +$ git log|head -n1 +commit 9125bf1ec0cf78c77a852e0547a4cc69db7797bf +$ time node run.js>/dev/null + +real 0m1.702s +user 0m1.644s +sys 0m0.084s diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/run.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/run.js new file mode 100644 index 000000000..3c0ca0615 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/bench/run.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/jquery.js'); + +var scope = detect(src); +console.dir(scope); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/detect.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/detect.js new file mode 100644 index 000000000..7b98e4884 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/detect.js @@ -0,0 +1,6 @@ +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/src.js'); + +var scope = detect(src); +console.dir(scope); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/src.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/src.js new file mode 100644 index 000000000..ff45a9225 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/example/src.js @@ -0,0 +1,27 @@ +var x = 5; +var y = 3, z = 2; + +w.foo(); +w = 2; + +RAWR=444; +RAWR.foo(); + +BLARG=3; + +foo(function () { + var BAR = 3; + process.nextTick(function (ZZZZZZZZZZZZ) { + console.log('beep boop'); + var xyz = 4; + x += 10; + x.zzzzzz; + ZZZ=6; + }); + function doom () { + } + ZZZ.foo(); + +}); + +console.log(xyz); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/index.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/index.js new file mode 100644 index 000000000..7ee779895 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/index.js @@ -0,0 +1,161 @@ +var astw = require('astw'); + +module.exports = function (src) { + var locals = {}; + var implicit = {}; + var exported = {}; + + src = String(src).replace(/^#![^\n]*\n/, ''); + var walk = astw(src); + + walk(function (node) { + if (node.type === 'VariableDeclaration') { + // take off the leading `var ` + var id = getScope(node); + for (var i = 0; i < node.declarations.length; i++) { + var d = node.declarations[i]; + locals[id][d.id.name] = d; + } + } + else if (isFunction(node)) { + var id = getScope(node.parent); + if (node.id) locals[id][node.id.name] = node; + var nid = node.params.length && getScope(node); + if (nid && !locals[nid]) locals[nid] = {}; + for (var i = 0; i < node.params.length; i++) { + var p = node.params[i]; + locals[nid][p.name] = p; + } + } + }); + + walk(function (node) { + if (node.type === 'Identifier' + && lookup(node) === undefined) { + if (node.parent.type === 'Property' + && node.parent.key === node) return; + if (node.parent.type === 'MemberExpression' + && node.parent.property === node) return; + if (isFunction(node.parent)) return; + + if (node.parent.type === 'AssignmentExpression') { + var isLeft0 = node.parent.left.type === 'MemberExpression' + && node.parent.left.object === node.name + ; + var isLeft1 = node.parent.left.type === 'Identifier' + && node.parent.left.name === node.name + ; + if (isLeft0 || isLeft1) { + exported[node.name] = keyOf(node).length; + } + } + if (!exported[node.name] + || exported[node.name] < keyOf(node).length) { + implicit[node.name] = keyOf(node).length; + } + } + }); + + var localScopes = {}; + var lks = objectKeys(locals); + for (var i = 0; i < lks.length; i++) { + var key = lks[i]; + localScopes[key] = objectKeys(locals[key]); + } + + return { + locals: localScopes, + globals: { + implicit: objectKeys(implicit), + exported: objectKeys(exported) + } + }; + + function lookup (node) { + for (var p = node; p; p = p.parent) { + if (isFunction(p) || p.type === 'Program') { + var id = getScope(p); + if (locals[id][node.name]) { + return id; + } + } + } + return undefined; + } + + function getScope (node) { + for ( + var p = node; + !isFunction(p) && p.type !== 'Program'; + p = p.parent + ); + var id = idOf(p); + if (!locals[id]) locals[id] = {}; + return id; + } + +}; + +function isFunction (x) { + return x.type === 'FunctionDeclaration' + || x.type === 'FunctionExpression' + ; +} + +function idOf (node) { + var id = []; + for (var n = node; n.type !== 'Program'; n = n.parent) { + var key = keyOf(n).join('.'); + id.unshift(key); + } + return id.join('.'); +} + +function keyOf (node) { + var p = node.parent; + var ks = objectKeys(p); + var kv = { keys : [], values : [], top : [] }; + + for (var i = 0; i < ks.length; i++) { + var key = ks[i]; + kv.keys.push(key); + kv.values.push(p[key]); + kv.top.push(undefined); + + if (isArray(p[key])) { + var keys = objectKeys(p[key]); + kv.keys.push.apply(kv.keys, keys); + kv.values.push.apply(kv.values, p[key]); + + var nkeys = []; + for (var j = 0; j < keys.length; j++) nkeys.push(key); + kv.top.push.apply(kv.top, nkeys); + } + } + var ix = indexOf(kv.values, node); + var res = []; + if (kv.top[ix]) res.push(kv.top[ix]); + if (kv.keys[ix]) res.push(kv.keys[ix]); + if (node.parent.type === 'CallExpression') { + res.unshift.apply(res, keyOf(node.parent.parent)); + } + return res; +} + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; + +function indexOf (xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (x === xs[i]) return i; + } + return -1; +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/.travis.yml b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/.travis.yml new file mode 100644 index 000000000..ed178f635 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - 0.9 diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/LICENSE b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/LICENSE new file mode 100644 index 000000000..ee27ba4b4 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/example/types.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/example/types.js new file mode 100644 index 000000000..08cbe28e6 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/example/types.js @@ -0,0 +1,8 @@ +var astw = require('../'); +var deparse = require('escodegen').generate; +var walk = astw('4 + beep(5 * 2)'); + +walk(function (node) { + var src = deparse(node); + console.log(node.type + ' :: ' + JSON.stringify(src)); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/index.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/index.js new file mode 100644 index 000000000..4d71a1f7f --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/index.js @@ -0,0 +1,42 @@ +var parse = require('esprima').parse; + +module.exports = function (src) { + var ast = typeof src === 'string' ? parse(src) : src; + return function (cb) { + walk(ast, undefined, cb); + }; +}; + +function walk (node, parent, cb) { + var keys = objectKeys(node); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key === 'parent') continue; + + var child = node[key]; + if (isArray(child)) { + for (var j = 0; j < child.length; j++) { + var c = child[j]; + if (c && typeof c.type === 'string') { + c.parent = node; + walk(c, node, cb); + } + } + } + else if (child && typeof child.type === 'string') { + child.parent = node; + walk(child, node, cb); + } + } + cb(node); +} + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse new file mode 100644 index 000000000..2b5398f83 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@" + ret=$? +else + node "$basedir/../esprima/bin/esparse.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse.cmd b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse.cmd new file mode 100644 index 000000000..0bc3f650c --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esparse.cmd @@ -0,0 +1,5 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\esprima\bin\esparse.js" %* +) ELSE ( + node "%~dp0\..\esprima\bin\esparse.js" %* +) \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate new file mode 100644 index 000000000..6d6df8a27 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@" + ret=$? +else + node "$basedir/../esprima/bin/esvalidate.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate.cmd b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate.cmd new file mode 100644 index 000000000..b8ec59210 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/.bin/esvalidate.cmd @@ -0,0 +1,5 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\esprima\bin\esvalidate.js" %* +) ELSE ( + node "%~dp0\..\esprima\bin\esvalidate.js" %* +) \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/.npmignore b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/.npmignore new file mode 100644 index 000000000..88dc4e812 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/.npmignore @@ -0,0 +1,8 @@ +.git +.travis.yml +/node_modules/ +/assets/ +/coverage/ +/demo/ +/test/3rdparty +/tools/ diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/ChangeLog b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/ChangeLog new file mode 100644 index 000000000..86c73feec --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/ChangeLog @@ -0,0 +1,18 @@ +2012-11-05: Version 1.0.2 + + Improvements: + + * Fix esvalidate's JUnit output for exception error (issue 374) + * Allow npm installation with test (npat=true) + +2012-10-28: Version 1.0.1 + + Improvements: + + * esvalidate understands shebang in a Unix shell script (issue 361) + * esvalidate treats fatal parsing failure as an error (issue 361) + * Reduce Node.js package via .npmignore (issue 362) + +2012-10-22: Version 1.0.0 + + Initial release. diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/LICENSE.BSD b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/LICENSE.BSD new file mode 100644 index 000000000..3e580c355 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL 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. diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/README.md b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/README.md new file mode 100644 index 000000000..a74bd12d6 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/README.md @@ -0,0 +1,73 @@ +**Esprima** ([esprima.org](http://esprima.org)) is a high performance, +standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +parser written in ECMAScript (also popularly known as +[JavaScript](http://en.wikipedia.org/wiki/JavaScript>JavaScript)). +Esprima is created and maintained by [Ariya Hidayat](http://twitter.com/ariyahidayat), +with the help of [many contributors](https://github.com/ariya/esprima/contributors). + +Esprima runs on web browsers (IE 6+, Firefox 1+, Safari 3+, Chrome 1+, Konqueror 4.6+, Opera 8+) as well as +[Node.js](http://nodejs.org). + +### Features + +- Full support for [ECMAScript 5.1](http://www.ecma-international.org/publications/standards/Ecma-262.htm)(ECMA-262) +- Sensible [syntax tree format](http://esprima.org/doc/index.html#ast) compatible with Mozilla +[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API) +- Heavily tested (> 550 [unit tests](http://esprima.org/test/) with solid 100% statement coverage) +- Optional tracking of syntax node location (index-based and line-column) +- Experimental support for ES6/Harmony (module, class, destructuring, ...) + +Esprima is blazing fast (see the [benchmark suite](http://esprima.org/test/benchmarks.html)). +It is up to 3x faster than UglifyJS v1 and it is still [competitive](http://esprima.org/test/compare.html) +with the new generation of fast parsers. + +### Applications + +Esprima serves as the basis for many popular JavaScript development tools: + +- Code coverage analysis: [node-cover](https://github.com/itay/node-cover), [Istanbul](https://github.com/yahoo/Istanbul) +- Documentation tool: [JFDoc](https://github.com/thejohnfreeman/jfdoc), [JSDuck](https://github.com/senchalabs/jsduck) +- Language extension: [LLJS](http://mbebenita.github.com/LLJS/) (low-level JS), +[Sweet.js](http://sweetjs.org/) (macro) +- ES6/Harmony transpiler: [Six](https://github.com/matthewrobb/six), [Harmonizr](https://github.com/jdiamond/harmonizr) +- Eclipse Orion smart editing ([outline view](https://github.com/aclement/esprima-outline), [content assist](http://contraptionsforprogramming.blogspot.com/2012/02/better-javascript-content-assist-in.html)) +- Source code modification: [Esmorph](https://github.com/ariya/esmorph), [Code Painter](https://github.com/fawek/codepainter), +- Source transformation: [node-falafel](https://github.com/substack/node-falafel), [Esmangle](https://github.com/Constellation/esmangle), [escodegen](https://github.com/Constellation/escodegen) + +### Questions? +- [Documentation](http://esprima.org/doc) +- [Issue tracker](http://issues.esprima.org): [known problems](http://code.google.com/p/esprima/issues/list?q=Defect) +and [future plans](http://code.google.com/p/esprima/issues/list?q=Enhancement) +- [Mailing list](http://groups.google.com/group/esprima) +- [Contribution guide](http://esprima.org/doc/index.html#contribution) + +Follow [@Esprima](http://twitter.com/Esprima) on Twitter to get the +development updates. +Feedback and contribution are welcomed! + +### License + +Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) + and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL 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. + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esparse.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esparse.js new file mode 100644 index 000000000..3e7bb81ea --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esparse.js @@ -0,0 +1,117 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, esprima, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = esprima.parse(content, options); + console.log(JSON.stringify(syntax, null, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esvalidate.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esvalidate.js new file mode 100644 index 000000000..e0af3f705 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/bin/esvalidate.js @@ -0,0 +1,177 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ + +var fs, esprima, options, fnames, count; + +if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = esprima.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/component.json b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/component.json new file mode 100644 index 000000000..ca85b4593 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/component.json @@ -0,0 +1,14 @@ +{ + "name": "esprima", + "version": "1.0.2", + "main": "./esprima.js", + "dependencies": {}, + "repository": { + "type": "git", + "url": "http://github.com/ariya/esprima.git" + }, + "licenses": [{ + "type": "BSD", + "url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD" + }] +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/doc/index.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/doc/index.html new file mode 100644 index 000000000..921f77f6f --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/doc/index.html @@ -0,0 +1,473 @@ + + + + +Esprima Documentation + + + + + + + +
    + + + +

    Esprima Documentation

    + +
    + +

    Basic Usage

    + +

    Esprima runs on web browsers (IE 6+, Firefox 1+, Safari 3+, Chrome 1+, Konqueror 4.6+, Opera 8+) as well as +Rhino and Node.js.

    + +

    In a web browser

    + +

    Just include the source file:

    + +
    +<script src="esparse.js"></script>
    +
    + +

    The module esprima will be available as part of the global window object:

    + +
    +var syntax = esprima.parse('var answer = 42');
    +
    + +

    Since Esprima supports AMD (Asynchronous Module Definition), it can be loaded via a module loader such as RequireJS:

    + +
    +require(['esprima'], function (parser) {
    +    // Do something with parser, e.g.
    +    var syntax = parser.parse('var answer = 42');
    +    console.log(JSON.stringify(syntax, null, 4));
    +});
    +
    + +

    Since Esprima is available as a Bower component, it can be installed with:

    + +
    +bower install esprima
    +
    + +

    Obviously, it can be used with Yeoman as well:

    + +
    +yeoman install esprima
    +
    + +

    With Node.js

    + +

    Esprima is available as a Node.js package, install it using npm:

    + +
    +npm install esprima
    +
    + +

    Load the module with require and use it:

    + +
    +var esprima = require('esprima');
    +console.log(JSON.stringify(esprima.parse('var answer = 42'), null, 4));
    +
    + +

    With Rhino

    + +

    Load the source file from another script:

    + +
    +load('/path/to/esprima.js');
    +
    + +

    The module esprima will be available as part of the global object:

    + +
    +var syntax = esprima.parse('42');
    +print(JSON.stringify(syntax, null, 2));
    +
    + +

    Parsing Interface

    + +

    Basic usage: + +

    +esprima.parse(code, options);
    +
    + +

    The output of the parser is the syntax tree formatted in JSON, see the following Syntax Tree Format section.

    + +

    Available options so far (by default, every option false):

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionWhen set to true
    locNodes have line and column-based location info
    rangeNodes have an index-based location range (array)
    rawLiterals have extra property which stores the verbatim source
    tokensAn extra array containing all found tokens
    commentAn extra array containing all line and block comments
    + + +

    The easiest way to see the different output based on various option settings is to use the online parser demo. + +

    Examples

    + +

    Detect Nested Ternary Conditionals

    + +

    The script detectnestedternary.js in the examples/ subdirectory is using Esprima to look for a ternary conditional, i.e. operator ?:, which is immediately followed (in one of its code paths) by another ternary conditional. The script can be invoked from the command-line with Node.js:

    + +
    +node detectnestedternary.js /some/path
    +
    + +

    An example code fragment which will be flagged by this script as having a nested ternary conditional:

    + +
    +var str = (age < 1) ? "baby" :
    +    (age < 5) ? "toddler" :
    +    (age < 18) ? "child": "adult";
    +
    + +

    which will yield the following report:

    + +
    +  Line 1 : Nested ternary for "age < 1"
    +  Line 2 : Nested ternary for "age < 5"
    +
    + +

    Find Possible Boolean Traps

    + +

    The script findbooleantrap.js in the examples/ subdirectory is using Esprima to detect some possible cases of Boolean trap, i.e. the use of Boolean literal which may lead to ambiguities and lack of readability. The script can be invoked from command-line with Node.js:

    + +
    +node findbooleantrap.js /some/path
    +
    + +It will search for all files (recursively) in the given path, try to parse each file, and then look for signs of Boolean traps: + +
      +
    • Literal used with a non-setter function (assumption: setter starts with the "set" prefix):
    • +
      this.refresh(true);
      +
    • Literal used with a function whose name may have a double-negative interpretation:
    • +
      item.setHidden(false);
      +
    • Two different literals in a single function call:
    • +
      element.stop(true, false);
      +
    • Multiple literals in a single function invocation:
    • +
      event.initKeyEvent("keypress", true, true, null, null,
      +    false, false, false, false, 9, 0);
      +
    • Ambiguous Boolean literal as the last argument:
    • +
      return getSomething(obj, false);
      +
    + +For some more info, read also the blog post on Boolean trap. + +

    Syntax Tree Format

    + +

    The output of the parser is expected to be compatible with Mozilla SpiderMonkey Parser API. +The best way to understand various different constructs is the online parser demo which shows the syntax tree (formatted with JSON.stringify) corresponding to the typed code. + +The simplest example is as follows. If the following code is executed: + +

    +esprima.parse('var answer = 42;');
    +
    + +then the return value will be (JSON formatted): + +
    +{
    +    type: 'Program',
    +    body: [
    +        {
    +            type: 'VariableDeclaration',
    +            declarations: [
    +                {
    +                    type: 'AssignmentExpression',
    +                    operator: =,
    +                    left: {
    +                        type: 'Identifier',
    +                        name: 'answer'
    +                    },
    +                    right: {
    +                        type: 'Literal',
    +                        value: 42
    +                    }
    +                }
    +            ]
    +        }
    +    ]
    +}
    +
    + +

    Contribution Guide

    + +

    Guidelines

    + +

    Contributors are mandated to follow the guides described in the following sections. Any contribution which do not conform to the guides may be rejected.

    + +

    Laundry list

    + +

    Before creating pull requests, make sure the following applies.

    + +

    There is a corresponding issue. If there is no issue yet, create one in the issue tracker.

    + +

    The commit log links the corresponding issue (usually as the last line).

    + +

    No functional regression. Run all unit tests.

    + +

    No coverage regression. Run the code coverage analysis.

    + +

    Each commit must be granular. Big changes should be splitted into smaller commits.

    + +

    Write understandable code. No need to be too terse (or even obfuscated).

    + +

    JSLint does not complain.

    + +

    A new feature must be accompanied with unit tests. No compromise.

    + +

    A new feature should not cause performance loss. Verify with the benchmark tests.

    + +

    Performance improvement should be backed up by actual conclusive speed-up in the benchmark suite.

    + +

    Coding style

    + +

    Indentation is 4 spaces.

    + +

    Open curly brace is at the end of the line.

    + +

    String literal uses single quote (') and not double quote (").

    + +

    Commit message

    + +

    Bad:

    + +
    +    Fix a problem with Firefox.
    +
    + +

    The above commit is too short and useless in the long term.

    + +

    Good:

    + +
    +    Add support for labeled statement.
    +
    +    It is covered in ECMAScript Language Specification Section 12.12.
    +    This also fixes parsing MooTools and JSLint code.
    +
    +    Running the benchmarks suite show negligible performance loss.
    +
    +    http://code.google.com/p/esprima/issues/detail?id=10
    +    http://code.google.com/p/esprima/issues/detail?id=15
    +    http://code.google.com/p/esprima/issues/detail?id=16
    +
    + +

    Important aspects:

    + +
      +
    • The first line is the short description, useful for per-line commit view and thus keep it under 80 characters.
    • +
    • The next paragraphs should provide more explanation (if needed).
    • +
    • Describe the testing situation (new unit/benchmark test, change in performance, etc).
    • +
    • Put the link to the issues for cross-ref.
    • +
    + +

    Baseline syntax tree as the expected result

    + +

    The test suite contains a collection of a pair of code and its syntax tree. To generate the syntax tree suitably formatted for the test fixture, use the included helper script tools/generate-test-fixture.js (with Node.js), e.g.: + +

    +node tools/generate-test-fixture.js "var answer = 42"
    +
    + +The syntax tree will be printed out to the console. This can be used in the test fixture. + +

    Test Workflow

    + +

    Unit tests

    + +

    Browser-based unit testing is available by opening test/index.html in the source tree. The online version is esprima.org/test.

    + +

    Command-line testing using Node.js:

    + +
    npm test
    + +

    Code coverage test

    + +

    Note: you need to use Node.js 0.6 or later version.

    + +

    Install node-cover:

    + +
    sudo npm install -g cover
    + +

    Run it in Esprima source tree:

    + +
    cover run test/runner.js
    + +

    Check the quick report:

    + +
    cover report
    + +

    To get the detailed report:

    + +
    cover report html
    + +

    and then open cover_html/index.html file and choose esprima.js from the list.

    + +

    Benchmark tests

    + +

    Available by opening test/benchmarks.html in the source tree. The online version is esprima.org/test/benchmarks.html.

    + +

    Note: Because the corpus is fetched via XML HTTP Request, the benchmarks test needs to be served via a web server and not local file.

    + +

    It is important to run this with various browsers to cover different JavaScript engines.

    + +

    Command-line benchmark using Node.js:

    + +
    node test/benchmark.js
    + +

    Command-line benchmark using V8 shell:

    + +
    /path/to/v8/shell test/benchmark.js
    + +

    The current corpus for the benchmarks:

    + +
      +
    • jQuery (version 1.7.1 and 1.6.4)
    • +
    • jQuery Mobile (version 1.0)
    • +
    • Prototype (version 1.7.0.0 and 1.6.1)
    • +
    • Ext Core (version 3.1.0 and 3.0.0)
    • +
    • MooTools (version 1.4.1 and 1.3.2)
    • +
    • Backbone (version 0.5.3)
    • +
    • Underscore (version 1.2.3)
    • +
    + +

    Speed comparison tests

    + +

    Available by opening test/compare.html. The online version is esprima.org/test/compare.html.

    + +

    Note: Because the corpus is fetched via XML HTTP Request, the benchmarks test needs to be served via a web server and not local file.

    + +

    Warning: Since each parser has a different format for the syntax tree, the speed is not fully comparable (the cost of constructing different result is not taken into account). These tests exist only to ensure that Esprima parser is not ridiculously slow, e.g. one magnitude slower compare to other parsers.

    + +

    The current corpus for the speed comparison tests:

    + +
      +
    • jQuery version 1.7.1
    • +
    • Prototype version 1.7.0.0
    • +
    • MooTools version 1.4.1
    • +
    • Ext Core version 3.1.0
    • +
    + +

    Manual tests

    + +

    Code parser

    + +

    Available by opening demo/parse.html. + +

    In this demo, whatever is typed in the editor will be parsed. If it is a valid code, the syntax tree will be shown formatted using JSON.stringify.

    + +

    Operator precedence

    + +

    Available by opening demo/precedence.html. + +

    The demo compares two expression and decides whether they are semantically equivalent or not. If not, the expression will be rewritten, with extra parentheses, to following the intended semantic of the original.

    + +

    Regular expression collector

    + +

    Available by opening demo/collector.html. + +

    The demo finds all the regular expressions in the given code, along with the location for each regular expression.

    + +

    Function tracing

    + +

    Available by opening demo/functiontrace.html. + +

    The demo inserts a function call at the beginning of every function block to log the number of times the function is executed.

    + + + +

    Sister projects

    + +

    Escodegen is a code generator which supports Esprima syntax tree. This is useful for source code transformation. The source can be parsed by Esprima and then regenerated using escodegen. Between the process, the syntax tree can be transformed.

    + +

    Esmorph is a non-destructive source code morphing tool. It can tweak portions of the code without affecting the rest (hence the term non-destructive).

    + +

    Similar parsers

    + +

    Narcissus is a metacircular implementation of JavaScript. Obviously it has a parsing capability. Check more at the code repo: github.com/mozilla/narcissus. Narcissus is likely the oldest JavaScript parser written in JavaScript.

    + +

    UglifyJS is a minifier and obfuscator which has a parser called parse-js. It is pretty popular and widely used. Read more at its project page: github.com/mishoo/UglifyJS.

    + +

    ZeParser, see github.com/qfox/ZeParser.

    + +

    License

    + +

    Copyright (C) 2012, 2011 Ariya Hidayat and other contributors.

    + +

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    +
      +
    • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    • +
    • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    • +
    + +

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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.

    + + + + + + + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/esprima.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/esprima.js new file mode 100644 index 000000000..9f77a4583 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/esprima.js @@ -0,0 +1,3895 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint bitwise:true plusplus:true */ +/*global esprima:true, define:true, exports:true, window: true, +throwError: true, createLiteral: true, generateStatement: true, +parseAssignmentExpression: true, parseBlock: true, parseExpression: true, +parseFunctionDeclaration: true, parseFunctionExpression: true, +parseFunctionSourceElements: true, parseVariableIdentifier: true, +parseLeftHandSideExpression: true, +parseStatement: true, parseSourceElement: true */ + +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // Rhino, and plain browser loading. + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.esprima = {})); + } +}(this, function (exports) { + 'use strict'; + + var Token, + TokenName, + Syntax, + PropertyKind, + Messages, + Regex, + source, + strict, + index, + lineNumber, + lineStart, + length, + buffer, + state, + extra; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8 + }; + + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + }; + + PropertyKind = { + Data: 1, + Get: 2, + Set: 4 + }; + + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', + AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', + AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode' + }; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\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\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\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-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\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-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\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-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\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]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\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\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\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\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + + function sliceSource(from, to) { + return source.slice(from, to); + } + + if (typeof 'esprima'[0] === 'undefined') { + sliceSource = function sliceArraySource(from, to) { + return source.slice(from, to).join(''); + }; + } + + function isDecimalDigit(ch) { + return '0123456789'.indexOf(ch) >= 0; + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + + // 7.2 White Space + + function isWhiteSpace(ch) { + return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || + (ch === '\u000C') || (ch === '\u00A0') || + (ch.charCodeAt(0) >= 0x1680 && + '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); + } + + function isIdentifierPart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch >= '0') && (ch <= '9')) || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + + // Future reserved words. + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + } + + return false; + } + + function isStrictModeReservedWord(id) { + switch (id) { + + // Strict Mode reserved words. + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + } + + return false; + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + var keyword = false; + switch (id.length) { + case 2: + keyword = (id === 'if') || (id === 'in') || (id === 'do'); + break; + case 3: + keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + break; + case 4: + keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with'); + break; + case 5: + keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw'); + break; + case 6: + keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch'); + break; + case 7: + keyword = (id === 'default') || (id === 'finally'); + break; + case 8: + keyword = (id === 'function') || (id === 'continue') || (id === 'debugger'); + break; + case 10: + keyword = (id === 'instanceof'); + break; + } + + if (keyword) { + return true; + } + + switch (id) { + // Future reserved words. + // 'const' is specialized as Keyword in V8. + case 'const': + return true; + + // For compatiblity to SpiderMonkey and ES.next + case 'yield': + case 'let': + return true; + } + + if (strict && isStrictModeReservedWord(id)) { + return true; + } + + return isFutureReservedWord(id); + } + + // 7.4 Comments + + function skipComment() { + var ch, blockComment, lineComment; + + blockComment = false; + lineComment = false; + + while (index < length) { + ch = source[index]; + + if (lineComment) { + ch = source[index++]; + if (isLineTerminator(ch)) { + lineComment = false; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } + } else if (blockComment) { + if (isLineTerminator(ch)) { + if (ch === '\r' && source[index + 1] === '\n') { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + ch = source[index++]; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + if (ch === '*') { + ch = source[index]; + if (ch === '/') { + ++index; + blockComment = false; + } + } + } + } else if (ch === '/') { + ch = source[index + 1]; + if (ch === '/') { + index += 2; + lineComment = true; + } else if (ch === '*') { + index += 2; + blockComment = true; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } else { + break; + } + } + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanIdentifier() { + var ch, start, id, restore; + + ch = source[index]; + if (!isIdentifierStart(ch)) { + return; + } + + start = index; + if (ch === '\\') { + ++index; + if (source[index] !== 'u') { + return; + } + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + if (ch === '\\' || !isIdentifierStart(ch)) { + return; + } + id = ch; + } else { + index = restore; + id = 'u'; + } + } else { + id = source[index++]; + } + + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch)) { + break; + } + if (ch === '\\') { + ++index; + if (source[index] !== 'u') { + return; + } + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + if (ch === '\\' || !isIdentifierPart(ch)) { + return; + } + id += ch; + } else { + index = restore; + id += 'u'; + } + } else { + id += source[index++]; + } + } + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + return { + type: Token.Identifier, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (isKeyword(id)) { + return { + type: Token.Keyword, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.1 Null Literals + + if (id === 'null') { + return { + type: Token.NullLiteral, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.2 Boolean Literals + + if (id === 'true' || id === 'false') { + return { + type: Token.BooleanLiteral, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + return { + type: Token.Identifier, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.7 Punctuators + + function scanPunctuator() { + var start = index, + ch1 = source[index], + ch2, + ch3, + ch4; + + // Check for most common single-character punctuators. + + if (ch1 === ';' || ch1 === '{' || ch1 === '}') { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === ',' || ch1 === '(' || ch1 === ')') { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // Dot (.) can also start a floating-point number, hence the need + // to check the next character. + + ch2 = source[index + 1]; + if (ch1 === '.' && !isDecimalDigit(ch2)) { + return { + type: Token.Punctuator, + value: source[index++], + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // Peek more characters. + + ch3 = source[index + 2]; + ch4 = source[index + 3]; + + // 4-character punctuator: >>>= + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + if (ch4 === '=') { + index += 4; + return { + type: Token.Punctuator, + value: '>>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // 3-character punctuators: === !== >>> <<= >>= + + if (ch1 === '=' && ch2 === '=' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '===', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '!' && ch2 === '=' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '!==', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + index += 3; + return { + type: Token.Punctuator, + value: '>>>', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '<' && ch2 === '<' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '<<=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 2-character punctuators: <= >= == != ++ -- << >> && || + // += -= *= %= &= |= ^= /= + + if (ch2 === '=') { + if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { + if ('+-<>&|'.indexOf(ch2) >= 0) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // The remaining 1-character punctuators. + + if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) { + return { + type: Token.Punctuator, + value: source[index++], + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // 7.8.3 Numeric Literals + + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = source[index++]; + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + number += source[index++]; + while (index < length) { + ch = source[index]; + if (!isHexDigit(ch)) { + break; + } + number += source[index++]; + } + + if (number.length <= 2) { + // only 0x + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + return { + type: Token.NumericLiteral, + value: parseInt(number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } else if (isOctalDigit(ch)) { + number += source[index++]; + while (index < length) { + ch = source[index]; + if (!isOctalDigit(ch)) { + break; + } + number += source[index++]; + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: true, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // decimal number starts with '0' such as '09' is illegal. + if (isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += source[index++]; + } + } + + if (ch === '.') { + number += source[index++]; + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += source[index++]; + } + } + + if (ch === 'e' || ch === 'E') { + number += source[index++]; + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += source[index++]; + } + + ch = source[index]; + if (isDecimalDigit(ch)) { + number += source[index++]; + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += source[index++]; + } + } else { + ch = 'character ' + ch; + if (index >= length) { + ch = ''; + } + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.4 String Literals + + function scanStringLiteral() { + var str = '', quote, start, ch, code, unescaped, restore, octal = false; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + while (index < length) { + ch = source[index++]; + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = source[index++]; + if (!isLineTerminator(ch)) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(source[index++]); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(source[index++]); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + } + } else if (isLineTerminator(ch)) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + function scanRegExp() { + var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false; + + buffer = null; + skipComment(); + + start = index; + ch = source[index]; + assert(ch === '/', 'Regular expression literal must start with a slash'); + str = source[index++]; + + while (index < length) { + ch = source[index++]; + str += ch; + if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } else { + if (ch === '\\') { + ch = source[index++]; + // ECMA-262 7.8.5 + if (isLineTerminator(ch)) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } else if (ch === '/') { + terminated = true; + break; + } else if (ch === '[') { + classMarker = true; + } else if (isLineTerminator(ch)) { + throwError({}, Messages.UnterminatedRegExp); + } + } + } + + if (!terminated) { + throwError({}, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + pattern = str.substr(1, str.length - 2); + + flags = ''; + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch)) { + break; + } + + ++index; + if (ch === '\\' && index < length) { + ch = source[index]; + if (ch === 'u') { + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + flags += ch; + str += '\\u'; + for (; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += 'u'; + str += '\\u'; + } + } else { + str += '\\'; + } + } else { + flags += ch; + str += ch; + } + } + + try { + value = new RegExp(pattern, flags); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } + + return { + literal: str, + value: value, + range: [start, index] + }; + } + + function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; + } + + function advance() { + var ch, token; + + skipComment(); + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + range: [index, index] + }; + } + + token = scanPunctuator(); + if (typeof token !== 'undefined') { + return token; + } + + ch = source[index]; + + if (ch === '\'' || ch === '"') { + return scanStringLiteral(); + } + + if (ch === '.' || isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + token = scanIdentifier(); + if (typeof token !== 'undefined') { + return token; + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + function lex() { + var token; + + if (buffer) { + index = buffer.range[1]; + lineNumber = buffer.lineNumber; + lineStart = buffer.lineStart; + token = buffer; + buffer = null; + return token; + } + + buffer = null; + return advance(); + } + + function lookahead() { + var pos, line, start; + + if (buffer !== null) { + return buffer; + } + + pos = index; + line = lineNumber; + start = lineStart; + buffer = advance(); + index = pos; + lineNumber = line; + lineStart = start; + + return buffer; + } + + // Return true if there is a line terminator before the next token. + + function peekLineTerminator() { + var pos, line, start, found; + + pos = index; + line = lineNumber; + start = lineStart; + skipComment(); + found = lineNumber !== line; + index = pos; + lineNumber = line; + lineStart = start; + + return found; + } + + // Throw an exception + + function throwError(token, messageFormat) { + var error, + args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function (whole, index) { + return args[index] || ''; + } + ); + + if (typeof token.lineNumber === 'number') { + error = new Error('Line ' + token.lineNumber + ': ' + msg); + error.index = token.range[0]; + error.lineNumber = token.lineNumber; + error.column = token.range[0] - lineStart + 1; + } else { + error = new Error('Line ' + lineNumber + ': ' + msg); + error.index = index; + error.lineNumber = lineNumber; + error.column = index - lineStart + 1; + } + + throw error; + } + + function throwErrorTolerant() { + try { + throwError.apply(null, arguments); + } catch (e) { + if (extra.errors) { + extra.errors.push(e); + } else { + throw e; + } + } + } + + + // Throw an exception because of the token. + + function throwUnexpected(token) { + if (token.type === Token.EOF) { + throwError(token, Messages.UnexpectedEOS); + } + + if (token.type === Token.NumericLiteral) { + throwError(token, Messages.UnexpectedNumber); + } + + if (token.type === Token.StringLiteral) { + throwError(token, Messages.UnexpectedString); + } + + if (token.type === Token.Identifier) { + throwError(token, Messages.UnexpectedIdentifier); + } + + if (token.type === Token.Keyword) { + if (isFutureReservedWord(token.value)) { + throwError(token, Messages.UnexpectedReserved); + } else if (strict && isStrictModeReservedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictReservedWord); + return; + } + throwError(token, Messages.UnexpectedToken, token.value); + } + + // BooleanLiteral, NullLiteral, or Punctuator. + throwError(token, Messages.UnexpectedToken, token.value); + } + + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + + function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpected(token); + } + } + + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + + function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpected(token); + } + } + + // Return true if the next token matches the specified punctuator. + + function match(value) { + var token = lookahead(); + return token.type === Token.Punctuator && token.value === value; + } + + // Return true if the next token matches the specified keyword + + function matchKeyword(keyword) { + var token = lookahead(); + return token.type === Token.Keyword && token.value === keyword; + } + + // Return true if the next token is an assignment operator + + function matchAssign() { + var token = lookahead(), + op = token.value; + + if (token.type !== Token.Punctuator) { + return false; + } + return op === '=' || + op === '*=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + } + + function consumeSemicolon() { + var token, line; + + // Catch the very common case first. + if (source[index] === ';') { + lex(); + return; + } + + line = lineNumber; + skipComment(); + if (lineNumber !== line) { + return; + } + + if (match(';')) { + lex(); + return; + } + + token = lookahead(); + if (token.type !== Token.EOF && !match('}')) { + throwUnexpected(token); + } + } + + // Return true if provided expression is LeftHandSideExpression + + function isLeftHandSide(expr) { + return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; + } + + // 11.1.4 Array Initialiser + + function parseArrayInitialiser() { + var elements = []; + + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(null); + } else { + elements.push(parseAssignmentExpression()); + + if (!match(']')) { + expect(','); + } + } + } + + expect(']'); + + return { + type: Syntax.ArrayExpression, + elements: elements + }; + } + + // 11.1.5 Object Initialiser + + function parsePropertyFunction(param, first) { + var previousStrict, body; + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (first && strict && isRestrictedWord(param[0].name)) { + throwErrorTolerant(first, Messages.StrictParamName); + } + strict = previousStrict; + + return { + type: Syntax.FunctionExpression, + id: null, + params: param, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }; + } + + function parseObjectPropertyKey() { + var token = lex(); + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return createLiteral(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseObjectProperty() { + var token, key, id, param; + + token = lookahead(); + + if (token.type === Token.Identifier) { + + id = parseObjectPropertyKey(); + + // Property Assignment: Getter and Setter. + + if (token.value === 'get' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + expect(')'); + return { + type: Syntax.Property, + key: key, + value: parsePropertyFunction([]), + kind: 'get' + }; + } else if (token.value === 'set' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + token = lookahead(); + if (token.type !== Token.Identifier) { + throwUnexpected(lex()); + } + param = [ parseVariableIdentifier() ]; + expect(')'); + return { + type: Syntax.Property, + key: key, + value: parsePropertyFunction(param, token), + kind: 'set' + }; + } else { + expect(':'); + return { + type: Syntax.Property, + key: id, + value: parseAssignmentExpression(), + kind: 'init' + }; + } + } else if (token.type === Token.EOF || token.type === Token.Punctuator) { + throwUnexpected(token); + } else { + key = parseObjectPropertyKey(); + expect(':'); + return { + type: Syntax.Property, + key: key, + value: parseAssignmentExpression(), + kind: 'init' + }; + } + } + + function parseObjectInitialiser() { + var properties = [], property, name, kind, map = {}, toString = String; + + expect('{'); + + while (!match('}')) { + property = parseObjectProperty(); + + if (property.key.type === Syntax.Identifier) { + name = property.key.name; + } else { + name = toString(property.key.value); + } + kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + if (Object.prototype.hasOwnProperty.call(map, name)) { + if (map[name] === PropertyKind.Data) { + if (strict && kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } else if (map[name] & kind) { + throwErrorTolerant({}, Messages.AccessorGetSet); + } + } + map[name] |= kind; + } else { + map[name] = kind; + } + + properties.push(property); + + if (!match('}')) { + expect(','); + } + } + + expect('}'); + + return { + type: Syntax.ObjectExpression, + properties: properties + }; + } + + // 11.1.6 The Grouping Operator + + function parseGroupExpression() { + var expr; + + expect('('); + + expr = parseExpression(); + + expect(')'); + + return expr; + } + + + // 11.1 Primary Expressions + + function parsePrimaryExpression() { + var token = lookahead(), + type = token.type; + + if (type === Token.Identifier) { + return { + type: Syntax.Identifier, + name: lex().value + }; + } + + if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return createLiteral(lex()); + } + + if (type === Token.Keyword) { + if (matchKeyword('this')) { + lex(); + return { + type: Syntax.ThisExpression + }; + } + + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + } + + if (type === Token.BooleanLiteral) { + lex(); + token.value = (token.value === 'true'); + return createLiteral(token); + } + + if (type === Token.NullLiteral) { + lex(); + token.value = null; + return createLiteral(token); + } + + if (match('[')) { + return parseArrayInitialiser(); + } + + if (match('{')) { + return parseObjectInitialiser(); + } + + if (match('(')) { + return parseGroupExpression(); + } + + if (match('/') || match('/=')) { + return createLiteral(scanRegExp()); + } + + return throwUnexpected(lex()); + } + + // 11.2 Left-Hand-Side Expressions + + function parseArguments() { + var args = []; + + expect('('); + + if (!match(')')) { + while (index < length) { + args.push(parseAssignmentExpression()); + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return args; + } + + function parseNonComputedProperty() { + var token = lex(); + + if (!isIdentifierName(token)) { + throwUnexpected(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseNonComputedMember() { + expect('.'); + + return parseNonComputedProperty(); + } + + function parseComputedMember() { + var expr; + + expect('['); + + expr = parseExpression(); + + expect(']'); + + return expr; + } + + function parseNewExpression() { + var expr; + + expectKeyword('new'); + + expr = { + type: Syntax.NewExpression, + callee: parseLeftHandSideExpression(), + 'arguments': [] + }; + + if (match('(')) { + expr['arguments'] = parseArguments(); + } + + return expr; + } + + function parseLeftHandSideExpressionAllowCall() { + var expr; + + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + + while (match('.') || match('[') || match('(')) { + if (match('(')) { + expr = { + type: Syntax.CallExpression, + callee: expr, + 'arguments': parseArguments() + }; + } else if (match('[')) { + expr = { + type: Syntax.MemberExpression, + computed: true, + object: expr, + property: parseComputedMember() + }; + } else { + expr = { + type: Syntax.MemberExpression, + computed: false, + object: expr, + property: parseNonComputedMember() + }; + } + } + + return expr; + } + + + function parseLeftHandSideExpression() { + var expr; + + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + + while (match('.') || match('[')) { + if (match('[')) { + expr = { + type: Syntax.MemberExpression, + computed: true, + object: expr, + property: parseComputedMember() + }; + } else { + expr = { + type: Syntax.MemberExpression, + computed: false, + object: expr, + property: parseNonComputedMember() + }; + } + } + + return expr; + } + + // 11.3 Postfix Expressions + + function parsePostfixExpression() { + var expr = parseLeftHandSideExpressionAllowCall(), token; + + token = lookahead(); + if (token.type !== Token.Punctuator) { + return expr; + } + + if ((match('++') || match('--')) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPostfix); + } + + if (!isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + expr = { + type: Syntax.UpdateExpression, + operator: lex().value, + argument: expr, + prefix: false + }; + } + + return expr; + } + + // 11.4 Unary Operators + + function parseUnaryExpression() { + var token, expr; + + token = lookahead(); + if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { + return parsePostfixExpression(); + } + + if (match('++') || match('--')) { + token = lex(); + expr = parseUnaryExpression(); + // 11.4.4, 11.4.5 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPrefix); + } + + if (!isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + expr = { + type: Syntax.UpdateExpression, + operator: token.value, + argument: expr, + prefix: true + }; + return expr; + } + + if (match('+') || match('-') || match('~') || match('!')) { + expr = { + type: Syntax.UnaryExpression, + operator: lex().value, + argument: parseUnaryExpression() + }; + return expr; + } + + if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + expr = { + type: Syntax.UnaryExpression, + operator: lex().value, + argument: parseUnaryExpression() + }; + if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { + throwErrorTolerant({}, Messages.StrictDelete); + } + return expr; + } + + return parsePostfixExpression(); + } + + // 11.5 Multiplicative Operators + + function parseMultiplicativeExpression() { + var expr = parseUnaryExpression(); + + while (match('*') || match('/') || match('%')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseUnaryExpression() + }; + } + + return expr; + } + + // 11.6 Additive Operators + + function parseAdditiveExpression() { + var expr = parseMultiplicativeExpression(); + + while (match('+') || match('-')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseMultiplicativeExpression() + }; + } + + return expr; + } + + // 11.7 Bitwise Shift Operators + + function parseShiftExpression() { + var expr = parseAdditiveExpression(); + + while (match('<<') || match('>>') || match('>>>')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseAdditiveExpression() + }; + } + + return expr; + } + // 11.8 Relational Operators + + function parseRelationalExpression() { + var expr, previousAllowIn; + + previousAllowIn = state.allowIn; + state.allowIn = true; + + expr = parseShiftExpression(); + + while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseShiftExpression() + }; + } + + state.allowIn = previousAllowIn; + return expr; + } + + // 11.9 Equality Operators + + function parseEqualityExpression() { + var expr = parseRelationalExpression(); + + while (match('==') || match('!=') || match('===') || match('!==')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseRelationalExpression() + }; + } + + return expr; + } + + // 11.10 Binary Bitwise Operators + + function parseBitwiseANDExpression() { + var expr = parseEqualityExpression(); + + while (match('&')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '&', + left: expr, + right: parseEqualityExpression() + }; + } + + return expr; + } + + function parseBitwiseXORExpression() { + var expr = parseBitwiseANDExpression(); + + while (match('^')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '^', + left: expr, + right: parseBitwiseANDExpression() + }; + } + + return expr; + } + + function parseBitwiseORExpression() { + var expr = parseBitwiseXORExpression(); + + while (match('|')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '|', + left: expr, + right: parseBitwiseXORExpression() + }; + } + + return expr; + } + + // 11.11 Binary Logical Operators + + function parseLogicalANDExpression() { + var expr = parseBitwiseORExpression(); + + while (match('&&')) { + lex(); + expr = { + type: Syntax.LogicalExpression, + operator: '&&', + left: expr, + right: parseBitwiseORExpression() + }; + } + + return expr; + } + + function parseLogicalORExpression() { + var expr = parseLogicalANDExpression(); + + while (match('||')) { + lex(); + expr = { + type: Syntax.LogicalExpression, + operator: '||', + left: expr, + right: parseLogicalANDExpression() + }; + } + + return expr; + } + + // 11.12 Conditional Operator + + function parseConditionalExpression() { + var expr, previousAllowIn, consequent; + + expr = parseLogicalORExpression(); + + if (match('?')) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = parseAssignmentExpression(); + state.allowIn = previousAllowIn; + expect(':'); + + expr = { + type: Syntax.ConditionalExpression, + test: expr, + consequent: consequent, + alternate: parseAssignmentExpression() + }; + } + + return expr; + } + + // 11.13 Assignment Operators + + function parseAssignmentExpression() { + var token, expr; + + token = lookahead(); + expr = parseConditionalExpression(); + + if (matchAssign()) { + // LeftHandSideExpression + if (!isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + // 11.13.1 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant(token, Messages.StrictLHSAssignment); + } + + expr = { + type: Syntax.AssignmentExpression, + operator: lex().value, + left: expr, + right: parseAssignmentExpression() + }; + } + + return expr; + } + + // 11.14 Comma Operator + + function parseExpression() { + var expr = parseAssignmentExpression(); + + if (match(',')) { + expr = { + type: Syntax.SequenceExpression, + expressions: [ expr ] + }; + + while (index < length) { + if (!match(',')) { + break; + } + lex(); + expr.expressions.push(parseAssignmentExpression()); + } + + } + return expr; + } + + // 12.1 Block + + function parseStatementList() { + var list = [], + statement; + + while (index < length) { + if (match('}')) { + break; + } + statement = parseSourceElement(); + if (typeof statement === 'undefined') { + break; + } + list.push(statement); + } + + return list; + } + + function parseBlock() { + var block; + + expect('{'); + + block = parseStatementList(); + + expect('}'); + + return { + type: Syntax.BlockStatement, + body: block + }; + } + + // 12.2 Variable Statement + + function parseVariableIdentifier() { + var token = lex(); + + if (token.type !== Token.Identifier) { + throwUnexpected(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseVariableDeclaration(kind) { + var id = parseVariableIdentifier(), + init = null; + + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } + + if (kind === 'const') { + expect('='); + init = parseAssignmentExpression(); + } else if (match('=')) { + lex(); + init = parseAssignmentExpression(); + } + + return { + type: Syntax.VariableDeclarator, + id: id, + init: init + }; + } + + function parseVariableDeclarationList(kind) { + var list = []; + + while (index < length) { + list.push(parseVariableDeclaration(kind)); + if (!match(',')) { + break; + } + lex(); + } + + return list; + } + + function parseVariableStatement() { + var declarations; + + expectKeyword('var'); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: 'var' + }; + } + + // kind may be `const` or `let` + // Both are experimental and not in the specification yet. + // see http://wiki.ecmascript.org/doku.php?id=harmony:const + // and http://wiki.ecmascript.org/doku.php?id=harmony:let + function parseConstLetDeclaration(kind) { + var declarations; + + expectKeyword(kind); + + declarations = parseVariableDeclarationList(kind); + + consumeSemicolon(); + + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: kind + }; + } + + // 12.3 Empty Statement + + function parseEmptyStatement() { + expect(';'); + + return { + type: Syntax.EmptyStatement + }; + } + + // 12.4 Expression Statement + + function parseExpressionStatement() { + var expr = parseExpression(); + + consumeSemicolon(); + + return { + type: Syntax.ExpressionStatement, + expression: expr + }; + } + + // 12.5 If statement + + function parseIfStatement() { + var test, consequent, alternate; + + expectKeyword('if'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + consequent = parseStatement(); + + if (matchKeyword('else')) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return { + type: Syntax.IfStatement, + test: test, + consequent: consequent, + alternate: alternate + }; + } + + // 12.6 Iteration Statements + + function parseDoWhileStatement() { + var body, test, oldInIteration; + + expectKeyword('do'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + if (match(';')) { + lex(); + } + + return { + type: Syntax.DoWhileStatement, + body: body, + test: test + }; + } + + function parseWhileStatement() { + var test, body, oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return { + type: Syntax.WhileStatement, + test: test, + body: body + }; + } + + function parseForVariableDeclaration() { + var token = lex(); + + return { + type: Syntax.VariableDeclaration, + declarations: parseVariableDeclarationList(), + kind: token.value + }; + } + + function parseForStatement() { + var init, test, update, left, right, body, oldInIteration; + + init = test = update = null; + + expectKeyword('for'); + + expect('('); + + if (match(';')) { + lex(); + } else { + if (matchKeyword('var') || matchKeyword('let')) { + state.allowIn = false; + init = parseForVariableDeclaration(); + state.allowIn = true; + + if (init.declarations.length === 1 && matchKeyword('in')) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } else { + state.allowIn = false; + init = parseExpression(); + state.allowIn = true; + + if (matchKeyword('in')) { + // LeftHandSideExpression + if (!isLeftHandSide(init)) { + throwError({}, Messages.InvalidLHSInForIn); + } + + lex(); + left = init; + right = parseExpression(); + init = null; + } + } + + if (typeof left === 'undefined') { + expect(';'); + } + } + + if (typeof left === 'undefined') { + + if (!match(';')) { + test = parseExpression(); + } + expect(';'); + + if (!match(')')) { + update = parseExpression(); + } + } + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + if (typeof left === 'undefined') { + return { + type: Syntax.ForStatement, + init: init, + test: test, + update: update, + body: body + }; + } + + return { + type: Syntax.ForInStatement, + left: left, + right: right, + body: body, + each: false + }; + } + + // 12.7 The continue statement + + function parseContinueStatement() { + var token, label = null; + + expectKeyword('continue'); + + // Optimize the most common form: 'continue;'. + if (source[index] === ';') { + lex(); + + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: null + }; + } + + if (peekLineTerminator()) { + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: null + }; + } + + token = lookahead(); + if (token.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: label + }; + } + + // 12.8 The break statement + + function parseBreakStatement() { + var token, label = null; + + expectKeyword('break'); + + // Optimize the most common form: 'break;'. + if (source[index] === ';') { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: null + }; + } + + if (peekLineTerminator()) { + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: null + }; + } + + token = lookahead(); + if (token.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: label + }; + } + + // 12.9 The return statement + + function parseReturnStatement() { + var token, argument = null; + + expectKeyword('return'); + + if (!state.inFunctionBody) { + throwErrorTolerant({}, Messages.IllegalReturn); + } + + // 'return' followed by a space and an identifier is very common. + if (source[index] === ' ') { + if (isIdentifierStart(source[index + 1])) { + argument = parseExpression(); + consumeSemicolon(); + return { + type: Syntax.ReturnStatement, + argument: argument + }; + } + } + + if (peekLineTerminator()) { + return { + type: Syntax.ReturnStatement, + argument: null + }; + } + + if (!match(';')) { + token = lookahead(); + if (!match('}') && token.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return { + type: Syntax.ReturnStatement, + argument: argument + }; + } + + // 12.10 The with statement + + function parseWithStatement() { + var object, body; + + if (strict) { + throwErrorTolerant({}, Messages.StrictModeWith); + } + + expectKeyword('with'); + + expect('('); + + object = parseExpression(); + + expect(')'); + + body = parseStatement(); + + return { + type: Syntax.WithStatement, + object: object, + body: body + }; + } + + // 12.10 The swith statement + + function parseSwitchCase() { + var test, + consequent = [], + statement; + + if (matchKeyword('default')) { + lex(); + test = null; + } else { + expectKeyword('case'); + test = parseExpression(); + } + expect(':'); + + while (index < length) { + if (match('}') || matchKeyword('default') || matchKeyword('case')) { + break; + } + statement = parseStatement(); + if (typeof statement === 'undefined') { + break; + } + consequent.push(statement); + } + + return { + type: Syntax.SwitchCase, + test: test, + consequent: consequent + }; + } + + function parseSwitchStatement() { + var discriminant, cases, clause, oldInSwitch, defaultFound; + + expectKeyword('switch'); + + expect('('); + + discriminant = parseExpression(); + + expect(')'); + + expect('{'); + + if (match('}')) { + lex(); + return { + type: Syntax.SwitchStatement, + discriminant: discriminant + }; + } + + cases = []; + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + defaultFound = false; + + while (index < length) { + if (match('}')) { + break; + } + clause = parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + throwError({}, Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + + state.inSwitch = oldInSwitch; + + expect('}'); + + return { + type: Syntax.SwitchStatement, + discriminant: discriminant, + cases: cases + }; + } + + // 12.13 The throw statement + + function parseThrowStatement() { + var argument; + + expectKeyword('throw'); + + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return { + type: Syntax.ThrowStatement, + argument: argument + }; + } + + // 12.14 The try statement + + function parseCatchClause() { + var param; + + expectKeyword('catch'); + + expect('('); + if (!match(')')) { + param = parseExpression(); + // 12.14.1 + if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { + throwErrorTolerant({}, Messages.StrictCatchVariable); + } + } + expect(')'); + + return { + type: Syntax.CatchClause, + param: param, + body: parseBlock() + }; + } + + function parseTryStatement() { + var block, handlers = [], finalizer = null; + + expectKeyword('try'); + + block = parseBlock(); + + if (matchKeyword('catch')) { + handlers.push(parseCatchClause()); + } + + if (matchKeyword('finally')) { + lex(); + finalizer = parseBlock(); + } + + if (handlers.length === 0 && !finalizer) { + throwError({}, Messages.NoCatchOrFinally); + } + + return { + type: Syntax.TryStatement, + block: block, + guardedHandlers: [], + handlers: handlers, + finalizer: finalizer + }; + } + + // 12.15 The debugger statement + + function parseDebuggerStatement() { + expectKeyword('debugger'); + + consumeSemicolon(); + + return { + type: Syntax.DebuggerStatement + }; + } + + // 12 Statements + + function parseStatement() { + var token = lookahead(), + expr, + labeledBody; + + if (token.type === Token.EOF) { + throwUnexpected(token); + } + + if (token.type === Token.Punctuator) { + switch (token.value) { + case ';': + return parseEmptyStatement(); + case '{': + return parseBlock(); + case '(': + return parseExpressionStatement(); + default: + break; + } + } + + if (token.type === Token.Keyword) { + switch (token.value) { + case 'break': + return parseBreakStatement(); + case 'continue': + return parseContinueStatement(); + case 'debugger': + return parseDebuggerStatement(); + case 'do': + return parseDoWhileStatement(); + case 'for': + return parseForStatement(); + case 'function': + return parseFunctionDeclaration(); + case 'if': + return parseIfStatement(); + case 'return': + return parseReturnStatement(); + case 'switch': + return parseSwitchStatement(); + case 'throw': + return parseThrowStatement(); + case 'try': + return parseTryStatement(); + case 'var': + return parseVariableStatement(); + case 'while': + return parseWhileStatement(); + case 'with': + return parseWithStatement(); + default: + break; + } + } + + expr = parseExpression(); + + // 12.12 Labelled Statements + if ((expr.type === Syntax.Identifier) && match(':')) { + lex(); + + if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) { + throwError({}, Messages.Redeclaration, 'Label', expr.name); + } + + state.labelSet[expr.name] = true; + labeledBody = parseStatement(); + delete state.labelSet[expr.name]; + + return { + type: Syntax.LabeledStatement, + label: expr, + body: labeledBody + }; + } + + consumeSemicolon(); + + return { + type: Syntax.ExpressionStatement, + expression: expr + }; + } + + // 13 Function Definition + + function parseFunctionSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody; + + expect('{'); + + while (index < length) { + token = lookahead(); + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = sliceSource(token.range[0] + 1, token.range[1] - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + + state.labelSet = {}; + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + + while (index < length) { + if (match('}')) { + break; + } + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + + expect('}'); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + + return { + type: Syntax.BlockStatement, + body: sourceElements + }; + } + + function parseFunctionDeclaration() { + var id, param, params = [], body, token, stricted, firstRestricted, message, previousStrict, paramSet; + + expectKeyword('function'); + token = lookahead(); + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + + expect('('); + + if (!match(')')) { + paramSet = {}; + while (index < length) { + token = lookahead(); + param = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + stricted = token; + message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + stricted = token; + message = Messages.StrictParamDupe; + } + } else if (!firstRestricted) { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + firstRestricted = token; + message = Messages.StrictParamDupe; + } + } + params.push(param); + paramSet[param.name] = true; + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return { + type: Syntax.FunctionDeclaration, + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }; + } + + function parseFunctionExpression() { + var token, id = null, stricted, firstRestricted, message, param, params = [], body, previousStrict, paramSet; + + expectKeyword('function'); + + if (!match('(')) { + token = lookahead(); + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + expect('('); + + if (!match(')')) { + paramSet = {}; + while (index < length) { + token = lookahead(); + param = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + stricted = token; + message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + stricted = token; + message = Messages.StrictParamDupe; + } + } else if (!firstRestricted) { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + firstRestricted = token; + message = Messages.StrictParamDupe; + } + } + params.push(param); + paramSet[param.name] = true; + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return { + type: Syntax.FunctionExpression, + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }; + } + + // 14 Program + + function parseSourceElement() { + var token = lookahead(); + + if (token.type === Token.Keyword) { + switch (token.value) { + case 'const': + case 'let': + return parseConstLetDeclaration(token.value); + case 'function': + return parseFunctionDeclaration(); + default: + return parseStatement(); + } + } + + if (token.type !== Token.EOF) { + return parseStatement(); + } + } + + function parseSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted; + + while (index < length) { + token = lookahead(); + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = sliceSource(token.range[0] + 1, token.range[1] - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (index < length) { + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + return sourceElements; + } + + function parseProgram() { + var program; + strict = false; + program = { + type: Syntax.Program, + body: parseSourceElements() + }; + return program; + } + + // The following functions are needed only when the option to preserve + // the comments is active. + + function addComment(type, value, start, end, loc) { + assert(typeof start === 'number', 'Comment must have valid position'); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (extra.comments.length > 0) { + if (extra.comments[extra.comments.length - 1].range[1] > start) { + return; + } + } + + extra.comments.push({ + type: type, + value: value, + range: [start, end], + loc: loc + }); + } + + function scanComment() { + var comment, ch, loc, start, blockComment, lineComment; + + comment = ''; + blockComment = false; + lineComment = false; + + while (index < length) { + ch = source[index]; + + if (lineComment) { + ch = source[index++]; + if (isLineTerminator(ch)) { + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + lineComment = false; + addComment('Line', comment, start, index - 1, loc); + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + comment = ''; + } else if (index >= length) { + lineComment = false; + comment += ch; + loc.end = { + line: lineNumber, + column: length - lineStart + }; + addComment('Line', comment, start, length, loc); + } else { + comment += ch; + } + } else if (blockComment) { + if (isLineTerminator(ch)) { + if (ch === '\r' && source[index + 1] === '\n') { + ++index; + comment += '\r\n'; + } else { + comment += ch; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + ch = source[index++]; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + comment += ch; + if (ch === '*') { + ch = source[index]; + if (ch === '/') { + comment = comment.substr(0, comment.length - 1); + blockComment = false; + ++index; + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); + comment = ''; + } + } + } + } else if (ch === '/') { + ch = source[index + 1]; + if (ch === '/') { + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + start = index; + index += 2; + lineComment = true; + if (index >= length) { + loc.end = { + line: lineNumber, + column: index - lineStart + }; + lineComment = false; + addComment('Line', comment, start, index, loc); + } + } else if (ch === '*') { + start = index; + index += 2; + blockComment = true; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } else { + break; + } + } + } + + function filterCommentLocation() { + var i, entry, comment, comments = []; + + for (i = 0; i < extra.comments.length; ++i) { + entry = extra.comments[i]; + comment = { + type: entry.type, + value: entry.value + }; + if (extra.range) { + comment.range = entry.range; + } + if (extra.loc) { + comment.loc = entry.loc; + } + comments.push(comment); + } + + extra.comments = comments; + } + + function collectToken() { + var start, loc, token, range, value; + + skipComment(); + start = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = extra.advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + range = [token.range[0], token.range[1]]; + value = sliceSource(token.range[0], token.range[1]); + extra.tokens.push({ + type: TokenName[token.type], + value: value, + range: range, + loc: loc + }); + } + + return token; + } + + function collectRegex() { + var pos, loc, regex, token; + + skipComment(); + + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = extra.scanRegExp(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + range: [pos, index], + loc: loc + }); + + return regex; + } + + function filterTokenLocation() { + var i, entry, token, tokens = []; + + for (i = 0; i < extra.tokens.length; ++i) { + entry = extra.tokens[i]; + token = { + type: entry.type, + value: entry.value + }; + if (extra.range) { + token.range = entry.range; + } + if (extra.loc) { + token.loc = entry.loc; + } + tokens.push(token); + } + + extra.tokens = tokens; + } + + function createLiteral(token) { + return { + type: Syntax.Literal, + value: token.value + }; + } + + function createRawLiteral(token) { + return { + type: Syntax.Literal, + value: token.value, + raw: sliceSource(token.range[0], token.range[1]) + }; + } + + function createLocationMarker() { + var marker = {}; + + marker.range = [index, index]; + marker.loc = { + start: { + line: lineNumber, + column: index - lineStart + }, + end: { + line: lineNumber, + column: index - lineStart + } + }; + + marker.end = function () { + this.range[1] = index; + this.loc.end.line = lineNumber; + this.loc.end.column = index - lineStart; + }; + + marker.applyGroup = function (node) { + if (extra.range) { + node.groupRange = [this.range[0], this.range[1]]; + } + if (extra.loc) { + node.groupLoc = { + start: { + line: this.loc.start.line, + column: this.loc.start.column + }, + end: { + line: this.loc.end.line, + column: this.loc.end.column + } + }; + } + }; + + marker.apply = function (node) { + if (extra.range) { + node.range = [this.range[0], this.range[1]]; + } + if (extra.loc) { + node.loc = { + start: { + line: this.loc.start.line, + column: this.loc.start.column + }, + end: { + line: this.loc.end.line, + column: this.loc.end.column + } + }; + } + }; + + return marker; + } + + function trackGroupExpression() { + var marker, expr; + + skipComment(); + marker = createLocationMarker(); + expect('('); + + expr = parseExpression(); + + expect(')'); + + marker.end(); + marker.applyGroup(expr); + + return expr; + } + + function trackLeftHandSideExpression() { + var marker, expr; + + skipComment(); + marker = createLocationMarker(); + + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + + while (match('.') || match('[')) { + if (match('[')) { + expr = { + type: Syntax.MemberExpression, + computed: true, + object: expr, + property: parseComputedMember() + }; + marker.end(); + marker.apply(expr); + } else { + expr = { + type: Syntax.MemberExpression, + computed: false, + object: expr, + property: parseNonComputedMember() + }; + marker.end(); + marker.apply(expr); + } + } + + return expr; + } + + function trackLeftHandSideExpressionAllowCall() { + var marker, expr; + + skipComment(); + marker = createLocationMarker(); + + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + + while (match('.') || match('[') || match('(')) { + if (match('(')) { + expr = { + type: Syntax.CallExpression, + callee: expr, + 'arguments': parseArguments() + }; + marker.end(); + marker.apply(expr); + } else if (match('[')) { + expr = { + type: Syntax.MemberExpression, + computed: true, + object: expr, + property: parseComputedMember() + }; + marker.end(); + marker.apply(expr); + } else { + expr = { + type: Syntax.MemberExpression, + computed: false, + object: expr, + property: parseNonComputedMember() + }; + marker.end(); + marker.apply(expr); + } + } + + return expr; + } + + function filterGroup(node) { + var n, i, entry; + + n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {}; + for (i in node) { + if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') { + entry = node[i]; + if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) { + n[i] = entry; + } else { + n[i] = filterGroup(entry); + } + } + } + return n; + } + + function wrapTrackingFunction(range, loc) { + + return function (parseFunction) { + + function isBinary(node) { + return node.type === Syntax.LogicalExpression || + node.type === Syntax.BinaryExpression; + } + + function visit(node) { + var start, end; + + if (isBinary(node.left)) { + visit(node.left); + } + if (isBinary(node.right)) { + visit(node.right); + } + + if (range) { + if (node.left.groupRange || node.right.groupRange) { + start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0]; + end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1]; + node.range = [start, end]; + } else if (typeof node.range === 'undefined') { + start = node.left.range[0]; + end = node.right.range[1]; + node.range = [start, end]; + } + } + if (loc) { + if (node.left.groupLoc || node.right.groupLoc) { + start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start; + end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end; + node.loc = { + start: start, + end: end + }; + } else if (typeof node.loc === 'undefined') { + node.loc = { + start: node.left.loc.start, + end: node.right.loc.end + }; + } + } + } + + return function () { + var marker, node; + + skipComment(); + + marker = createLocationMarker(); + node = parseFunction.apply(null, arguments); + marker.end(); + + if (range && typeof node.range === 'undefined') { + marker.apply(node); + } + + if (loc && typeof node.loc === 'undefined') { + marker.apply(node); + } + + if (isBinary(node)) { + visit(node); + } + + return node; + }; + }; + } + + function patch() { + + var wrapTracking; + + if (extra.comments) { + extra.skipComment = skipComment; + skipComment = scanComment; + } + + if (extra.raw) { + extra.createLiteral = createLiteral; + createLiteral = createRawLiteral; + } + + if (extra.range || extra.loc) { + + extra.parseGroupExpression = parseGroupExpression; + extra.parseLeftHandSideExpression = parseLeftHandSideExpression; + extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall; + parseGroupExpression = trackGroupExpression; + parseLeftHandSideExpression = trackLeftHandSideExpression; + parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall; + + wrapTracking = wrapTrackingFunction(extra.range, extra.loc); + + extra.parseAdditiveExpression = parseAdditiveExpression; + extra.parseAssignmentExpression = parseAssignmentExpression; + extra.parseBitwiseANDExpression = parseBitwiseANDExpression; + extra.parseBitwiseORExpression = parseBitwiseORExpression; + extra.parseBitwiseXORExpression = parseBitwiseXORExpression; + extra.parseBlock = parseBlock; + extra.parseFunctionSourceElements = parseFunctionSourceElements; + extra.parseCatchClause = parseCatchClause; + extra.parseComputedMember = parseComputedMember; + extra.parseConditionalExpression = parseConditionalExpression; + extra.parseConstLetDeclaration = parseConstLetDeclaration; + extra.parseEqualityExpression = parseEqualityExpression; + extra.parseExpression = parseExpression; + extra.parseForVariableDeclaration = parseForVariableDeclaration; + extra.parseFunctionDeclaration = parseFunctionDeclaration; + extra.parseFunctionExpression = parseFunctionExpression; + extra.parseLogicalANDExpression = parseLogicalANDExpression; + extra.parseLogicalORExpression = parseLogicalORExpression; + extra.parseMultiplicativeExpression = parseMultiplicativeExpression; + extra.parseNewExpression = parseNewExpression; + extra.parseNonComputedProperty = parseNonComputedProperty; + extra.parseObjectProperty = parseObjectProperty; + extra.parseObjectPropertyKey = parseObjectPropertyKey; + extra.parsePostfixExpression = parsePostfixExpression; + extra.parsePrimaryExpression = parsePrimaryExpression; + extra.parseProgram = parseProgram; + extra.parsePropertyFunction = parsePropertyFunction; + extra.parseRelationalExpression = parseRelationalExpression; + extra.parseStatement = parseStatement; + extra.parseShiftExpression = parseShiftExpression; + extra.parseSwitchCase = parseSwitchCase; + extra.parseUnaryExpression = parseUnaryExpression; + extra.parseVariableDeclaration = parseVariableDeclaration; + extra.parseVariableIdentifier = parseVariableIdentifier; + + parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression); + parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression); + parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression); + parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression); + parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression); + parseBlock = wrapTracking(extra.parseBlock); + parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); + parseCatchClause = wrapTracking(extra.parseCatchClause); + parseComputedMember = wrapTracking(extra.parseComputedMember); + parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); + parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); + parseEqualityExpression = wrapTracking(extra.parseEqualityExpression); + parseExpression = wrapTracking(extra.parseExpression); + parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); + parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); + parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); + parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression); + parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression); + parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression); + parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression); + parseNewExpression = wrapTracking(extra.parseNewExpression); + parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); + parseObjectProperty = wrapTracking(extra.parseObjectProperty); + parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); + parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); + parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); + parseProgram = wrapTracking(extra.parseProgram); + parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); + parseRelationalExpression = wrapTracking(extra.parseRelationalExpression); + parseStatement = wrapTracking(extra.parseStatement); + parseShiftExpression = wrapTracking(extra.parseShiftExpression); + parseSwitchCase = wrapTracking(extra.parseSwitchCase); + parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); + parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); + parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); + } + + if (typeof extra.tokens !== 'undefined') { + extra.advance = advance; + extra.scanRegExp = scanRegExp; + + advance = collectToken; + scanRegExp = collectRegex; + } + } + + function unpatch() { + if (typeof extra.skipComment === 'function') { + skipComment = extra.skipComment; + } + + if (extra.raw) { + createLiteral = extra.createLiteral; + } + + if (extra.range || extra.loc) { + parseAdditiveExpression = extra.parseAdditiveExpression; + parseAssignmentExpression = extra.parseAssignmentExpression; + parseBitwiseANDExpression = extra.parseBitwiseANDExpression; + parseBitwiseORExpression = extra.parseBitwiseORExpression; + parseBitwiseXORExpression = extra.parseBitwiseXORExpression; + parseBlock = extra.parseBlock; + parseFunctionSourceElements = extra.parseFunctionSourceElements; + parseCatchClause = extra.parseCatchClause; + parseComputedMember = extra.parseComputedMember; + parseConditionalExpression = extra.parseConditionalExpression; + parseConstLetDeclaration = extra.parseConstLetDeclaration; + parseEqualityExpression = extra.parseEqualityExpression; + parseExpression = extra.parseExpression; + parseForVariableDeclaration = extra.parseForVariableDeclaration; + parseFunctionDeclaration = extra.parseFunctionDeclaration; + parseFunctionExpression = extra.parseFunctionExpression; + parseGroupExpression = extra.parseGroupExpression; + parseLeftHandSideExpression = extra.parseLeftHandSideExpression; + parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall; + parseLogicalANDExpression = extra.parseLogicalANDExpression; + parseLogicalORExpression = extra.parseLogicalORExpression; + parseMultiplicativeExpression = extra.parseMultiplicativeExpression; + parseNewExpression = extra.parseNewExpression; + parseNonComputedProperty = extra.parseNonComputedProperty; + parseObjectProperty = extra.parseObjectProperty; + parseObjectPropertyKey = extra.parseObjectPropertyKey; + parsePrimaryExpression = extra.parsePrimaryExpression; + parsePostfixExpression = extra.parsePostfixExpression; + parseProgram = extra.parseProgram; + parsePropertyFunction = extra.parsePropertyFunction; + parseRelationalExpression = extra.parseRelationalExpression; + parseStatement = extra.parseStatement; + parseShiftExpression = extra.parseShiftExpression; + parseSwitchCase = extra.parseSwitchCase; + parseUnaryExpression = extra.parseUnaryExpression; + parseVariableDeclaration = extra.parseVariableDeclaration; + parseVariableIdentifier = extra.parseVariableIdentifier; + } + + if (typeof extra.scanRegExp === 'function') { + advance = extra.advance; + scanRegExp = extra.scanRegExp; + } + } + + function stringToArray(str) { + var length = str.length, + result = [], + i; + for (i = 0; i < length; ++i) { + result[i] = str.charAt(i); + } + return result; + } + + function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + buffer = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false + }; + + extra = {}; + if (typeof options !== 'undefined') { + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + extra.raw = (typeof options.raw === 'boolean') && options.raw; + if (typeof options.tokens === 'boolean' && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + } + + if (length > 0) { + if (typeof source[0] === 'undefined') { + // Try first to convert to a string. This is good as fast path + // for old IE which understands string indexing for string + // literals only and not for string object. + if (code instanceof String) { + source = code.valueOf(); + } + + // Force accessing the characters via an array. + if (typeof source[0] === 'undefined') { + source = stringToArray(code); + } + } + } + + patch(); + try { + program = parseProgram(); + if (typeof extra.comments !== 'undefined') { + filterCommentLocation(); + program.comments = extra.comments; + } + if (typeof extra.tokens !== 'undefined') { + filterTokenLocation(); + program.tokens = extra.tokens; + } + if (typeof extra.errors !== 'undefined') { + program.errors = extra.errors; + } + if (extra.range || extra.loc) { + program.body = filterGroup(program.body); + } + } catch (e) { + throw e; + } finally { + unpatch(); + extra = {}; + } + + return program; + } + + // Sync with package.json. + exports.version = '1.0.2'; + + exports.parse = parse; + + // Deep copy. + exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === 'function') { + types = Object.create(null); + } + + for (name in Syntax) { + if (Syntax.hasOwnProperty(name)) { + types[name] = Syntax[name]; + } + } + + if (typeof Object.freeze === 'function') { + Object.freeze(types); + } + + return types; + }()); + +})); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/detectnestedternary.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/detectnestedternary.js new file mode 100644 index 000000000..f144955d1 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/detectnestedternary.js @@ -0,0 +1,106 @@ +// Usage: node detectnestedternary.js /path/to/some/directory +// For more details, please read http://esprima.org/doc/#nestedternary + +/*jslint node:true sloppy:true plusplus:true */ + +var fs = require('fs'), + esprima = require('../esprima'), + dirname = process.argv[2]; + + +// Executes visitor on the object and its children (recursively). +function traverse(object, visitor) { + var key, child; + + visitor.call(null, object); + for (key in object) { + if (object.hasOwnProperty(key)) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverse(child, visitor); + } + } + } +} + +// http://stackoverflow.com/q/5827612/ +function walk(dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) { + return done(err); + } + var i = 0; + (function next() { + var file = list[i++]; + if (!file) { + return done(null, results); + } + file = dir + '/' + file; + fs.stat(file, function (err, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + }()); + }); +} + +walk(dirname, function (err, results) { + if (err) { + console.log('Error', err); + return; + } + + results.forEach(function (filename) { + var shortname, first, content, syntax; + + shortname = filename; + first = true; + + if (shortname.substr(0, dirname.length) === dirname) { + shortname = shortname.substr(dirname.length + 1, shortname.length); + } + + function report(node, problem) { + if (first === true) { + console.log(shortname + ': '); + first = false; + } + console.log(' Line', node.loc.start.line, ':', problem); + } + + function checkConditional(node) { + var condition; + + if (node.consequent.type === 'ConditionalExpression' || + node.alternate.type === 'ConditionalExpression') { + + condition = content.substring(node.test.range[0], node.test.range[1]); + if (condition.length > 20) { + condition = condition.substring(0, 20) + '...'; + } + condition = '"' + condition + '"'; + report(node, 'Nested ternary for ' + condition); + } + } + + try { + content = fs.readFileSync(filename, 'utf-8'); + syntax = esprima.parse(content, { tolerant: true, loc: true, range: true }); + traverse(syntax, function (node) { + if (node.type === 'ConditionalExpression') { + checkConditional(node); + } + }); + } catch (e) { + } + + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/findbooleantrap.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/findbooleantrap.js new file mode 100644 index 000000000..dc6d1d9c5 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/findbooleantrap.js @@ -0,0 +1,173 @@ +// Usage: node findbooleantrap.js /path/to/some/directory +// For more details, please read http://esprima.org/doc/#booleantrap. + +/*jslint node:true sloppy:true plusplus:true */ + +var fs = require('fs'), + esprima = require('../esprima'), + dirname = process.argv[2], + doubleNegativeList = []; + + +// Black-list of terms with double-negative meaning. +doubleNegativeList = [ + 'hidden', + 'caseinsensitive', + 'disabled' +]; + + +// Executes visitor on the object and its children (recursively). +function traverse(object, visitor) { + var key, child; + + if (visitor.call(null, object) === false) { + return; + } + for (key in object) { + if (object.hasOwnProperty(key)) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverse(child, visitor); + } + } + } +} + +// http://stackoverflow.com/q/5827612/ +function walk(dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) { + return done(err); + } + var i = 0; + (function next() { + var file = list[i++]; + if (!file) { + return done(null, results); + } + file = dir + '/' + file; + fs.stat(file, function (err, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + }()); + }); +} + +walk(dirname, function (err, results) { + if (err) { + console.log('Error', err); + return; + } + + results.forEach(function (filename) { + var shortname, first, content, syntax; + + shortname = filename; + first = true; + + if (shortname.substr(0, dirname.length) === dirname) { + shortname = shortname.substr(dirname.length + 1, shortname.length); + } + + function getFunctionName(node) { + if (node.callee.type === 'Identifier') { + return node.callee.name; + } + if (node.callee.type === 'MemberExpression') { + return node.callee.property.name; + } + } + + function report(node, problem) { + if (first === true) { + console.log(shortname + ': '); + first = false; + } + console.log(' Line', node.loc.start.line, 'in function', + getFunctionName(node) + ':', problem); + } + + function checkSingleArgument(node) { + var args = node['arguments'], + functionName = getFunctionName(node); + + if ((args.length !== 1) || (typeof args[0].value !== 'boolean')) { + return; + } + + // Check if the method is a setter, i.e. starts with 'set', + // e.g. 'setEnabled(false)'. + if (functionName.substr(0, 3) !== 'set') { + report(node, 'Boolean literal with a non-setter function'); + } + + // Does it contain a term with double-negative meaning? + doubleNegativeList.forEach(function (term) { + if (functionName.toLowerCase().indexOf(term.toLowerCase()) >= 0) { + report(node, 'Boolean literal with confusing double-negative'); + } + }); + } + + function checkMultipleArguments(node) { + var args = node['arguments'], + literalCount = 0; + + args.forEach(function (arg) { + if (typeof arg.value === 'boolean') { + literalCount++; + } + }); + + // At least two arguments must be Boolean literals. + if (literalCount >= 2) { + + // Check for two different Boolean literals in one call. + if (literalCount === 2 && args.length === 2) { + if (args[0].value !== args[1].value) { + report(node, 'Confusing true vs false'); + return; + } + } + + report(node, 'Multiple Boolean literals'); + } + } + + function checkLastArgument(node) { + var args = node['arguments']; + + if (args.length < 2) { + return; + } + + if (typeof args[args.length - 1].value === 'boolean') { + report(node, 'Ambiguous Boolean literal as the last argument'); + } + } + + try { + content = fs.readFileSync(filename, 'utf-8'); + syntax = esprima.parse(content, { tolerant: true, loc: true }); + traverse(syntax, function (node) { + if (node.type === 'CallExpression') { + checkSingleArgument(node); + checkLastArgument(node); + checkMultipleArguments(node); + } + }); + } catch (e) { + } + + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/tokendist.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/tokendist.js new file mode 100644 index 000000000..bdd7761ca --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/examples/tokendist.js @@ -0,0 +1,33 @@ +/*jslint node:true */ +var fs = require('fs'), + esprima = require('../esprima'), + files = process.argv.splice(2), + histogram, + type; + +histogram = { + Boolean: 0, + Identifier: 0, + Keyword: 0, + Null: 0, + Numeric: 0, + Punctuator: 0, + RegularExpression: 0, + String: 0 +}; + +files.forEach(function (filename) { + 'use strict'; + var content = fs.readFileSync(filename, 'utf-8'), + tokens = esprima.parse(content, { tokens: true }).tokens; + + tokens.forEach(function (token) { + histogram[token.type] += 1; + }); +}); + +for (type in histogram) { + if (histogram.hasOwnProperty(type)) { + console.log(type, histogram[type]); + } +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/index.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/index.html new file mode 100644 index 000000000..a78e83e15 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/index.html @@ -0,0 +1,102 @@ + + + + +Esprima + + + +
    + + + +

    Esprima ECMAScript parsing infrastructure for multipurpose analysis

    + +
    +

    Esprima is a high performance, standard-compliant +ECMAScript parser +written in ECMAScript (also popularly known as +JavaScript).

    + +

    Esprima runs on web browsers (IE 6+, Firefox 1+, Safari 3+, Chrome 1+, Konqueror 4.6+, Opera 8+) as well as +Rhino and Node.js.

    + +

    Features

    + +
      +
    • Full support for ECMAScript 5.1 (ECMA-262)
    • +
    • Sensible syntax tree format, compatible with Mozilla +Parser AST
    • +
    • Heavily tested (> 550 unit tests with solid 100% statement coverage)
    • +
    • Optional tracking of syntax node location (index-based and line-column)
    • +
    • Experimental support for ES6/Harmony (module, class, destructuring, ...)
    • +
    + +

    Esprima is blazing fast (see the benchmark suite). +It is up to 3x faster than UglifyJS v1 and it is still +competitive with the new generation of fast parsers.

    + +

    Applications

    + +Esprima serves as the basis for many popular JavaScript development tools: + + + +

    Feedback is welcomed! Please join the discussion in the mailing list.

    + +
    + + + +
    + + +
    +Fork me on GitHub + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/package.json b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/package.json new file mode 100644 index 000000000..7581a5ab2 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/package.json @@ -0,0 +1,49 @@ +{ + "name": "esprima", + "description": "ECMAScript parsing infrastructure for multipurpose analysis", + "homepage": "http://esprima.org", + "main": "esprima.js", + "bin": { + "esparse": "./bin/esparse.js", + "esvalidate": "./bin/esvalidate.js" + }, + "version": "1.0.2", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "ariya", + "email": "ariya.hidayat@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/ariya/esprima.git" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "node test/run.js", + "benchmark": "node test/benchmarks.js", + "benchmark-quick": "node test/benchmarks.js quick" + }, + "_id": "esprima@1.0.2", + "dist": { + "shasum": "8039bf9ceac4d9d2c15f623264fb292b5502ceaf", + "tarball": "http://registry.npmjs.org/esprima/-/esprima-1.0.2.tgz" + }, + "_npmVersion": "1.1.61", + "_npmUser": { + "name": "ariya", + "email": "ariya.hidayat@gmail.com" + }, + "directories": {}, + "_shasum": "8039bf9ceac4d9d2c15f623264fb292b5502ceaf", + "_from": "esprima@1.0.2", + "_resolved": "https://registry.npmjs.org/esprima/-/esprima-1.0.2.tgz" +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.html new file mode 100644 index 000000000..018749710 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.html @@ -0,0 +1,58 @@ + + + + +Esprima: Benchmarks + + + + + + + + + + +
    + + + +

    Benchmarks show the speed

    + +

    Time measurement is carried out using Benchmark.js.

    + +

    Esprima version .

    + +

    Please wait...

    + +

    + + +

    + +

    + +

    Note: On a modern machine and up-to-date web browsers, +running full benchmarks suite takes around 1 minute.
    +For the quick benchmarks, the running time is only about 15 seconds.

    + + +
    + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.js new file mode 100644 index 000000000..788b140b2 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/benchmarks.js @@ -0,0 +1,334 @@ +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +/*jslint browser: true node: true */ +/*global load:true, print:true */ +var setupBenchmarks, + fixture; + +fixture = [ + 'jQuery 1.7.1', + 'jQuery 1.6.4', + 'jQuery.Mobile 1.0', + 'Prototype 1.7.0.0', + 'Prototype 1.6.1', + 'Ext Core 3.1.0', + 'Ext Core 3.0.0', + 'MooTools 1.4.1', + 'MooTools 1.3.2', + 'Backbone 0.5.3', + 'Underscore 1.2.3' +]; + +function slug(name) { + 'use strict'; + return name.toLowerCase().replace(/\s/g, '-'); +} + +function kb(bytes) { + 'use strict'; + return (bytes / 1024).toFixed(1); +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + setupBenchmarks = function () { + 'use strict'; + + function id(i) { + return document.getElementById(i); + } + + function setText(id, str) { + var el = document.getElementById(id); + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function enableRunButtons() { + id('runquick').disabled = false; + id('runfull').disabled = false; + } + + function disableRunButtons() { + id('runquick').disabled = true; + id('runfull').disabled = true; + } + + function createTable() { + var str = '', + index, + test, + name; + + str += ''; + str += ''; + str += ''; + str += ''; + for (index = 0; index < fixture.length; index += 1) { + test = fixture[index]; + name = slug(test); + str += ''; + str += ''; + str += ''; + str += ''; + str += ''; + str += ''; + } + str += ''; + str += ''; + str += ''; + str += ''; + str += ''; + str += '
    SourceSize (KiB)Time (ms)Variance
    ' + test + '
    Total
    '; + + id('result').innerHTML = str; + } + + function loadTests() { + + var index = 0, + totalSize = 0; + + function load(test, callback) { + var xhr = new XMLHttpRequest(), + src = '3rdparty/' + test + '.js'; + + window.data = window.data || {}; + window.data[test] = ''; + + try { + xhr.timeout = 30000; + xhr.open('GET', src, true); + + xhr.ontimeout = function () { + setText('status', 'Error: time out while loading ' + test); + callback.apply(); + }; + + xhr.onreadystatechange = function () { + var success = false, + size = 0; + + if (this.readyState === XMLHttpRequest.DONE) { + if (this.status === 200) { + window.data[test] = this.responseText; + size = this.responseText.length; + totalSize += size; + success = true; + } + } + + if (success) { + setText(test + '-size', kb(size)); + } else { + setText('status', 'Please wait. Error loading ' + src); + setText(test + '-size', 'Error'); + } + + callback.apply(); + }; + + xhr.send(null); + } catch (e) { + setText('status', 'Please wait. Error loading ' + src); + callback.apply(); + } + } + + function loadNextTest() { + var test; + + if (index < fixture.length) { + test = fixture[index]; + index += 1; + setText('status', 'Please wait. Loading ' + test + + ' (' + index + ' of ' + fixture.length + ')'); + window.setTimeout(function () { + load(slug(test), loadNextTest); + }, 100); + } else { + setText('total-size', kb(totalSize)); + setText('status', 'Ready.'); + enableRunButtons(); + } + } + + loadNextTest(); + } + + function runBenchmarks(suite) { + + var index = 0, + totalTime = 0; + + function reset() { + var i, name; + for (i = 0; i < fixture.length; i += 1) { + name = slug(fixture[i]); + setText(name + '-time', ''); + setText(name + '-variance', ''); + } + setText('total-time', ''); + } + + function run() { + var el, test, source, benchmark; + + if (index >= suite.length) { + setText('total-time', (1000 * totalTime).toFixed(1)); + setText('status', 'Ready.'); + enableRunButtons(); + return; + } + + test = slug(suite[index]); + el = id(test); + source = window.data[test]; + setText(test + '-time', 'Running...'); + + // Force the result to be held in this array, thus defeating any + // possible "dead core elimination" optimization. + window.tree = []; + + benchmark = new window.Benchmark(test, function (o) { + var syntax = window.esprima.parse(source); + window.tree.push(syntax.body.length); + }, { + 'onComplete': function () { + setText(this.name + '-time', (1000 * this.stats.mean).toFixed(1)); + setText(this.name + '-variance', (1000 * this.stats.variance).toFixed(1)); + totalTime += this.stats.mean; + } + }); + + window.setTimeout(function () { + benchmark.run(); + index += 1; + window.setTimeout(run, 211); + }, 211); + } + + + disableRunButtons(); + setText('status', 'Please wait. Running benchmarks...'); + + reset(); + run(); + } + + id('runquick').onclick = function () { + runBenchmarks(['jQuery 1.7.1', 'jQuery.Mobile 1.0', 'Backbone 0.5.3']); + }; + + id('runfull').onclick = function () { + runBenchmarks(fixture); + }; + + setText('benchmarkjs-version', ' version ' + window.Benchmark.version); + setText('version', window.esprima.version); + + createTable(); + disableRunButtons(); + loadTests(); + }; +} else { + + // UMD workaround for V8 shell. + var window; + + (function (global) { + 'use strict'; + var Benchmark, + esprima, + dirname, + option, + fs, + readFileSync, + log; + + if (typeof require === 'undefined') { + dirname = 'test'; + load(dirname + '/3rdparty/benchmark.js'); + + window = global; + load(dirname + '/../esprima.js'); + + Benchmark = global.Benchmark; + esprima = global.esprima; + readFileSync = global.read; + log = print; + } else { + Benchmark = require('./3rdparty/benchmark'); + esprima = require('../esprima'); + fs = require('fs'); + option = process.argv[2]; + readFileSync = function readFileSync(filename) { + return fs.readFileSync(filename, 'utf-8'); + }; + dirname = __dirname; + log = console.log.bind(console); + } + + function runTests(tests) { + var index, + tree = [], + totalTime = 0, + totalSize = 0; + + tests.reduce(function (suite, filename) { + var source = readFileSync(dirname + '/3rdparty/' + slug(filename) + '.js'), + size = source.length; + totalSize += size; + return suite.add(filename, function () { + var syntax = esprima.parse(source); + tree.push(syntax.body.length); + }, { + 'onComplete': function (event, bench) { + log(this.name + + ' size ' + kb(size) + + ' time ' + (1000 * this.stats.mean).toFixed(1) + + ' variance ' + (1000 * this.stats.variance).toFixed(1)); + totalTime += this.stats.mean; + } + }); + }, new Benchmark.Suite()).on('complete', function () { + log('Total size ' + kb(totalSize) + + ' time ' + (1000 * totalTime).toFixed(1)); + }).run(); + } + + if (option === 'quick') { + runTests(['jQuery 1.7.1', 'jQuery.Mobile 1.0', 'Backbone 0.5.3']); + } else { + runTests(fixture); + } + }(this)); +} +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.html new file mode 100644 index 000000000..51f12267d --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.html @@ -0,0 +1,69 @@ + + + + +Esprima: Speed Comparison + + + + + + + + + + +
    + + + +

    Compare with other parsers

    + +

    Time measurement is carried out using Benchmark.js.

    + +

    Esprima version .

    + +

    Please wait... +

    + +

    + + +

    Warning: Since each parser may have a different format for the syntax tree, the speed is not fully comparable (the cost of constructing different result is not taken into account). These tests exist only to ensure that Esprima parser is not ridiculously slow compare to other parsers.

    + +

    parse-js is the parser used in UglifyJS v1. It's a JavaScript port of the Common LISP version. This test uses parse-js from UglifyJS version 1.3.2 (June 26 2012).

    + +

    Acorn is a compact stand-alone JavaScript parser. This test uses Acorn revision 0590d122 (dated Oct 3 2012).

    + +

    More comparison variants will be added in the near future.

    + + +
    + + + + + + + + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.js new file mode 100644 index 000000000..b81655ce3 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compare.js @@ -0,0 +1,328 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint browser: true node: true */ +/*global load:true, print:true */ +var setupBenchmarks, + parsers, + fixtureList, + suite; + +parsers = [ + 'Esprima', + 'parse-js', + 'Acorn' +]; + +fixtureList = [ + 'jQuery 1.7.1', + 'Prototype 1.7.0.0', + 'MooTools 1.4.1', + 'Ext Core 3.1.0' +]; + +function slug(name) { + 'use strict'; + return name.toLowerCase().replace(/\s/g, '-'); +} + +function kb(bytes) { + 'use strict'; + return (bytes / 1024).toFixed(1); +} + +function inject(fname) { + 'use strict'; + var head = document.getElementsByTagName('head')[0], + script = document.createElement('script'); + + script.src = fname; + script.type = 'text/javascript'; + head.appendChild(script); +} + +if (typeof window !== 'undefined') { + + // Run all tests in a browser environment. + setupBenchmarks = function () { + 'use strict'; + + function id(i) { + return document.getElementById(i); + } + + function setText(id, str) { + var el = document.getElementById(id); + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function enableRunButtons() { + id('run').disabled = false; + } + + function disableRunButtons() { + id('run').disabled = true; + } + + function createTable() { + var str = '', + i, + index, + test, + name; + + str += ''; + str += ''; + for (i = 0; i < parsers.length; i += 1) { + str += ''; + } + str += ''; + str += ''; + for (index = 0; index < fixtureList.length; index += 1) { + test = fixtureList[index]; + name = slug(test); + str += ''; + str += ''; + if (window.data && window.data[name]) { + str += ''; + } else { + str += ''; + } + for (i = 0; i < parsers.length; i += 1) { + str += ''; + } + str += ''; + } + str += ''; + str += ''; + for (i = 0; i < parsers.length; i += 1) { + str += ''; + } + str += ''; + str += ''; + str += '
    SourceSize (KiB)' + parsers[i] + '
    ' + test + '' + kb(window.data[name].length) + '
    Total
    '; + + id('result').innerHTML = str; + } + + function loadFixtures() { + + var index = 0, + totalSize = 0; + + function load(test, callback) { + var xhr = new XMLHttpRequest(), + src = '3rdparty/' + test + '.js'; + + window.data = window.data || {}; + window.data[test] = ''; + + try { + xhr.timeout = 30000; + xhr.open('GET', src, true); + + xhr.ontimeout = function () { + setText('status', 'Error: time out while loading ' + test); + callback.apply(); + }; + + xhr.onreadystatechange = function () { + var success = false, + size = 0; + + if (this.readyState === XMLHttpRequest.DONE) { + if (this.status === 200) { + window.data[test] = this.responseText; + size = this.responseText.length; + totalSize += size; + success = true; + } + } + + if (success) { + setText(test + '-size', kb(size)); + } else { + setText('status', 'Please wait. Error loading ' + src); + setText(test + '-size', 'Error'); + } + + callback.apply(); + }; + + xhr.send(null); + } catch (e) { + setText('status', 'Please wait. Error loading ' + src); + callback.apply(); + } + } + + function loadNextTest() { + var test; + + if (index < fixtureList.length) { + test = fixtureList[index]; + index += 1; + setText('status', 'Please wait. Loading ' + test + + ' (' + index + ' of ' + fixtureList.length + ')'); + window.setTimeout(function () { + load(slug(test), loadNextTest); + }, 100); + } else { + setText('total-size', kb(totalSize)); + setText('status', 'Ready.'); + enableRunButtons(); + } + } + + loadNextTest(); + } + + function setupParser() { + var i, j; + + suite = []; + for (i = 0; i < fixtureList.length; i += 1) { + for (j = 0; j < parsers.length; j += 1) { + suite.push({ + fixture: fixtureList[i], + parser: parsers[j] + }); + } + } + + createTable(); + } + + function runBenchmarks() { + + var index = 0, + totalTime = {}; + + function reset() { + var i, name; + for (i = 0; i < suite.length; i += 1) { + name = slug(suite[i].fixture) + '-' + slug(suite[i].parser); + setText(name + '-time', ''); + } + } + + function run() { + var fixture, parser, test, source, fn, benchmark; + + if (index >= suite.length) { + setText('status', 'Ready.'); + enableRunButtons(); + return; + } + + fixture = suite[index].fixture; + parser = suite[index].parser; + + source = window.data[slug(fixture)]; + + test = slug(fixture) + '-' + slug(parser); + setText(test + '-time', 'Running...'); + + setText('status', 'Please wait. Parsing ' + fixture + '...'); + + // Force the result to be held in this array, thus defeating any + // possible "dead code elimination" optimization. + window.tree = []; + + switch (parser) { + case 'Esprima': + fn = function () { + var syntax = window.esprima.parse(source); + window.tree.push(syntax.body.length); + }; + break; + + case 'parse-js': + fn = function () { + var syntax = window.parseJS.parse(source); + window.tree.push(syntax.length); + }; + break; + + case 'Acorn': + fn = function () { + var syntax = window.acorn.parse(source); + window.tree.push(syntax.body.length); + }; + break; + + default: + throw 'Unknown parser type ' + parser; + } + + benchmark = new window.Benchmark(test, fn, { + 'onComplete': function () { + setText(this.name + '-time', (1000 * this.stats.mean).toFixed(1)); + if (!totalTime[parser]) { + totalTime[parser] = this.stats.mean; + } else { + totalTime[parser] += this.stats.mean; + } + setText(slug(parser) + '-total', (1000 * totalTime[parser]).toFixed(1)); + } + }); + + window.setTimeout(function () { + benchmark.run(); + index += 1; + window.setTimeout(run, 211); + }, 211); + } + + + disableRunButtons(); + setText('status', 'Please wait. Running benchmarks...'); + + reset(); + run(); + } + + id('run').onclick = function () { + runBenchmarks(); + }; + + setText('benchmarkjs-version', ' version ' + window.Benchmark.version); + setText('version', window.esprima.version); + + setupParser(); + createTable(); + + disableRunButtons(); + loadFixtures(); + }; +} else { + // TODO + console.log('Not implemented yet!'); +} +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.html new file mode 100644 index 000000000..2ae18cc25 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.html @@ -0,0 +1,40 @@ + + + + +Esprima: Compatibility Tests + + + + + + + +
    + + + +

    Compatibility keeps everyone happy

    +

    Esprima version .

    +

    The following tests are to ensure that the syntax tree is compatible to +that produced by Mozilla SpiderMonkey +Parser reflection.

    +

    Please wait...

    +
    + +
    + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.js new file mode 100644 index 000000000..ee3a6295e --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/compat.js @@ -0,0 +1,239 @@ +/* + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint node: true */ +/*global document: true, window:true, esprima: true, testReflect: true */ + +var runTests; + +function getContext(esprima, reportCase, reportFailure) { + 'use strict'; + + var Reflect, Pattern; + + // Maps Mozilla Reflect object to our Esprima parser. + Reflect = { + parse: function (code) { + var result; + + reportCase(code); + + try { + result = esprima.parse(code); + } catch (error) { + result = error; + } + + return result; + } + }; + + // This is used by Reflect test suite to match a syntax tree. + Pattern = function (obj) { + var pattern; + + // Poor man's deep object cloning. + pattern = JSON.parse(JSON.stringify(obj)); + + // Special handling for regular expression literal since we need to + // convert it to a string literal, otherwise it will be decoded + // as object "{}" and the regular expression would be lost. + if (obj.type && obj.type === 'Literal') { + if (obj.value instanceof RegExp) { + pattern = { + type: obj.type, + value: obj.value.toString() + }; + } + } + + // Special handling for branch statement because SpiderMonkey + // prefers to put the 'alternate' property before 'consequent'. + if (obj.type && obj.type === 'IfStatement') { + pattern = { + type: pattern.type, + test: pattern.test, + consequent: pattern.consequent, + alternate: pattern.alternate + }; + } + + // Special handling for do while statement because SpiderMonkey + // prefers to put the 'test' property before 'body'. + if (obj.type && obj.type === 'DoWhileStatement') { + pattern = { + type: pattern.type, + body: pattern.body, + test: pattern.test + }; + } + + function adjustRegexLiteralAndRaw(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } else if (key === 'raw' && typeof value === "string") { + // Ignore Esprima-specific 'raw' property. + return undefined; + } + return value; + } + + if (obj.type && (obj.type === 'Program')) { + pattern.assert = function (tree) { + var actual, expected; + actual = JSON.stringify(tree, adjustRegexLiteralAndRaw, 4); + expected = JSON.stringify(obj, null, 4); + + if (expected !== actual) { + reportFailure(expected, actual); + } + }; + } + + return pattern; + }; + + return { + Reflect: Reflect, + Pattern: Pattern + }; +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + runTests = function () { + 'use strict'; + + var total = 0, + failures = 0; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function reportCase(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + total += 1; + } + + function reportFailure(expected, actual) { + var report, e; + + failures += 1; + + report = document.getElementById('report'); + + e = document.createElement('p'); + setText(e, 'Expected'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'expected'); + setText(e, expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'actual'); + setText(e, actual); + report.appendChild(e); + } + + setText(document.getElementById('version'), esprima.version); + + window.setTimeout(function () { + var tick, context = getContext(esprima, reportCase, reportFailure); + + tick = new Date(); + testReflect(context.Reflect, context.Pattern); + tick = (new Date()) - tick; + + if (failures > 0) { + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }, 513); + }; +} else { + (function (global) { + 'use strict'; + var esprima = require('../esprima'), + tick, + total = 0, + failures = [], + header, + current, + context; + + function reportCase(code) { + total += 1; + current = code; + } + + function reportFailure(expected, actual) { + failures.push({ + source: current, + expected: expected.toString(), + actual: actual.toString() + }); + } + + context = getContext(esprima, reportCase, reportFailure); + + tick = new Date(); + require('./reflect').testReflect(context.Reflect, context.Pattern); + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + }(this)); +} +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.footer.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.footer.html new file mode 100644 index 000000000..9943ff0f8 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.footer.html @@ -0,0 +1,3 @@ + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.header.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.header.html new file mode 100644 index 000000000..0885679aa --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.header.html @@ -0,0 +1,37 @@ + + + + +Esprima: Coverage Analysis Report + + + + +
    + + + +

    Coverage Analysis ensures systematic exercise of the parser

    + +

    Note: This is not a live (in-browser) code coverage report. +The analysis is performed offline +(using node-cover).
    + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.html new file mode 100644 index 000000000..696c682a8 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/coverage.html @@ -0,0 +1,4676 @@ + + + + +Esprima: Coverage Analysis Report + + + + +

    + + + +

    Coverage Analysis ensures systematic exercise of the parser

    + +

    Note: This is not a live (in-browser) code coverage report. +The analysis is performed offline +(using node-cover).
    + +Tested revision: b61b064 + (dated 4 Aug 2012 ).

    +
    +/*
    +    Copyright (C) 2012 Ariya Hidayat 
    +    Copyright (C) 2012 Mathias Bynens 
    +    Copyright (C) 2012 Joost-Wim Boekesteijn 
    +    Copyright (C) 2012 Kris Kowal 
    +    Copyright (C) 2012 Yusuke Suzuki 
    +    Copyright (C) 2012 Arpad Borsos 
    +    Copyright (C) 2011 Ariya Hidayat 
    +  
    +    Redistribution and use in source and binary forms, with or without
    +    modification, are permitted provided that the following conditions are met:
    +  
    +      * Redistributions of source code must retain the above copyright
    +        notice, this list of conditions and the following disclaimer.
    +      * Redistributions in binary form must reproduce the above copyright
    +        notice, this list of conditions and the following disclaimer in the
    +        documentation and/or other materials provided with the distribution.
    +  
    +    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    +    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    +    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    +    ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
    +    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    +    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    +    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    +    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    +    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +  */
    +  
    +  /*jslint bitwise:true plusplus:true */
    +  /*global esprima:true, define:true, exports:true, window: true,
    +  throwError: true, createLiteral: true, generateStatement: true,
    +  parseAssignmentExpression: true, parseBlock: true,
    +  parseClassExpression: true, parseClassDeclaration: true, parseExpression: true,
    +  parseFunctionDeclaration: true, parseFunctionExpression: true,
    +  parseFunctionSourceElements: true, parseVariableIdentifier: true,
    +  parseImportSpecifier: true,
    +  parseLeftHandSideExpression: true,
    +  parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true,
    +  parseYieldExpression: true
    +  */
    +  
    +  (function (factory) {
    +      'use strict';
    +  
    +      // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    +      // and plain browser loading,
    +      if (typeof define === 'function' && define.amd) {
    +          define(['exports'], factory);
    +      } else if (typeof exports !== 'undefined') {
    +          factory(exports);
    +      } else {
    +          factory((window.esprima = {}));
    +      }
    +  }(function (exports) {
    +      'use strict';
    +  
    +      var Token,
    +          TokenName,
    +          Syntax,
    +          PropertyKind,
    +          Messages,
    +          Regex,
    +          source,
    +          strict,
    +          yieldAllowed,
    +          yieldFound,
    +          index,
    +          lineNumber,
    +          lineStart,
    +          length,
    +          buffer,
    +          state,
    +          extra;
    +  
    +      Token = {
    +          BooleanLiteral: 1,
    +          EOF: 2,
    +          Identifier: 3,
    +          Keyword: 4,
    +          NullLiteral: 5,
    +          NumericLiteral: 6,
    +          Punctuator: 7,
    +          StringLiteral: 8
    +      };
    +  
    +      TokenName = {};
    +      TokenName[Token.BooleanLiteral] = 'Boolean';
    +      TokenName[Token.EOF] = '';
    +      TokenName[Token.Identifier] = 'Identifier';
    +      TokenName[Token.Keyword] = 'Keyword';
    +      TokenName[Token.NullLiteral] = 'Null';
    +      TokenName[Token.NumericLiteral] = 'Numeric';
    +      TokenName[Token.Punctuator] = 'Punctuator';
    +      TokenName[Token.StringLiteral] = 'String';
    +  
    +      Syntax = {
    +          ArrayExpression: 'ArrayExpression',
    +          ArrayPattern: 'ArrayPattern',
    +          ArrowFunctionExpression: 'ArrowFunctionExpression',
    +          AssignmentExpression: 'AssignmentExpression',
    +          BinaryExpression: 'BinaryExpression',
    +          BlockStatement: 'BlockStatement',
    +          BreakStatement: 'BreakStatement',
    +          CallExpression: 'CallExpression',
    +          CatchClause: 'CatchClause',
    +          ClassBody: 'ClassBody',
    +          ClassDeclaration: 'ClassDeclaration',
    +          ClassExpression: 'ClassExpression',
    +          MethodDefinition: 'MethodDefinition',
    +          ClassHeritage: 'ClassHeritage',
    +          ConditionalExpression: 'ConditionalExpression',
    +          ContinueStatement: 'ContinueStatement',
    +          DebuggerStatement: 'DebuggerStatement',
    +          DoWhileStatement: 'DoWhileStatement',
    +          EmptyStatement: 'EmptyStatement',
    +          ExportDeclaration: 'ExportDeclaration',
    +          ExportSpecifier: 'ExportSpecifier',
    +          ExportSpecifierSet: 'ExportSpecifierSet',
    +          ExpressionStatement: 'ExpressionStatement',
    +          ForInStatement: 'ForInStatement',
    +          ForOfStatement: 'ForOfStatement',
    +          ForStatement: 'ForStatement',
    +          FunctionDeclaration: 'FunctionDeclaration',
    +          FunctionExpression: 'FunctionExpression',
    +          Glob: 'Glob',
    +          Identifier: 'Identifier',
    +          IfStatement: 'IfStatement',
    +          ImportDeclaration: 'ImportDeclaration',
    +          ImportSpecifier: 'ImportSpecifier',
    +          LabeledStatement: 'LabeledStatement',
    +          Literal: 'Literal',
    +          LogicalExpression: 'LogicalExpression',
    +          MemberExpression: 'MemberExpression',
    +          ModuleDeclaration: 'ModuleDeclaration',
    +          NewExpression: 'NewExpression',
    +          ObjectExpression: 'ObjectExpression',
    +          ObjectPattern: 'ObjectPattern',
    +          Path:  'Path',
    +          Program: 'Program',
    +          Property: 'Property',
    +          ReturnStatement: 'ReturnStatement',
    +          SequenceExpression: 'SequenceExpression',
    +          SwitchCase: 'SwitchCase',
    +          SwitchStatement: 'SwitchStatement',
    +          ThisExpression: 'ThisExpression',
    +          ThrowStatement: 'ThrowStatement',
    +          TryStatement: 'TryStatement',
    +          UnaryExpression: 'UnaryExpression',
    +          UpdateExpression: 'UpdateExpression',
    +          VariableDeclaration: 'VariableDeclaration',
    +          VariableDeclarator: 'VariableDeclarator',
    +          WhileStatement: 'WhileStatement',
    +          WithStatement: 'WithStatement',
    +          YieldExpression: 'YieldExpression'
    +      };
    +  
    +      PropertyKind = {
    +          Data: 1,
    +          Get: 2,
    +          Set: 4
    +      };
    +  
    +      // Error messages should be identical to V8.
    +      Messages = {
    +          UnexpectedToken:  'Unexpected token %0',
    +          UnexpectedNumber:  'Unexpected number',
    +          UnexpectedString:  'Unexpected string',
    +          UnexpectedIdentifier:  'Unexpected identifier',
    +          UnexpectedReserved:  'Unexpected reserved word',
    +          UnexpectedEOS:  'Unexpected end of input',
    +          NewlineAfterThrow:  'Illegal newline after throw',
    +          InvalidRegExp: 'Invalid regular expression',
    +          UnterminatedRegExp:  'Invalid regular expression: missing /',
    +          InvalidLHSInAssignment:  'Invalid left-hand side in assignment',
    +          InvalidLHSInForIn:  'Invalid left-hand side in for-in',
    +          MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
    +          NoCatchOrFinally:  'Missing catch or finally after try',
    +          UnknownLabel: 'Undefined label \'%0\'',
    +          Redeclaration: '%0 \'%1\' has already been declared',
    +          IllegalContinue: 'Illegal continue statement',
    +          IllegalBreak: 'Illegal break statement',
    +          IllegalReturn: 'Illegal return statement',
    +          IllegalYield: 'Illegal yield expression',
    +          StrictModeWith:  'Strict mode code may not include a with statement',
    +          StrictCatchVariable:  'Catch variable may not be eval or arguments in strict mode',
    +          StrictVarName:  'Variable name may not be eval or arguments in strict mode',
    +          StrictParamName:  'Parameter name eval or arguments is not allowed in strict mode',
    +          StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
    +          StrictFunctionName:  'Function name may not be eval or arguments in strict mode',
    +          StrictOctalLiteral:  'Octal literals are not allowed in strict mode.',
    +          StrictDelete:  'Delete of an unqualified identifier in strict mode.',
    +          StrictDuplicateProperty:  'Duplicate data property in object literal not allowed in strict mode',
    +          AccessorDataProperty:  'Object literal may not have data and accessor property with the same name',
    +          AccessorGetSet:  'Object literal may not have multiple get/set accessors with the same name',
    +          StrictLHSAssignment:  'Assignment to eval or arguments is not allowed in strict mode',
    +          StrictLHSPostfix:  'Postfix increment/decrement may not have eval or arguments operand in strict mode',
    +          StrictLHSPrefix:  'Prefix increment/decrement may not have eval or arguments operand in strict mode',
    +          StrictReservedWord:  'Use of future reserved word in strict mode',
    +          NoFromAfterImport: 'Missing from after import',
    +          NoYieldInGenerator: 'Missing yield in generator'
    +      };
    +  
    +      // See also tools/generate-unicode-regex.py.
    +      Regex = {
    +          NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\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\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\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-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\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-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\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-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\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]'),
    +          NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\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\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\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\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
    +      };
    +  
    +      // Ensure the condition is true, otherwise throw an error.
    +      // This is only to have a better contract semantic, i.e. another safety net
    +      // to catch a logic error. The condition shall be fulfilled in normal case.
    +      // Do NOT use this to enforce a certain condition on any user input.
    +  
    +      function assert(condition, message) {
    +          if (!condition) {
    +              throw new Error('ASSERT: ' + message);
    +          }
    +      }
    +  
    +      function sliceSource(from, to) {
    +          return source.slice(from, to);
    +      }
    +  
    +      if (typeof 'esprima'[0] === 'undefined') {
    +          sliceSource = function sliceArraySource(from, to) {
    +              return source.slice(from, to).join('');
    +          };
    +      }
    +  
    +      function isDecimalDigit(ch) {
    +          return '0123456789'.indexOf(ch) >= 0;
    +      }
    +  
    +      function isHexDigit(ch) {
    +          return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
    +      }
    +  
    +      function isOctalDigit(ch) {
    +          return '01234567'.indexOf(ch) >= 0;
    +      }
    +  
    +  
    +      // 7.2 White Space
    +  
    +      function isWhiteSpace(ch) {
    +          return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
    +              (ch === '\u000C') || (ch === '\u00A0') ||
    +              (ch.charCodeAt(0) >= 0x1680 &&
    +               '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
    +      }
    +  
    +      // 7.3 Line Terminators
    +  
    +      function isLineTerminator(ch) {
    +          return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
    +      }
    +  
    +      // 7.6 Identifier Names and Identifiers
    +  
    +      function isIdentifierStart(ch) {
    +          return (ch === '$') || (ch === '_') || (ch === '\\') ||
    +              (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
    +              ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
    +      }
    +  
    +      function isIdentifierPart(ch) {
    +          return (ch === '$') || (ch === '_') || (ch === '\\') ||
    +              (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
    +              ((ch >= '0') && (ch <= '9')) ||
    +              ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
    +      }
    +  
    +      // 7.6.1.2 Future Reserved Words
    +  
    +      function isFutureReservedWord(id) {
    +          switch (id) {
    +  
    +          // Future reserved words.
    +          case 'class':
    +          case 'enum':
    +          case 'export':
    +          case 'extends':
    +          case 'import':
    +          case 'super':
    +              return true;
    +          }
    +  
    +          return false;
    +      }
    +  
    +      function isStrictModeReservedWord(id) {
    +          switch (id) {
    +  
    +          // Strict Mode reserved words.
    +          case 'implements':
    +          case 'interface':
    +          case 'package':
    +          case 'private':
    +          case 'protected':
    +          case 'public':
    +          case 'static':
    +          case 'yield':
    +          case 'let':
    +              return true;
    +          }
    +  
    +          return false;
    +      }
    +  
    +      function isRestrictedWord(id) {
    +          return id === 'eval' || id === 'arguments';
    +      }
    +  
    +      // 7.6.1.1 Keywords
    +  
    +      function isKeyword(id) {
    +          var keyword = false;
    +          switch (id.length) {
    +          case 2:
    +              keyword = (id === 'if') || (id === 'in') || (id === 'do');
    +              break;
    +          case 3:
    +              keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
    +              break;
    +          case 4:
    +              keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
    +              break;
    +          case 5:
    +              keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
    +              break;
    +          case 6:
    +              keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
    +              break;
    +          case 7:
    +              keyword = (id === 'default') || (id === 'finally');
    +              break;
    +          case 8:
    +              keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
    +              break;
    +          case 10:
    +              keyword = (id === 'instanceof');
    +              break;
    +          }
    +  
    +          if (keyword) {
    +              return true;
    +          }
    +  
    +          switch (id) {
    +          // Future reserved words.
    +          // 'const' is specialized as Keyword in V8.
    +          case 'const':
    +              return true;
    +  
    +          // For compatiblity to SpiderMonkey and ES.next
    +          case 'yield':
    +          case 'let':
    +              return true;
    +          }
    +  
    +          if (strict && isStrictModeReservedWord(id)) {
    +              return true;
    +          }
    +  
    +          return isFutureReservedWord(id);
    +      }
    +  
    +      // Return the next character and move forward.
    +  
    +      function nextChar() {
    +          return source[index++];
    +      }
    +  
    +      // 7.4 Comments
    +  
    +      function skipComment() {
    +          var ch, blockComment, lineComment;
    +  
    +          blockComment = false;
    +          lineComment = false;
    +  
    +          while (index < length) {
    +              ch = source[index];
    +  
    +              if (lineComment) {
    +                  ch = nextChar();
    +                  if (isLineTerminator(ch)) {
    +                      lineComment = false;
    +                      if (ch === '\r' && source[index] === '\n') {
    +                          ++index;
    +                      }
    +                      ++lineNumber;
    +                      lineStart = index;
    +                  }
    +              } else if (blockComment) {
    +                  if (isLineTerminator(ch)) {
    +                      if (ch === '\r' && source[index + 1] === '\n') {
    +                          ++index;
    +                      }
    +                      ++lineNumber;
    +                      ++index;
    +                      lineStart = index;
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                  } else {
    +                      ch = nextChar();
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                      if (ch === '*') {
    +                          ch = source[index];
    +                          if (ch === '/') {
    +                              ++index;
    +                              blockComment = false;
    +                          }
    +                      }
    +                  }
    +              } else if (ch === '/') {
    +                  ch = source[index + 1];
    +                  if (ch === '/') {
    +                      index += 2;
    +                      lineComment = true;
    +                  } else if (ch === '*') {
    +                      index += 2;
    +                      blockComment = true;
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                  } else {
    +                      break;
    +                  }
    +              } else if (isWhiteSpace(ch)) {
    +                  ++index;
    +              } else if (isLineTerminator(ch)) {
    +                  ++index;
    +                  if (ch ===  '\r' && source[index] === '\n') {
    +                      ++index;
    +                  }
    +                  ++lineNumber;
    +                  lineStart = index;
    +              } else {
    +                  break;
    +              }
    +          }
    +      }
    +  
    +      function scanHexEscape(prefix) {
    +          var i, len, ch, code = 0;
    +  
    +          len = (prefix === 'u') ? 4 : 2;
    +          for (i = 0; i < len; ++i) {
    +              if (index < length && isHexDigit(source[index])) {
    +                  ch = nextChar();
    +                  code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
    +              } else {
    +                  return '';
    +              }
    +          }
    +          return String.fromCharCode(code);
    +      }
    +  
    +      function scanUnicodeCodePointEscape() {
    +          var ch, code, cu1, cu2;
    +  
    +          ch = source[index];
    +          code = 0;
    +  
    +          // At least, one hex digit is required.
    +          if (ch === '}') {
    +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +          }
    +  
    +          while (index < length) {
    +              ch = nextChar();
    +              if (!isHexDigit(ch)) {
    +                  break;
    +              }
    +              code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
    +          }
    +  
    +          if (code > 0x10FFFF || ch !== '}') {
    +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +          }
    +  
    +          // UTF-16 Encoding
    +          if (code <= 0xFFFF) {
    +              return String.fromCharCode(code);
    +          }
    +          cu1 = ((code - 0x10000) >> 10) + 0xD800;
    +          cu2 = ((code - 0x10000) & 1023) + 0xDC00;
    +          return String.fromCharCode(cu1, cu2);
    +      }
    +  
    +      function scanIdentifier() {
    +          var ch, start, id, restore;
    +  
    +          ch = source[index];
    +          if (!isIdentifierStart(ch)) {
    +              return;
    +          }
    +  
    +          start = index;
    +          if (ch === '\\') {
    +              ++index;
    +              if (source[index] !== 'u') {
    +                  return;
    +              }
    +              ++index;
    +              restore = index;
    +              ch = scanHexEscape('u');
    +              if (ch) {
    +                  if (ch === '\\' || !isIdentifierStart(ch)) {
    +                      return;
    +                  }
    +                  id = ch;
    +              } else {
    +                  index = restore;
    +                  id = 'u';
    +              }
    +          } else {
    +              id = nextChar();
    +          }
    +  
    +          while (index < length) {
    +              ch = source[index];
    +              if (!isIdentifierPart(ch)) {
    +                  break;
    +              }
    +              if (ch === '\\') {
    +                  ++index;
    +                  if (source[index] !== 'u') {
    +                      return;
    +                  }
    +                  ++index;
    +                  restore = index;
    +                  ch = scanHexEscape('u');
    +                  if (ch) {
    +                      if (ch === '\\' || !isIdentifierPart(ch)) {
    +                          return;
    +                      }
    +                      id += ch;
    +                  } else {
    +                      index = restore;
    +                      id += 'u';
    +                  }
    +              } else {
    +                  id += nextChar();
    +              }
    +          }
    +  
    +          // There is no keyword or literal with only one character.
    +          // Thus, it must be an identifier.
    +          if (id.length === 1) {
    +              return {
    +                  type: Token.Identifier,
    +                  value: id,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (isKeyword(id)) {
    +              return {
    +                  type: Token.Keyword,
    +                  value: id,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // 7.8.1 Null Literals
    +  
    +          if (id === 'null') {
    +              return {
    +                  type: Token.NullLiteral,
    +                  value: id,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // 7.8.2 Boolean Literals
    +  
    +          if (id === 'true' || id === 'false') {
    +              return {
    +                  type: Token.BooleanLiteral,
    +                  value: id,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          return {
    +              type: Token.Identifier,
    +              value: id,
    +              lineNumber: lineNumber,
    +              lineStart: lineStart,
    +              range: [start, index]
    +          };
    +      }
    +  
    +      // 7.7 Punctuators
    +  
    +      function scanPunctuator() {
    +          var start = index,
    +              ch1 = source[index],
    +              ch2,
    +              ch3,
    +              ch4;
    +  
    +          // Check for most common single-character punctuators.
    +  
    +          if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
    +              ++index;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: ch1,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
    +              ++index;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: ch1,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // Dot (.) can also start a floating-point number, hence the need
    +          // to check the next character.
    +  
    +          ch2 = source[index + 1];
    +          if (ch1 === '.' && !isDecimalDigit(ch2)) {
    +              return {
    +                  type: Token.Punctuator,
    +                  value: nextChar(),
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // Peek more characters.
    +  
    +          ch3 = source[index + 2];
    +          ch4 = source[index + 3];
    +  
    +          // 4-character punctuator: >>>=
    +  
    +          if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
    +              if (ch4 === '=') {
    +                  index += 4;
    +                  return {
    +                      type: Token.Punctuator,
    +                      value: '>>>=',
    +                      lineNumber: lineNumber,
    +                      lineStart: lineStart,
    +                      range: [start, index]
    +                  };
    +              }
    +          }
    +  
    +          // 3-character punctuators: === !== >>> <<= >>=
    +  
    +          if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
    +              index += 3;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '===',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
    +              index += 3;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '!==',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
    +              index += 3;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '>>>',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
    +              index += 3;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '<<=',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
    +              index += 3;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '>>=',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // 2-character punctuators: <= >= == != ++ -- << >> && ||
    +          // += -= *= %= &= |= ^= /=
    +  
    +          if (ch2 === '=') {
    +              if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
    +                  index += 2;
    +                  return {
    +                      type: Token.Punctuator,
    +                      value: ch1 + ch2,
    +                      lineNumber: lineNumber,
    +                      lineStart: lineStart,
    +                      range: [start, index]
    +                  };
    +              }
    +          }
    +  
    +          if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
    +              if ('+-<>&|'.indexOf(ch2) >= 0) {
    +                  index += 2;
    +                  return {
    +                      type: Token.Punctuator,
    +                      value: ch1 + ch2,
    +                      lineNumber: lineNumber,
    +                      lineStart: lineStart,
    +                      range: [start, index]
    +                  };
    +              }
    +          }
    +  
    +          if (ch1 === '=' && ch2 === '>') {
    +              index += 2;
    +              return {
    +                  type: Token.Punctuator,
    +                  value: '=>',
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +  
    +          // The remaining 1-character punctuators.
    +  
    +          if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
    +              return {
    +                  type: Token.Punctuator,
    +                  value: nextChar(),
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [start, index]
    +              };
    +          }
    +      }
    +  
    +      // 7.8.3 Numeric Literals
    +  
    +      function scanNumericLiteral() {
    +          var number, start, ch, octal;
    +  
    +          ch = source[index];
    +          assert(isDecimalDigit(ch) || (ch === '.'),
    +              'Numeric literal must start with a decimal digit or a decimal point');
    +  
    +          start = index;
    +          number = '';
    +          if (ch !== '.') {
    +              number = nextChar();
    +              ch = source[index];
    +  
    +              // Hex number starts with '0x'.
    +              // Octal number starts with '0'.
    +              // Octal number in ES6 starts with '0o'.
    +              // Binary number in ES6 starts with '0b'.
    +              if (number === '0') {
    +                  if (ch === 'x' || ch === 'X') {
    +                      number += nextChar();
    +                      while (index < length) {
    +                          ch = source[index];
    +                          if (!isHexDigit(ch)) {
    +                              break;
    +                          }
    +                          number += nextChar();
    +                      }
    +  
    +                      if (number.length <= 2) {
    +                          // only 0x
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +  
    +                      if (index < length) {
    +                          ch = source[index];
    +                          if (isIdentifierStart(ch)) {
    +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                          }
    +                      }
    +                      return {
    +                          type: Token.NumericLiteral,
    +                          value: parseInt(number, 16),
    +                          lineNumber: lineNumber,
    +                          lineStart: lineStart,
    +                          range: [start, index]
    +                      };
    +                  } else if (ch === 'b' || ch === 'B') {
    +                      nextChar();
    +                      number = '';
    +  
    +                      while (index < length) {
    +                          ch = source[index];
    +                          if (ch !== '0' && ch !== '1') {
    +                              break;
    +                          }
    +                          number += nextChar();
    +                      }
    +  
    +                      if (number.length === 0) {
    +                          // only 0b or 0B
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +  
    +                      if (index < length) {
    +                          ch = source[index];
    +                          if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
    +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                          }
    +                      }
    +                      return {
    +                          type: Token.NumericLiteral,
    +                          value: parseInt(number, 2),
    +                          lineNumber: lineNumber,
    +                          lineStart: lineStart,
    +                          range: [start, index]
    +                      };
    +                  } else if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
    +                      if (isOctalDigit(ch)) {
    +                          octal = true;
    +                          number = nextChar();
    +                      } else {
    +                          octal = false;
    +                          nextChar();
    +                          number = '';
    +                      }
    +  
    +                      while (index < length) {
    +                          ch = source[index];
    +                          if (!isOctalDigit(ch)) {
    +                              break;
    +                          }
    +                          number += nextChar();
    +                      }
    +  
    +                      if (number.length === 0) {
    +                          // only 0o or 0O
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +  
    +                      if (index < length) {
    +                          ch = source[index];
    +                          if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
    +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                          }
    +                      }
    +  
    +                      return {
    +                          type: Token.NumericLiteral,
    +                          value: parseInt(number, 8),
    +                          octal: octal,
    +                          lineNumber: lineNumber,
    +                          lineStart: lineStart,
    +                          range: [start, index]
    +                      };
    +                  }
    +  
    +                  // decimal number starts with '0' such as '09' is illegal.
    +                  if (isDecimalDigit(ch)) {
    +                      throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                  }
    +              }
    +  
    +              while (index < length) {
    +                  ch = source[index];
    +                  if (!isDecimalDigit(ch)) {
    +                      break;
    +                  }
    +                  number += nextChar();
    +              }
    +          }
    +  
    +          if (ch === '.') {
    +              number += nextChar();
    +              while (index < length) {
    +                  ch = source[index];
    +                  if (!isDecimalDigit(ch)) {
    +                      break;
    +                  }
    +                  number += nextChar();
    +              }
    +          }
    +  
    +          if (ch === 'e' || ch === 'E') {
    +              number += nextChar();
    +  
    +              ch = source[index];
    +              if (ch === '+' || ch === '-') {
    +                  number += nextChar();
    +              }
    +  
    +              ch = source[index];
    +              if (isDecimalDigit(ch)) {
    +                  number += nextChar();
    +                  while (index < length) {
    +                      ch = source[index];
    +                      if (!isDecimalDigit(ch)) {
    +                          break;
    +                      }
    +                      number += nextChar();
    +                  }
    +              } else {
    +                  ch = 'character ' + ch;
    +                  if (index >= length) {
    +                      ch = '';
    +                  }
    +                  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +              }
    +          }
    +  
    +          if (index < length) {
    +              ch = source[index];
    +              if (isIdentifierStart(ch)) {
    +                  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +              }
    +          }
    +  
    +          return {
    +              type: Token.NumericLiteral,
    +              value: parseFloat(number),
    +              lineNumber: lineNumber,
    +              lineStart: lineStart,
    +              range: [start, index]
    +          };
    +      }
    +  
    +      // 7.8.4 String Literals
    +  
    +      function scanStringLiteral() {
    +          var str = '', quote, start, ch, code, unescaped, restore, octal = false;
    +  
    +          quote = source[index];
    +          assert((quote === '\'' || quote === '"'),
    +              'String literal must starts with a quote');
    +  
    +          start = index;
    +          ++index;
    +  
    +          while (index < length) {
    +              ch = nextChar();
    +  
    +              if (ch === quote) {
    +                  quote = '';
    +                  break;
    +              } else if (ch === '\\') {
    +                  ch = nextChar();
    +                  if (!isLineTerminator(ch)) {
    +                      switch (ch) {
    +                      case 'n':
    +                          str += '\n';
    +                          break;
    +                      case 'r':
    +                          str += '\r';
    +                          break;
    +                      case 't':
    +                          str += '\t';
    +                          break;
    +                      case 'u':
    +                      case 'x':
    +                          if (source[index] === '{') {
    +                              ++index;
    +                              str += scanUnicodeCodePointEscape();
    +                          } else {
    +                              restore = index;
    +                              unescaped = scanHexEscape(ch);
    +                              if (unescaped) {
    +                                  str += unescaped;
    +                              } else {
    +                                  index = restore;
    +                                  str += ch;
    +                              }
    +                          }
    +                          break;
    +                      case 'b':
    +                          str += '\b';
    +                          break;
    +                      case 'f':
    +                          str += '\f';
    +                          break;
    +                      case 'v':
    +                          str += '\v';
    +                          break;
    +  
    +                      default:
    +                          if (isOctalDigit(ch)) {
    +                              code = '01234567'.indexOf(ch);
    +  
    +                              // \0 is not octal escape sequence
    +                              if (code !== 0) {
    +                                  octal = true;
    +                              }
    +  
    +                              if (index < length && isOctalDigit(source[index])) {
    +                                  octal = true;
    +                                  code = code * 8 + '01234567'.indexOf(nextChar());
    +  
    +                                  // 3 digits are only allowed when string starts
    +                                  // with 0, 1, 2, 3
    +                                  if ('0123'.indexOf(ch) >= 0 &&
    +                                          index < length &&
    +                                          isOctalDigit(source[index])) {
    +                                      code = code * 8 + '01234567'.indexOf(nextChar());
    +                                  }
    +                              }
    +                              str += String.fromCharCode(code);
    +                          } else {
    +                              str += ch;
    +                          }
    +                          break;
    +                      }
    +                  } else {
    +                      ++lineNumber;
    +                      if (ch ===  '\r' && source[index] === '\n') {
    +                          ++index;
    +                      }
    +                  }
    +              } else if (isLineTerminator(ch)) {
    +                  break;
    +              } else {
    +                  str += ch;
    +              }
    +          }
    +  
    +          if (quote !== '') {
    +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +          }
    +  
    +          return {
    +              type: Token.StringLiteral,
    +              value: str,
    +              octal: octal,
    +              lineNumber: lineNumber,
    +              lineStart: lineStart,
    +              range: [start, index]
    +          };
    +      }
    +  
    +      function scanRegExp() {
    +          var str = '', ch, start, pattern, flags, value, classMarker = false, restore;
    +  
    +          buffer = null;
    +          skipComment();
    +  
    +          start = index;
    +          ch = source[index];
    +          assert(ch === '/', 'Regular expression literal must start with a slash');
    +          str = nextChar();
    +  
    +          while (index < length) {
    +              ch = nextChar();
    +              str += ch;
    +              if (classMarker) {
    +                  if (ch === ']') {
    +                      classMarker = false;
    +                  }
    +              } else {
    +                  if (ch === '\\') {
    +                      ch = nextChar();
    +                      // ECMA-262 7.8.5
    +                      if (isLineTerminator(ch)) {
    +                          throwError({}, Messages.UnterminatedRegExp);
    +                      }
    +                      str += ch;
    +                  } else if (ch === '/') {
    +                      break;
    +                  } else if (ch === '[') {
    +                      classMarker = true;
    +                  } else if (isLineTerminator(ch)) {
    +                      throwError({}, Messages.UnterminatedRegExp);
    +                  }
    +              }
    +          }
    +  
    +          if (str.length === 1) {
    +              throwError({}, Messages.UnterminatedRegExp);
    +          }
    +  
    +          // Exclude leading and trailing slash.
    +          pattern = str.substr(1, str.length - 2);
    +  
    +          flags = '';
    +          while (index < length) {
    +              ch = source[index];
    +              if (!isIdentifierPart(ch)) {
    +                  break;
    +              }
    +  
    +              ++index;
    +              if (ch === '\\' && index < length) {
    +                  ch = source[index];
    +                  if (ch === 'u') {
    +                      ++index;
    +                      restore = index;
    +                      ch = scanHexEscape('u');
    +                      if (ch) {
    +                          flags += ch;
    +                          str += '\\u';
    +                          for (; restore < index; ++restore) {
    +                              str += source[restore];
    +                          }
    +                      } else {
    +                          index = restore;
    +                          flags += 'u';
    +                          str += '\\u';
    +                      }
    +                  } else {
    +                      str += '\\';
    +                  }
    +              } else {
    +                  flags += ch;
    +                  str += ch;
    +              }
    +          }
    +  
    +          try {
    +              value = new RegExp(pattern, flags);
    +          } catch (e) {
    +              throwError({}, Messages.InvalidRegExp);
    +          }
    +  
    +          return {
    +              literal: str,
    +              value: value,
    +              range: [start, index]
    +          };
    +      }
    +  
    +      function isIdentifierName(token) {
    +          return token.type === Token.Identifier ||
    +              token.type === Token.Keyword ||
    +              token.type === Token.BooleanLiteral ||
    +              token.type === Token.NullLiteral;
    +      }
    +  
    +      function advance() {
    +          var ch, token;
    +  
    +          skipComment();
    +  
    +          if (index >= length) {
    +              return {
    +                  type: Token.EOF,
    +                  lineNumber: lineNumber,
    +                  lineStart: lineStart,
    +                  range: [index, index]
    +              };
    +          }
    +  
    +          token = scanPunctuator();
    +          if (typeof token !== 'undefined') {
    +              return token;
    +          }
    +  
    +          ch = source[index];
    +  
    +          if (ch === '\'' || ch === '"') {
    +              return scanStringLiteral();
    +          }
    +  
    +          if (ch === '.' || isDecimalDigit(ch)) {
    +              return scanNumericLiteral();
    +          }
    +  
    +          token = scanIdentifier();
    +          if (typeof token !== 'undefined') {
    +              return token;
    +          }
    +  
    +          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +      }
    +  
    +      function lex() {
    +          var token;
    +  
    +          if (buffer) {
    +              index = buffer.range[1];
    +              lineNumber = buffer.lineNumber;
    +              lineStart = buffer.lineStart;
    +              token = buffer;
    +              buffer = null;
    +              return token;
    +          }
    +  
    +          buffer = null;
    +          return advance();
    +      }
    +  
    +      function lookahead() {
    +          var pos, line, start;
    +  
    +          if (buffer !== null) {
    +              return buffer;
    +          }
    +  
    +          pos = index;
    +          line = lineNumber;
    +          start = lineStart;
    +          buffer = advance();
    +          index = pos;
    +          lineNumber = line;
    +          lineStart = start;
    +  
    +          return buffer;
    +      }
    +  
    +      function lookahead2() {
    +          var adv, pos, line, start, result;
    +  
    +          // If we are collecting the tokens, don't grab the next one yet.
    +          adv = (typeof extra.advance === 'function') ? extra.advance : advance;
    +  
    +          pos = index;
    +          line = lineNumber;
    +          start = lineStart;
    +  
    +          // Scan for the next immediate token.
    +          if (buffer === null) {
    +              buffer = adv();
    +          }
    +          index = buffer.range[1];
    +          lineNumber = buffer.lineNumber;
    +          lineStart = buffer.lineStart;
    +  
    +          // Grab the token right after.
    +          result = adv();
    +          index = pos;
    +          lineNumber = line;
    +          lineStart = start;
    +  
    +          return result;
    +      }
    +  
    +      // Return true if there is a line terminator before the next token.
    +  
    +      function peekLineTerminator() {
    +          var pos, line, start, found;
    +  
    +          pos = index;
    +          line = lineNumber;
    +          start = lineStart;
    +          skipComment();
    +          found = lineNumber !== line;
    +          index = pos;
    +          lineNumber = line;
    +          lineStart = start;
    +  
    +          return found;
    +      }
    +  
    +      // Throw an exception
    +  
    +      function throwError(token, messageFormat) {
    +          var error,
    +              args = Array.prototype.slice.call(arguments, 2),
    +              msg = messageFormat.replace(
    +                  /%(\d)/g,
    +                  function (whole, index) {
    +                      return args[index] || '';
    +                  }
    +              );
    +  
    +          if (typeof token.lineNumber === 'number') {
    +              error = new Error('Line ' + token.lineNumber + ': ' + msg);
    +              error.index = token.range[0];
    +              error.lineNumber = token.lineNumber;
    +              error.column = token.range[0] - lineStart + 1;
    +          } else {
    +              error = new Error('Line ' + lineNumber + ': ' + msg);
    +              error.index = index;
    +              error.lineNumber = lineNumber;
    +              error.column = index - lineStart + 1;
    +          }
    +  
    +          throw error;
    +      }
    +  
    +      function throwErrorTolerant() {
    +          try {
    +              throwError.apply(null, arguments);
    +          } catch (e) {
    +              if (extra.errors) {
    +                  extra.errors.push(e);
    +              } else {
    +                  throw e;
    +              }
    +          }
    +      }
    +  
    +  
    +      // Throw an exception because of the token.
    +  
    +      function throwUnexpected(token) {
    +          if (token.type === Token.EOF) {
    +              throwError(token, Messages.UnexpectedEOS);
    +          }
    +  
    +          if (token.type === Token.NumericLiteral) {
    +              throwError(token, Messages.UnexpectedNumber);
    +          }
    +  
    +          if (token.type === Token.StringLiteral) {
    +              throwError(token, Messages.UnexpectedString);
    +          }
    +  
    +          if (token.type === Token.Identifier) {
    +              throwError(token, Messages.UnexpectedIdentifier);
    +          }
    +  
    +          if (token.type === Token.Keyword) {
    +              if (isFutureReservedWord(token.value)) {
    +                  throwError(token, Messages.UnexpectedReserved);
    +              } else if (strict && isStrictModeReservedWord(token.value)) {
    +                  throwError(token, Messages.StrictReservedWord);
    +              }
    +              throwError(token, Messages.UnexpectedToken, token.value);
    +          }
    +  
    +          // BooleanLiteral, NullLiteral, or Punctuator.
    +          throwError(token, Messages.UnexpectedToken, token.value);
    +      }
    +  
    +      // Expect the next token to match the specified punctuator.
    +      // If not, an exception will be thrown.
    +  
    +      function expect(value) {
    +          var token = lex();
    +          if (token.type !== Token.Punctuator || token.value !== value) {
    +              throwUnexpected(token);
    +          }
    +      }
    +  
    +      // Expect the next token to match the specified keyword.
    +      // If not, an exception will be thrown.
    +  
    +      function expectKeyword(keyword) {
    +          var token = lex();
    +          if (token.type !== Token.Keyword || token.value !== keyword) {
    +              throwUnexpected(token);
    +          }
    +      }
    +  
    +      // Return true if the next token matches the specified punctuator.
    +  
    +      function match(value) {
    +          var token = lookahead();
    +          return token.type === Token.Punctuator && token.value === value;
    +      }
    +  
    +      // Return true if the next token matches the specified keyword
    +  
    +      function matchKeyword(keyword) {
    +          var token = lookahead();
    +          return token.type === Token.Keyword && token.value === keyword;
    +      }
    +  
    +  
    +      // Return true if the next token matches the specified contextual keyword
    +  
    +      function matchContextualKeyword(keyword) {
    +          var token = lookahead();
    +          return token.type === Token.Identifier && token.value === keyword;
    +      }
    +  
    +      // Return true if the next token is an assignment operator
    +  
    +      function matchAssign() {
    +          var token = lookahead(),
    +              op = token.value;
    +  
    +          if (token.type !== Token.Punctuator) {
    +              return false;
    +          }
    +          return op === '=' ||
    +              op === '*=' ||
    +              op === '/=' ||
    +              op === '%=' ||
    +              op === '+=' ||
    +              op === '-=' ||
    +              op === '<<=' ||
    +              op === '>>=' ||
    +              op === '>>>=' ||
    +              op === '&=' ||
    +              op === '^=' ||
    +              op === '|=';
    +      }
    +  
    +      function consumeSemicolon() {
    +          var token, line;
    +  
    +          // Catch the very common case first.
    +          if (source[index] === ';') {
    +              lex();
    +              return;
    +          }
    +  
    +          line = lineNumber;
    +          skipComment();
    +          if (lineNumber !== line) {
    +              return;
    +          }
    +  
    +          if (match(';')) {
    +              lex();
    +              return;
    +          }
    +  
    +          token = lookahead();
    +          if (token.type !== Token.EOF && !match('}')) {
    +              throwUnexpected(token);
    +          }
    +          return;
    +      }
    +  
    +      // Return true if provided expression is LeftHandSideExpression
    +  
    +      function isLeftHandSide(expr) {
    +          return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
    +      }
    +  
    +      function isAssignableLeftHandSide(expr) {
    +          return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
    +      }
    +  
    +      // 11.1.4 Array Initialiser
    +  
    +      function parseArrayInitialiser() {
    +          var elements = [],
    +              undef;
    +  
    +          expect('[');
    +  
    +          while (!match(']')) {
    +              if (match(',')) {
    +                  lex();
    +                  elements.push(undef);
    +              } else {
    +                  elements.push(parseAssignmentExpression());
    +  
    +                  if (!match(']')) {
    +                      expect(',');
    +                  }
    +              }
    +          }
    +  
    +          expect(']');
    +  
    +          return {
    +              type: Syntax.ArrayExpression,
    +              elements: elements
    +          };
    +      }
    +  
    +      // 11.1.5 Object Initialiser
    +  
    +      function parsePropertyFunction(param, options) {
    +          var previousStrict, previousYieldAllowed, body;
    +  
    +          previousStrict = strict;
    +          previousYieldAllowed = yieldAllowed;
    +          yieldAllowed = options.generator;
    +          body = parseConciseBody();
    +          if (options.name && strict && isRestrictedWord(param[0].name)) {
    +              throwError(options.name, Messages.StrictParamName);
    +          }
    +          if (yieldAllowed && !yieldFound) {
    +              throwError({}, Messages.NoYieldInGenerator);
    +          }
    +          strict = previousStrict;
    +          yieldAllowed = previousYieldAllowed;
    +  
    +          return {
    +              type: Syntax.FunctionExpression,
    +              id: null,
    +              params: param,
    +              body: body,
    +              generator: options.generator
    +          };
    +      }
    +  
    +      function parsePropertyMethodFunction(options) {
    +          var token, previousStrict, param, params, paramSet, method;
    +  
    +          previousStrict = strict;
    +          strict = true;
    +          params = [];
    +  
    +          expect('(');
    +  
    +          if (!match(')')) {
    +              paramSet = {};
    +              while (index < length) {
    +                  token = lookahead();
    +                  param = parseVariableIdentifier();
    +                  if (isRestrictedWord(token.value)) {
    +                      throwError(token, Messages.StrictParamName);
    +                  }
    +                  if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
    +                      throwError(token, Messages.StrictParamDupe);
    +                  }
    +                  params.push(param);
    +                  paramSet[param.name] = true;
    +                  if (match(')')) {
    +                      break;
    +                  }
    +                  expect(',');
    +              }
    +          }
    +  
    +          expect(')');
    +  
    +          method = parsePropertyFunction(params, { generator: options.generator });
    +  
    +          strict = previousStrict;
    +  
    +          return method;
    +      }
    +  
    +      function parseObjectPropertyKey() {
    +          var token = lex();
    +  
    +          // Note: This function is called only from parseObjectProperty(), where
    +          // EOF and Punctuator tokens are already filtered out.
    +  
    +          if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
    +              if (strict && token.octal) {
    +                  throwError(token, Messages.StrictOctalLiteral);
    +              }
    +              return createLiteral(token);
    +          }
    +  
    +          return {
    +              type: Syntax.Identifier,
    +              name: token.value
    +          };
    +      }
    +  
    +      function parseObjectProperty() {
    +          var token, key, id, param;
    +  
    +          token = lookahead();
    +  
    +          if (token.type === Token.Identifier) {
    +  
    +              id = parseObjectPropertyKey();
    +  
    +              // Property Assignment: Getter and Setter.
    +  
    +              if (token.value === 'get' && !(match(':') || match('('))) {
    +                  key = parseObjectPropertyKey();
    +                  expect('(');
    +                  expect(')');
    +                  return {
    +                      type: Syntax.Property,
    +                      key: key,
    +                      value: parsePropertyFunction([], { generator: false }),
    +                      kind: 'get'
    +                  };
    +              } else if (token.value === 'set' && !(match(':') || match('('))) {
    +                  key = parseObjectPropertyKey();
    +                  expect('(');
    +                  token = lookahead();
    +                  param = [ parseVariableIdentifier() ];
    +                  expect(')');
    +                  return {
    +                      type: Syntax.Property,
    +                      key: key,
    +                      value: parsePropertyFunction(param, { generator: false, name: token }),
    +                      kind: 'set'
    +                  };
    +              } else {
    +                  if (match(':')) {
    +                      lex();
    +                      return {
    +                          type: Syntax.Property,
    +                          key: id,
    +                          value: parseAssignmentExpression(),
    +                          kind: 'init'
    +                      };
    +                  } else if (match('(')) {
    +                      return {
    +                          type: Syntax.Property,
    +                          key: id,
    +                          value: parsePropertyMethodFunction({ generator: false }),
    +                          kind: 'init',
    +                          method: true
    +                      };
    +                  } else {
    +                      return {
    +                          type: Syntax.Property,
    +                          key: id,
    +                          value: id,
    +                          kind: 'init',
    +                          shorthand: true
    +                      };
    +                  }
    +              }
    +          } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
    +              if (!match('*')) {
    +                  throwUnexpected(token);
    +              }
    +              lex();
    +  
    +              id = parseObjectPropertyKey();
    +  
    +              if (!match('(')) {
    +                  throwUnexpected(lex());
    +              }
    +  
    +              return {
    +                  type: Syntax.Property,
    +                  key: id,
    +                  value: parsePropertyMethodFunction({ generator: true }),
    +                  kind: 'init',
    +                  method: true
    +              };
    +          } else {
    +              key = parseObjectPropertyKey();
    +              if (match(':')) {
    +                  lex();
    +                  return {
    +                      type: Syntax.Property,
    +                      key: key,
    +                      value: parseAssignmentExpression(),
    +                      kind: 'init'
    +                  };
    +              } else if (match('(')) {
    +                  return {
    +                      type: Syntax.Property,
    +                      key: key,
    +                      value: parsePropertyMethodFunction({ generator: false }),
    +                      kind: 'init',
    +                      method: true
    +                  };
    +              } else {
    +                  return {
    +                      type: Syntax.Property,
    +                      key: key,
    +                      value: key,
    +                      kind: 'init',
    +                      shorthand: true
    +                  };
    +              }
    +          }
    +      }
    +  
    +      function parseObjectInitialiser() {
    +          var properties = [], property, name, kind, map = {}, toString = String;
    +  
    +          expect('{');
    +  
    +          while (!match('}')) {
    +              property = parseObjectProperty();
    +  
    +              if (property.key.type === Syntax.Identifier) {
    +                  name = property.key.name;
    +              } else {
    +                  name = toString(property.key.value);
    +              }
    +              kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
    +              if (Object.prototype.hasOwnProperty.call(map, name)) {
    +                  if (map[name] === PropertyKind.Data) {
    +                      if (strict && kind === PropertyKind.Data) {
    +                          throwErrorTolerant({}, Messages.StrictDuplicateProperty);
    +                      } else if (kind !== PropertyKind.Data) {
    +                          throwError({}, Messages.AccessorDataProperty);
    +                      }
    +                  } else {
    +                      if (kind === PropertyKind.Data) {
    +                          throwError({}, Messages.AccessorDataProperty);
    +                      } else if (map[name] & kind) {
    +                          throwError({}, Messages.AccessorGetSet);
    +                      }
    +                  }
    +                  map[name] |= kind;
    +              } else {
    +                  map[name] = kind;
    +              }
    +  
    +              properties.push(property);
    +  
    +              if (!match('}')) {
    +                  expect(',');
    +              }
    +          }
    +  
    +          expect('}');
    +  
    +          return {
    +              type: Syntax.ObjectExpression,
    +              properties: properties
    +          };
    +      }
    +  
    +      // 11.1 Primary Expressions
    +  
    +      function parsePrimaryExpression() {
    +          var expr,
    +              token = lookahead(),
    +              type = token.type;
    +  
    +          if (type === Token.Identifier) {
    +              return {
    +                  type: Syntax.Identifier,
    +                  name: lex().value
    +              };
    +          }
    +  
    +          if (type === Token.StringLiteral || type === Token.NumericLiteral) {
    +              if (strict && token.octal) {
    +                  throwErrorTolerant(token, Messages.StrictOctalLiteral);
    +              }
    +              return createLiteral(lex());
    +          }
    +  
    +          if (type === Token.Keyword) {
    +              if (matchKeyword('this')) {
    +                  lex();
    +                  return {
    +                      type: Syntax.ThisExpression
    +                  };
    +              }
    +  
    +              if (matchKeyword('function')) {
    +                  return parseFunctionExpression();
    +              }
    +  
    +              if (matchKeyword('class')) {
    +                  return parseClassExpression();
    +              }
    +  
    +              if (matchKeyword('super')) {
    +                  lex();
    +                  return {
    +                      type: Syntax.Identifier,
    +                      name: 'super'
    +                  };
    +              }
    +          }
    +  
    +          if (type === Token.BooleanLiteral) {
    +              lex();
    +              token.value = (token.value === 'true');
    +              return createLiteral(token);
    +          }
    +  
    +          if (type === Token.NullLiteral) {
    +              lex();
    +              token.value = null;
    +              return createLiteral(token);
    +          }
    +  
    +          if (match('[')) {
    +              return parseArrayInitialiser();
    +          }
    +  
    +          if (match('{')) {
    +              return parseObjectInitialiser();
    +          }
    +  
    +          if (match('(')) {
    +              lex();
    +              state.lastParenthesized = expr = parseExpression();
    +              state.parenthesizedCount += 1;
    +              expect(')');
    +              return expr;
    +          }
    +  
    +          if (match('/') || match('/=')) {
    +              return createLiteral(scanRegExp());
    +          }
    +  
    +          return throwUnexpected(lex());
    +      }
    +  
    +      // 11.2 Left-Hand-Side Expressions
    +  
    +      function parseArguments() {
    +          var args = [];
    +  
    +          expect('(');
    +  
    +          if (!match(')')) {
    +              while (index < length) {
    +                  args.push(parseAssignmentExpression());
    +                  if (match(')')) {
    +                      break;
    +                  }
    +                  expect(',');
    +              }
    +          }
    +  
    +          expect(')');
    +  
    +          return args;
    +      }
    +  
    +      function parseNonComputedProperty() {
    +          var token = lex();
    +  
    +          if (!isIdentifierName(token)) {
    +              throwUnexpected(token);
    +          }
    +  
    +          return {
    +              type: Syntax.Identifier,
    +              name: token.value
    +          };
    +      }
    +  
    +      function parseNonComputedMember(object) {
    +          return {
    +              type: Syntax.MemberExpression,
    +              computed: false,
    +              object: object,
    +              property: parseNonComputedProperty()
    +          };
    +      }
    +  
    +      function parseComputedMember(object) {
    +          var property, expr;
    +  
    +          expect('[');
    +          property = parseExpression();
    +          expr = {
    +              type: Syntax.MemberExpression,
    +              computed: true,
    +              object: object,
    +              property: property
    +          };
    +          expect(']');
    +          return expr;
    +      }
    +  
    +      function parseCallMember(object) {
    +          return {
    +              type: Syntax.CallExpression,
    +              callee: object,
    +              'arguments': parseArguments()
    +          };
    +      }
    +  
    +      function parseNewExpression() {
    +          var expr;
    +  
    +          expectKeyword('new');
    +  
    +          expr = {
    +              type: Syntax.NewExpression,
    +              callee: parseLeftHandSideExpression(),
    +              'arguments': []
    +          };
    +  
    +          if (match('(')) {
    +              expr['arguments'] = parseArguments();
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      function parseLeftHandSideExpressionAllowCall() {
    +          var useNew, expr;
    +  
    +          useNew = matchKeyword('new');
    +          expr = useNew ? parseNewExpression() : parsePrimaryExpression();
    +  
    +          while (index < length) {
    +              if (match('.')) {
    +                  lex();
    +                  expr = parseNonComputedMember(expr);
    +              } else if (match('[')) {
    +                  expr = parseComputedMember(expr);
    +              } else if (match('(')) {
    +                  expr = parseCallMember(expr);
    +              } else {
    +                  break;
    +              }
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      function parseLeftHandSideExpression() {
    +          var useNew, expr;
    +  
    +          useNew = matchKeyword('new');
    +          expr = useNew ? parseNewExpression() : parsePrimaryExpression();
    +  
    +          while (index < length) {
    +              if (match('.')) {
    +                  lex();
    +                  expr = parseNonComputedMember(expr);
    +              } else if (match('[')) {
    +                  expr = parseComputedMember(expr);
    +              } else {
    +                  break;
    +              }
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.3 Postfix Expressions
    +  
    +      function parsePostfixExpression() {
    +          var expr = parseLeftHandSideExpressionAllowCall();
    +  
    +          if ((match('++') || match('--')) && !peekLineTerminator()) {
    +              // 11.3.1, 11.3.2
    +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
    +                  throwError({}, Messages.StrictLHSPostfix);
    +              }
    +  
    +              if (!isLeftHandSide(expr)) {
    +                  throwError({}, Messages.InvalidLHSInAssignment);
    +              }
    +  
    +              expr = {
    +                  type: Syntax.UpdateExpression,
    +                  operator: lex().value,
    +                  argument: expr,
    +                  prefix: false
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.4 Unary Operators
    +  
    +      function parseUnaryExpression() {
    +          var token, expr;
    +  
    +          if (match('++') || match('--')) {
    +              token = lex();
    +              expr = parseUnaryExpression();
    +              // 11.4.4, 11.4.5
    +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
    +                  throwError({}, Messages.StrictLHSPrefix);
    +              }
    +  
    +              if (!isLeftHandSide(expr)) {
    +                  throwError({}, Messages.InvalidLHSInAssignment);
    +              }
    +  
    +              expr = {
    +                  type: Syntax.UpdateExpression,
    +                  operator: token.value,
    +                  argument: expr,
    +                  prefix: true
    +              };
    +              return expr;
    +          }
    +  
    +          if (match('+') || match('-') || match('~') || match('!')) {
    +              expr = {
    +                  type: Syntax.UnaryExpression,
    +                  operator: lex().value,
    +                  argument: parseUnaryExpression()
    +              };
    +              return expr;
    +          }
    +  
    +          if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
    +              expr = {
    +                  type: Syntax.UnaryExpression,
    +                  operator: lex().value,
    +                  argument: parseUnaryExpression()
    +              };
    +              if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
    +                  throwErrorTolerant({}, Messages.StrictDelete);
    +              }
    +              return expr;
    +          }
    +  
    +          return parsePostfixExpression();
    +      }
    +  
    +      // 11.5 Multiplicative Operators
    +  
    +      function parseMultiplicativeExpression() {
    +          var expr = parseUnaryExpression();
    +  
    +          while (match('*') || match('/') || match('%')) {
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseUnaryExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.6 Additive Operators
    +  
    +      function parseAdditiveExpression() {
    +          var expr = parseMultiplicativeExpression();
    +  
    +          while (match('+') || match('-')) {
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseMultiplicativeExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.7 Bitwise Shift Operators
    +  
    +      function parseShiftExpression() {
    +          var expr = parseAdditiveExpression();
    +  
    +          while (match('<<') || match('>>') || match('>>>')) {
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseAdditiveExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +      // 11.8 Relational Operators
    +  
    +      function parseRelationalExpression() {
    +          var expr, previousAllowIn;
    +  
    +          previousAllowIn = state.allowIn;
    +          state.allowIn = true;
    +  
    +          expr = parseShiftExpression();
    +  
    +          while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseShiftExpression()
    +              };
    +          }
    +  
    +          state.allowIn = previousAllowIn;
    +          return expr;
    +      }
    +  
    +      // 11.9 Equality Operators
    +  
    +      function parseEqualityExpression() {
    +          var expr = parseRelationalExpression();
    +  
    +          while ((!peekLineTerminator() && (matchContextualKeyword('is') || matchContextualKeyword('isnt'))) || match('==') || match('!=') || match('===') || match('!==')) {
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseRelationalExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.10 Binary Bitwise Operators
    +  
    +      function parseBitwiseANDExpression() {
    +          var expr = parseEqualityExpression();
    +  
    +          while (match('&')) {
    +              lex();
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: '&',
    +                  left: expr,
    +                  right: parseEqualityExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      function parseBitwiseXORExpression() {
    +          var expr = parseBitwiseANDExpression();
    +  
    +          while (match('^')) {
    +              lex();
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: '^',
    +                  left: expr,
    +                  right: parseBitwiseANDExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      function parseBitwiseORExpression() {
    +          var expr = parseBitwiseXORExpression();
    +  
    +          while (match('|')) {
    +              lex();
    +              expr = {
    +                  type: Syntax.BinaryExpression,
    +                  operator: '|',
    +                  left: expr,
    +                  right: parseBitwiseXORExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.11 Binary Logical Operators
    +  
    +      function parseLogicalANDExpression() {
    +          var expr = parseBitwiseORExpression();
    +  
    +          while (match('&&')) {
    +              lex();
    +              expr = {
    +                  type: Syntax.LogicalExpression,
    +                  operator: '&&',
    +                  left: expr,
    +                  right: parseBitwiseORExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      function parseLogicalORExpression() {
    +          var expr = parseLogicalANDExpression();
    +  
    +          while (match('||')) {
    +              lex();
    +              expr = {
    +                  type: Syntax.LogicalExpression,
    +                  operator: '||',
    +                  left: expr,
    +                  right: parseLogicalANDExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.12 Conditional Operator
    +  
    +      function parseConditionalExpression() {
    +          var expr, previousAllowIn, consequent;
    +  
    +          expr = parseLogicalORExpression();
    +  
    +          if (match('?')) {
    +              lex();
    +              previousAllowIn = state.allowIn;
    +              state.allowIn = true;
    +              consequent = parseAssignmentExpression();
    +              state.allowIn = previousAllowIn;
    +              expect(':');
    +  
    +              expr = {
    +                  type: Syntax.ConditionalExpression,
    +                  test: expr,
    +                  consequent: consequent,
    +                  alternate: parseAssignmentExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.13 Assignment Operators
    +  
    +      function reinterpretAsAssignmentBindingPattern(expr) {
    +          var i, len, property, element;
    +  
    +          if (expr.type === Syntax.ObjectExpression) {
    +              expr.type = Syntax.ObjectPattern;
    +              for (i = 0, len = expr.properties.length; i < len; i += 1) {
    +                  property = expr.properties[i];
    +                  if (property.kind !== 'init') {
    +                      throwError({}, Messages.InvalidLHSInAssignment);
    +                  }
    +                  reinterpretAsAssignmentBindingPattern(property.value);
    +              }
    +          } else if (expr.type === Syntax.ArrayExpression) {
    +              expr.type = Syntax.ArrayPattern;
    +              for (i = 0, len = expr.elements.length; i < len; i += 1) {
    +                  element = expr.elements[i];
    +                  if (element) {
    +                      reinterpretAsAssignmentBindingPattern(element);
    +                  }
    +              }
    +          } else if (expr.type === Syntax.Identifier) {
    +              if (isRestrictedWord(expr.name)) {
    +                  throwError({}, Messages.InvalidLHSInAssignment);
    +              }
    +          } else {
    +              if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
    +                  throwError({}, Messages.InvalidLHSInAssignment);
    +              }
    +          }
    +      }
    +  
    +      function reinterpretAsCoverFormalsList(expr) {
    +          var i, len, param, paramSet;
    +          assert(expr.type === Syntax.SequenceExpression);
    +  
    +          paramSet = {};
    +  
    +          for (i = 0, len = expr.expressions.length; i < len; i += 1) {
    +              param = expr.expressions[i];
    +              if (param.type !== Syntax.Identifier) {
    +                  return null;
    +              }
    +              if (isRestrictedWord(param.name)) {
    +                  throwError({}, Messages.StrictParamName);
    +              }
    +              if (Object.prototype.hasOwnProperty.call(paramSet, param.name)) {
    +                  throwError({}, Messages.StrictParamDupe);
    +              }
    +              paramSet[param.name] = true;
    +          }
    +          return expr.expressions;
    +      }
    +  
    +      function parseArrowFunctionExpression(param) {
    +          var previousStrict, previousYieldAllowed, body;
    +  
    +          expect('=>');
    +  
    +          previousStrict = strict;
    +          previousYieldAllowed = yieldAllowed;
    +          strict = true;
    +          yieldAllowed = false;
    +          body = parseConciseBody();
    +          strict = previousStrict;
    +          yieldAllowed = previousYieldAllowed;
    +  
    +          return {
    +              type: Syntax.ArrowFunctionExpression,
    +              id: null,
    +              params: param,
    +              body: body
    +          };
    +      }
    +  
    +      function parseAssignmentExpression() {
    +          var expr, token, oldParenthesizedCount, coverFormalsList;
    +  
    +          if (matchKeyword('yield')) {
    +              return parseYieldExpression();
    +          }
    +  
    +          oldParenthesizedCount = state.parenthesizedCount;
    +  
    +          if (match('(')) {
    +              token = lookahead2();
    +              if (token.type === Token.Punctuator && token.value === ')') {
    +                  lex();
    +                  lex();
    +                  if (!match('=>')) {
    +                      throwUnexpected(lex());
    +                  }
    +                  return parseArrowFunctionExpression([]);
    +              }
    +          }
    +  
    +          expr = parseConditionalExpression();
    +  
    +          if (match('=>')) {
    +              if (expr.type === Syntax.Identifier) {
    +                  if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
    +                      if (isRestrictedWord(expr.name)) {
    +                          throwError({}, Messages.StrictParamName);
    +                      }
    +                      return parseArrowFunctionExpression([ expr ]);
    +                  }
    +              } else if (expr.type === Syntax.SequenceExpression) {
    +                  if (state.parenthesizedCount === (oldParenthesizedCount + 1)) {
    +                      coverFormalsList = reinterpretAsCoverFormalsList(expr);
    +                      if (coverFormalsList) {
    +                          return parseArrowFunctionExpression(coverFormalsList);
    +                      }
    +                  }
    +              }
    +          }
    +  
    +          if (matchAssign()) {
    +              // 11.13.1
    +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
    +                  throwError({}, Messages.StrictLHSAssignment);
    +              }
    +  
    +              // ES.next draf 11.13 Runtime Semantics step 1
    +              if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
    +                  reinterpretAsAssignmentBindingPattern(expr);
    +              } else if (!isLeftHandSide(expr)) {
    +                  throwError({}, Messages.InvalidLHSInAssignment);
    +              }
    +  
    +              expr = {
    +                  type: Syntax.AssignmentExpression,
    +                  operator: lex().value,
    +                  left: expr,
    +                  right: parseAssignmentExpression()
    +              };
    +          }
    +  
    +          return expr;
    +      }
    +  
    +      // 11.14 Comma Operator
    +  
    +      function parseExpression() {
    +          var expr = parseAssignmentExpression();
    +  
    +          if (match(',')) {
    +              expr = {
    +                  type: Syntax.SequenceExpression,
    +                  expressions: [ expr ]
    +              };
    +  
    +              while (index < length) {
    +                  if (!match(',')) {
    +                      break;
    +                  }
    +                  lex();
    +                  expr.expressions.push(parseAssignmentExpression());
    +              }
    +  
    +          }
    +          return expr;
    +      }
    +  
    +      // 12.1 Block
    +  
    +      function parseStatementList() {
    +          var list = [],
    +              statement;
    +  
    +          while (index < length) {
    +              if (match('}')) {
    +                  break;
    +              }
    +              statement = parseSourceElement();
    +              if (typeof statement === 'undefined') {
    +                  break;
    +              }
    +              list.push(statement);
    +          }
    +  
    +          return list;
    +      }
    +  
    +      function parseBlock() {
    +          var block;
    +  
    +          expect('{');
    +  
    +          block = parseStatementList();
    +  
    +          expect('}');
    +  
    +          return {
    +              type: Syntax.BlockStatement,
    +              body: block
    +          };
    +      }
    +  
    +      // 12.2 Variable Statement
    +  
    +      function parseVariableIdentifier() {
    +          var token = lex();
    +  
    +          if (token.type !== Token.Identifier) {
    +              throwUnexpected(token);
    +          }
    +  
    +          return {
    +              type: Syntax.Identifier,
    +              name: token.value
    +          };
    +      }
    +  
    +      function parseVariableDeclaration(kind) {
    +          var id = parseVariableIdentifier(),
    +              init = null;
    +  
    +          // 12.2.1
    +          if (strict && isRestrictedWord(id.name)) {
    +              throwErrorTolerant({}, Messages.StrictVarName);
    +          }
    +  
    +          if (kind === 'const') {
    +              expect('=');
    +              init = parseAssignmentExpression();
    +          } else if (match('=')) {
    +              lex();
    +              init = parseAssignmentExpression();
    +          }
    +  
    +          return {
    +              type: Syntax.VariableDeclarator,
    +              id: id,
    +              init: init
    +          };
    +      }
    +  
    +      function parseVariableDeclarationList(kind) {
    +          var list = [];
    +  
    +          while (index < length) {
    +              list.push(parseVariableDeclaration(kind));
    +              if (!match(',')) {
    +                  break;
    +              }
    +              lex();
    +          }
    +  
    +          return list;
    +      }
    +  
    +      function parseVariableStatement() {
    +          var declarations;
    +  
    +          expectKeyword('var');
    +  
    +          declarations = parseVariableDeclarationList();
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.VariableDeclaration,
    +              declarations: declarations,
    +              kind: 'var'
    +          };
    +      }
    +  
    +      // kind may be `const` or `let`
    +      // Both are experimental and not in the specification yet.
    +      // see http://wiki.ecmascript.org/doku.php?id=harmony:const
    +      // and http://wiki.ecmascript.org/doku.php?id=harmony:let
    +      function parseConstLetDeclaration(kind) {
    +          var declarations;
    +  
    +          expectKeyword(kind);
    +  
    +          declarations = parseVariableDeclarationList(kind);
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.VariableDeclaration,
    +              declarations: declarations,
    +              kind: kind
    +          };
    +      }
    +  
    +      // http://wiki.ecmascript.org/doku.php?id=harmony:modules
    +  
    +      function parsePath() {
    +          var result, id;
    +  
    +          result = {
    +              type: Syntax.Path,
    +              body: []
    +          };
    +  
    +          while (true) {
    +              id = parseVariableIdentifier();
    +              result.body.push(id);
    +              if (!match('.')) {
    +                  break;
    +              }
    +              lex();
    +          }
    +  
    +          return result;
    +      }
    +  
    +      function parseGlob() {
    +          expect('*');
    +          return {
    +              type: Syntax.Glob
    +          };
    +      }
    +  
    +      function parseModuleDeclaration() {
    +          var id, token, declaration;
    +  
    +          token = lex();
    +          if (token.value !== 'module') {
    +              throwUnexpected(token);
    +          }
    +  
    +          id = parseVariableIdentifier();
    +  
    +          if (match('{')) {
    +              return {
    +                  type: Syntax.ModuleDeclaration,
    +                  id: id,
    +                  body: parseModuleBlock()
    +              };
    +          }
    +  
    +          expect('=');
    +  
    +          token = lookahead();
    +          if (token.type === Token.StringLiteral) {
    +              declaration = {
    +                  type: Syntax.ModuleDeclaration,
    +                  id: id,
    +                  from: parsePrimaryExpression()
    +              };
    +          } else {
    +              declaration = {
    +                  type: Syntax.ModuleDeclaration,
    +                  id: id,
    +                  from: parsePath()
    +              };
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          return declaration;
    +      }
    +  
    +      function parseExportSpecifierSetProperty() {
    +          var specifier;
    +  
    +          specifier = {
    +              type: Syntax.ExportSpecifier,
    +              id: parseVariableIdentifier(),
    +              from: null
    +          };
    +  
    +          if (match(':')) {
    +              lex();
    +              specifier.from = parsePath();
    +          }
    +  
    +          return specifier;
    +      }
    +  
    +      function parseExportSpecifier() {
    +          var specifier, specifiers;
    +  
    +          if (match('{')) {
    +              lex();
    +              specifiers = [];
    +  
    +              do {
    +                  specifiers.push(parseExportSpecifierSetProperty());
    +              } while (match(',') && lex());
    +  
    +              expect('}');
    +  
    +              return {
    +                  type: Syntax.ExportSpecifierSet,
    +                  specifiers: specifiers
    +              };
    +          }
    +  
    +          if (match('*')) {
    +              specifier = {
    +                  type: Syntax.ExportSpecifier,
    +                  id: parseGlob(),
    +                  from: null
    +              };
    +  
    +              if (matchContextualKeyword('from')) {
    +                  lex();
    +                  specifier.from = parsePath();
    +              }
    +          } else {
    +              specifier = {
    +                  type: Syntax.ExportSpecifier,
    +                  id: parseVariableIdentifier(),
    +                  from: null
    +              };
    +          }
    +          return specifier;
    +      }
    +  
    +      function parseExportDeclaration() {
    +          var token, specifiers;
    +  
    +          expectKeyword('export');
    +  
    +          token = lookahead();
    +  
    +          if (token.type === Token.Keyword || (token.type === Token.Identifier && token.value === 'module')) {
    +              switch (token.value) {
    +              case 'function':
    +                  return {
    +                      type: Syntax.ExportDeclaration,
    +                      declaration: parseFunctionDeclaration()
    +                  };
    +              case 'module':
    +                  return {
    +                      type: Syntax.ExportDeclaration,
    +                      declaration: parseModuleDeclaration()
    +                  };
    +              case 'let':
    +              case 'const':
    +                  return {
    +                      type: Syntax.ExportDeclaration,
    +                      declaration: parseConstLetDeclaration(token.value)
    +                  };
    +              case 'var':
    +                  return {
    +                      type: Syntax.ExportDeclaration,
    +                      declaration: parseStatement()
    +                  };
    +              }
    +              throwUnexpected(lex());
    +          }
    +  
    +          specifiers = [ parseExportSpecifier() ];
    +          if (match(',')) {
    +              while (index < length) {
    +                  if (!match(',')) {
    +                      break;
    +                  }
    +                  lex();
    +                  specifiers.push(parseExportSpecifier());
    +              }
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ExportDeclaration,
    +              specifiers: specifiers
    +          };
    +      }
    +  
    +      function parseImportDeclaration() {
    +          var specifiers, from;
    +  
    +          expectKeyword('import');
    +  
    +          if (match('*')) {
    +              specifiers = [parseGlob()];
    +          } else if (match('{')) {
    +              lex();
    +              specifiers = [];
    +  
    +              do {
    +                  specifiers.push(parseImportSpecifier());
    +              } while (match(',') && lex());
    +  
    +              expect('}');
    +          } else {
    +              specifiers = [parseVariableIdentifier()];
    +          }
    +  
    +          if (!matchContextualKeyword('from')) {
    +              throwError({}, Messages.NoFromAfterImport);
    +          }
    +  
    +          lex();
    +  
    +          if (lookahead().type === Token.StringLiteral) {
    +              from = parsePrimaryExpression();
    +          } else {
    +              from = parsePath();
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ImportDeclaration,
    +              specifiers: specifiers,
    +              from: from
    +          };
    +      }
    +  
    +      function parseImportSpecifier() {
    +          var specifier;
    +  
    +          specifier = {
    +              type: Syntax.ImportSpecifier,
    +              id: parseVariableIdentifier(),
    +              from: null
    +          };
    +  
    +          if (match(':')) {
    +              lex();
    +              specifier.from = parsePath();
    +          }
    +  
    +          return specifier;
    +      }
    +  
    +      // 12.3 Empty Statement
    +  
    +      function parseEmptyStatement() {
    +          expect(';');
    +  
    +          return {
    +              type: Syntax.EmptyStatement
    +          };
    +      }
    +  
    +      // 12.4 Expression Statement
    +  
    +      function parseExpressionStatement() {
    +          var expr = parseExpression();
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ExpressionStatement,
    +              expression: expr
    +          };
    +      }
    +  
    +      // 12.5 If statement
    +  
    +      function parseIfStatement() {
    +          var test, consequent, alternate;
    +  
    +          expectKeyword('if');
    +  
    +          expect('(');
    +  
    +          test = parseExpression();
    +  
    +          expect(')');
    +  
    +          consequent = parseStatement();
    +  
    +          if (matchKeyword('else')) {
    +              lex();
    +              alternate = parseStatement();
    +          } else {
    +              alternate = null;
    +          }
    +  
    +          return {
    +              type: Syntax.IfStatement,
    +              test: test,
    +              consequent: consequent,
    +              alternate: alternate
    +          };
    +      }
    +  
    +      // 12.6 Iteration Statements
    +  
    +      function parseDoWhileStatement() {
    +          var body, test, oldInIteration;
    +  
    +          expectKeyword('do');
    +  
    +          oldInIteration = state.inIteration;
    +          state.inIteration = true;
    +  
    +          body = parseStatement();
    +  
    +          state.inIteration = oldInIteration;
    +  
    +          expectKeyword('while');
    +  
    +          expect('(');
    +  
    +          test = parseExpression();
    +  
    +          expect(')');
    +  
    +          if (match(';')) {
    +              lex();
    +          }
    +  
    +          return {
    +              type: Syntax.DoWhileStatement,
    +              body: body,
    +              test: test
    +          };
    +      }
    +  
    +      function parseWhileStatement() {
    +          var test, body, oldInIteration;
    +  
    +          expectKeyword('while');
    +  
    +          expect('(');
    +  
    +          test = parseExpression();
    +  
    +          expect(')');
    +  
    +          oldInIteration = state.inIteration;
    +          state.inIteration = true;
    +  
    +          body = parseStatement();
    +  
    +          state.inIteration = oldInIteration;
    +  
    +          return {
    +              type: Syntax.WhileStatement,
    +              test: test,
    +              body: body
    +          };
    +      }
    +  
    +      function parseForVariableDeclaration() {
    +          var token = lex();
    +  
    +          return {
    +              type: Syntax.VariableDeclaration,
    +              declarations: parseVariableDeclarationList(),
    +              kind: token.value
    +          };
    +      }
    +  
    +      function parseForStatement() {
    +          var init, test, update, left, right, body, operator, oldInIteration;
    +  
    +          init = test = update = null;
    +  
    +          expectKeyword('for');
    +  
    +          expect('(');
    +  
    +          if (match(';')) {
    +              lex();
    +          } else {
    +              if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
    +                  state.allowIn = false;
    +                  init = parseForVariableDeclaration();
    +                  state.allowIn = true;
    +  
    +                  if (init.declarations.length === 1) {
    +                      if (matchKeyword('in') || matchContextualKeyword('of')) {
    +                          operator = lookahead();
    +                          if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
    +                              lex();
    +                              left = init;
    +                              right = parseExpression();
    +                              init = null;
    +                          }
    +                      }
    +                  }
    +              } else {
    +                  state.allowIn = false;
    +                  init = parseExpression();
    +                  state.allowIn = true;
    +  
    +                  if (matchContextualKeyword('of')) {
    +                      operator = lex();
    +                      left = init;
    +                      right = parseExpression();
    +                      init = null;
    +                  } else if (matchKeyword('in')) {
    +                      // LeftHandSideExpression
    +                      if (!isAssignableLeftHandSide(init)) {
    +                          throwError({}, Messages.InvalidLHSInForIn);
    +                      }
    +                      operator = lex();
    +                      left = init;
    +                      right = parseExpression();
    +                      init = null;
    +                  }
    +              }
    +  
    +              if (typeof left === 'undefined') {
    +                  expect(';');
    +              }
    +          }
    +  
    +          if (typeof left === 'undefined') {
    +  
    +              if (!match(';')) {
    +                  test = parseExpression();
    +              }
    +              expect(';');
    +  
    +              if (!match(')')) {
    +                  update = parseExpression();
    +              }
    +          }
    +  
    +          expect(')');
    +  
    +          oldInIteration = state.inIteration;
    +          state.inIteration = true;
    +  
    +          body = parseStatement();
    +  
    +          state.inIteration = oldInIteration;
    +  
    +          if (typeof left === 'undefined') {
    +              return {
    +                  type: Syntax.ForStatement,
    +                  init: init,
    +                  test: test,
    +                  update: update,
    +                  body: body
    +              };
    +          }
    +  
    +          if (operator.value === 'in') {
    +              return {
    +                  type: Syntax.ForInStatement,
    +                  left: left,
    +                  right: right,
    +                  body: body,
    +                  each: false
    +              };
    +          } else {
    +              return {
    +                  type: Syntax.ForOfStatement,
    +                  left: left,
    +                  right: right,
    +                  body: body
    +              };
    +          }
    +      }
    +  
    +      // 12.7 The continue statement
    +  
    +      function parseContinueStatement() {
    +          var token, label = null;
    +  
    +          expectKeyword('continue');
    +  
    +          // Optimize the most common form: 'continue;'.
    +          if (source[index] === ';') {
    +              lex();
    +  
    +              if (!state.inIteration) {
    +                  throwError({}, Messages.IllegalContinue);
    +              }
    +  
    +              return {
    +                  type: Syntax.ContinueStatement,
    +                  label: null
    +              };
    +          }
    +  
    +          if (peekLineTerminator()) {
    +              if (!state.inIteration) {
    +                  throwError({}, Messages.IllegalContinue);
    +              }
    +  
    +              return {
    +                  type: Syntax.ContinueStatement,
    +                  label: null
    +              };
    +          }
    +  
    +          token = lookahead();
    +          if (token.type === Token.Identifier) {
    +              label = parseVariableIdentifier();
    +  
    +              if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
    +                  throwError({}, Messages.UnknownLabel, label.name);
    +              }
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          if (label === null && !state.inIteration) {
    +              throwError({}, Messages.IllegalContinue);
    +          }
    +  
    +          return {
    +              type: Syntax.ContinueStatement,
    +              label: label
    +          };
    +      }
    +  
    +      // 12.8 The break statement
    +  
    +      function parseBreakStatement() {
    +          var token, label = null;
    +  
    +          expectKeyword('break');
    +  
    +          // Optimize the most common form: 'break;'.
    +          if (source[index] === ';') {
    +              lex();
    +  
    +              if (!(state.inIteration || state.inSwitch)) {
    +                  throwError({}, Messages.IllegalBreak);
    +              }
    +  
    +              return {
    +                  type: Syntax.BreakStatement,
    +                  label: null
    +              };
    +          }
    +  
    +          if (peekLineTerminator()) {
    +              if (!(state.inIteration || state.inSwitch)) {
    +                  throwError({}, Messages.IllegalBreak);
    +              }
    +  
    +              return {
    +                  type: Syntax.BreakStatement,
    +                  label: null
    +              };
    +          }
    +  
    +          token = lookahead();
    +          if (token.type === Token.Identifier) {
    +              label = parseVariableIdentifier();
    +  
    +              if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
    +                  throwError({}, Messages.UnknownLabel, label.name);
    +              }
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          if (label === null && !(state.inIteration || state.inSwitch)) {
    +              throwError({}, Messages.IllegalBreak);
    +          }
    +  
    +          return {
    +              type: Syntax.BreakStatement,
    +              label: label
    +          };
    +      }
    +  
    +      // 12.9 The return statement
    +  
    +      function parseReturnStatement() {
    +          var token, argument = null;
    +  
    +          expectKeyword('return');
    +  
    +          if (!state.inFunctionBody) {
    +              throwErrorTolerant({}, Messages.IllegalReturn);
    +          }
    +  
    +          // 'return' followed by a space and an identifier is very common.
    +          if (source[index] === ' ') {
    +              if (isIdentifierStart(source[index + 1])) {
    +                  argument = parseExpression();
    +                  consumeSemicolon();
    +                  return {
    +                      type: Syntax.ReturnStatement,
    +                      argument: argument
    +                  };
    +              }
    +          }
    +  
    +          if (peekLineTerminator()) {
    +              return {
    +                  type: Syntax.ReturnStatement,
    +                  argument: null
    +              };
    +          }
    +  
    +          if (!match(';')) {
    +              token = lookahead();
    +              if (!match('}') && token.type !== Token.EOF) {
    +                  argument = parseExpression();
    +              }
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ReturnStatement,
    +              argument: argument
    +          };
    +      }
    +  
    +      // 12.10 The with statement
    +  
    +      function parseWithStatement() {
    +          var object, body;
    +  
    +          if (strict) {
    +              throwErrorTolerant({}, Messages.StrictModeWith);
    +          }
    +  
    +          expectKeyword('with');
    +  
    +          expect('(');
    +  
    +          object = parseExpression();
    +  
    +          expect(')');
    +  
    +          body = parseStatement();
    +  
    +          return {
    +              type: Syntax.WithStatement,
    +              object: object,
    +              body: body
    +          };
    +      }
    +  
    +      // 12.10 The swith statement
    +  
    +      function parseSwitchCase() {
    +          var test,
    +              consequent = [],
    +              statement;
    +  
    +          if (matchKeyword('default')) {
    +              lex();
    +              test = null;
    +          } else {
    +              expectKeyword('case');
    +              test = parseExpression();
    +          }
    +          expect(':');
    +  
    +          while (index < length) {
    +              if (match('}') || matchKeyword('default') || matchKeyword('case')) {
    +                  break;
    +              }
    +              statement = parseSourceElement();
    +              if (typeof statement === 'undefined') {
    +                  break;
    +              }
    +              consequent.push(statement);
    +          }
    +  
    +          return {
    +              type: Syntax.SwitchCase,
    +              test: test,
    +              consequent: consequent
    +          };
    +      }
    +  
    +      function parseSwitchStatement() {
    +          var discriminant, cases, clause, oldInSwitch, defaultFound;
    +  
    +          expectKeyword('switch');
    +  
    +          expect('(');
    +  
    +          discriminant = parseExpression();
    +  
    +          expect(')');
    +  
    +          expect('{');
    +  
    +          if (match('}')) {
    +              lex();
    +              return {
    +                  type: Syntax.SwitchStatement,
    +                  discriminant: discriminant
    +              };
    +          }
    +  
    +          cases = [];
    +  
    +          oldInSwitch = state.inSwitch;
    +          state.inSwitch = true;
    +          defaultFound = false;
    +  
    +          while (index < length) {
    +              if (match('}')) {
    +                  break;
    +              }
    +              clause = parseSwitchCase();
    +              if (clause.test === null) {
    +                  if (defaultFound) {
    +                      throwError({}, Messages.MultipleDefaultsInSwitch);
    +                  }
    +                  defaultFound = true;
    +              }
    +              cases.push(clause);
    +          }
    +  
    +          state.inSwitch = oldInSwitch;
    +  
    +          expect('}');
    +  
    +          return {
    +              type: Syntax.SwitchStatement,
    +              discriminant: discriminant,
    +              cases: cases
    +          };
    +      }
    +  
    +      // 12.13 The throw statement
    +  
    +      function parseThrowStatement() {
    +          var argument;
    +  
    +          expectKeyword('throw');
    +  
    +          if (peekLineTerminator()) {
    +              throwError({}, Messages.NewlineAfterThrow);
    +          }
    +  
    +          argument = parseExpression();
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ThrowStatement,
    +              argument: argument
    +          };
    +      }
    +  
    +      // 12.14 The try statement
    +  
    +      function parseCatchClause() {
    +          var param;
    +  
    +          expectKeyword('catch');
    +  
    +          expect('(');
    +          if (!match(')')) {
    +              param = parseExpression();
    +              // 12.14.1
    +              if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
    +                  throwErrorTolerant({}, Messages.StrictCatchVariable);
    +              }
    +          }
    +          expect(')');
    +  
    +          return {
    +              type: Syntax.CatchClause,
    +              param: param,
    +              guard: null,
    +              body: parseBlock()
    +          };
    +      }
    +  
    +      function parseTryStatement() {
    +          var block, handlers = [], finalizer = null;
    +  
    +          expectKeyword('try');
    +  
    +          block = parseBlock();
    +  
    +          if (matchKeyword('catch')) {
    +              handlers.push(parseCatchClause());
    +          }
    +  
    +          if (matchKeyword('finally')) {
    +              lex();
    +              finalizer = parseBlock();
    +          }
    +  
    +          if (handlers.length === 0 && !finalizer) {
    +              throwError({}, Messages.NoCatchOrFinally);
    +          }
    +  
    +          return {
    +              type: Syntax.TryStatement,
    +              block: block,
    +              handlers: handlers,
    +              finalizer: finalizer
    +          };
    +      }
    +  
    +      // 12.15 The debugger statement
    +  
    +      function parseDebuggerStatement() {
    +          expectKeyword('debugger');
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.DebuggerStatement
    +          };
    +      }
    +  
    +      // 12 Statements
    +  
    +      function parseStatement() {
    +          var token = lookahead(),
    +              expr,
    +              labeledBody;
    +  
    +          if (token.type === Token.EOF) {
    +              throwUnexpected(token);
    +          }
    +  
    +          if (token.type === Token.Punctuator) {
    +              switch (token.value) {
    +              case ';':
    +                  return parseEmptyStatement();
    +              case '{':
    +                  return parseBlock();
    +              case '(':
    +                  return parseExpressionStatement();
    +              default:
    +                  break;
    +              }
    +          }
    +  
    +          if (token.type === Token.Keyword) {
    +              switch (token.value) {
    +              case 'break':
    +                  return parseBreakStatement();
    +              case 'continue':
    +                  return parseContinueStatement();
    +              case 'debugger':
    +                  return parseDebuggerStatement();
    +              case 'do':
    +                  return parseDoWhileStatement();
    +              case 'for':
    +                  return parseForStatement();
    +              case 'function':
    +                  return parseFunctionDeclaration();
    +              case 'class':
    +                  return parseClassDeclaration();
    +              case 'if':
    +                  return parseIfStatement();
    +              case 'return':
    +                  return parseReturnStatement();
    +              case 'switch':
    +                  return parseSwitchStatement();
    +              case 'throw':
    +                  return parseThrowStatement();
    +              case 'try':
    +                  return parseTryStatement();
    +              case 'var':
    +                  return parseVariableStatement();
    +              case 'while':
    +                  return parseWhileStatement();
    +              case 'with':
    +                  return parseWithStatement();
    +              default:
    +                  break;
    +              }
    +          }
    +  
    +          expr = parseExpression();
    +  
    +          // 12.12 Labelled Statements
    +          if ((expr.type === Syntax.Identifier) && match(':')) {
    +              lex();
    +  
    +              if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
    +                  throwError({}, Messages.Redeclaration, 'Label', expr.name);
    +              }
    +  
    +              state.labelSet[expr.name] = true;
    +              labeledBody = parseStatement();
    +              delete state.labelSet[expr.name];
    +  
    +              return {
    +                  type: Syntax.LabeledStatement,
    +                  label: expr,
    +                  body: labeledBody
    +              };
    +          }
    +  
    +          consumeSemicolon();
    +  
    +          return {
    +              type: Syntax.ExpressionStatement,
    +              expression: expr
    +          };
    +      }
    +  
    +      // 13 Function Definition
    +  
    +      function parseConciseBody() {
    +          if (match('{')) {
    +              return parseFunctionSourceElements();
    +          } else {
    +              return parseAssignmentExpression();
    +          }
    +      }
    +  
    +      function parseFunctionSourceElements() {
    +          var sourceElement, sourceElements = [], token, directive, firstRestricted,
    +              oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount;
    +  
    +          expect('{');
    +  
    +          while (index < length) {
    +              token = lookahead();
    +              if (token.type !== Token.StringLiteral) {
    +                  break;
    +              }
    +  
    +              sourceElement = parseSourceElement();
    +              sourceElements.push(sourceElement);
    +              if (sourceElement.expression.type !== Syntax.Literal) {
    +                  // this is not directive
    +                  break;
    +              }
    +              directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
    +              if (directive === 'use strict') {
    +                  strict = true;
    +                  if (firstRestricted) {
    +                      throwError(firstRestricted, Messages.StrictOctalLiteral);
    +                  }
    +              } else {
    +                  if (!firstRestricted && token.octal) {
    +                      firstRestricted = token;
    +                  }
    +              }
    +          }
    +  
    +          oldLabelSet = state.labelSet;
    +          oldInIteration = state.inIteration;
    +          oldInSwitch = state.inSwitch;
    +          oldInFunctionBody = state.inFunctionBody;
    +          oldParenthesizedCount = state.parenthesizedCount;
    +  
    +          state.labelSet = {};
    +          state.inIteration = false;
    +          state.inSwitch = false;
    +          state.inFunctionBody = true;
    +          state.parenthesizedCount = 0;
    +  
    +          while (index < length) {
    +              if (match('}')) {
    +                  break;
    +              }
    +              sourceElement = parseSourceElement();
    +              if (typeof sourceElement === 'undefined') {
    +                  break;
    +              }
    +              sourceElements.push(sourceElement);
    +          }
    +  
    +          expect('}');
    +  
    +          state.labelSet = oldLabelSet;
    +          state.inIteration = oldInIteration;
    +          state.inSwitch = oldInSwitch;
    +          state.inFunctionBody = oldInFunctionBody;
    +          state.parenthesizedCount = oldParenthesizedCount;
    +  
    +          return {
    +              type: Syntax.BlockStatement,
    +              body: sourceElements
    +          };
    +      }
    +  
    +      function parseFunctionDeclaration() {
    +          var id, param, params = [], body, token, firstRestricted, message, previousStrict, previousYieldAllowed, paramSet, generator;
    +  
    +          expectKeyword('function');
    +  
    +          generator = false;
    +          if (match('*')) {
    +              lex();
    +              generator = true;
    +          }
    +  
    +          token = lookahead();
    +  
    +          id = parseVariableIdentifier();
    +          if (strict) {
    +              if (isRestrictedWord(token.value)) {
    +                  throwError(token, Messages.StrictFunctionName);
    +              }
    +          } else {
    +              if (isRestrictedWord(token.value)) {
    +                  firstRestricted = token;
    +                  message = Messages.StrictFunctionName;
    +              } else if (isStrictModeReservedWord(token.value)) {
    +                  firstRestricted = token;
    +                  message = Messages.StrictReservedWord;
    +              }
    +          }
    +  
    +          expect('(');
    +  
    +          if (!match(')')) {
    +              paramSet = {};
    +              while (index < length) {
    +                  token = lookahead();
    +                  param = parseVariableIdentifier();
    +                  if (strict) {
    +                      if (isRestrictedWord(token.value)) {
    +                          throwError(token, Messages.StrictParamName);
    +                      }
    +                      if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
    +                          throwError(token, Messages.StrictParamDupe);
    +                      }
    +                  } else if (!firstRestricted) {
    +                      if (isRestrictedWord(token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictParamName;
    +                      } else if (isStrictModeReservedWord(token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictReservedWord;
    +                      } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictParamDupe;
    +                      }
    +                  }
    +                  params.push(param);
    +                  paramSet[param.name] = true;
    +                  if (match(')')) {
    +                      break;
    +                  }
    +                  expect(',');
    +              }
    +          }
    +  
    +          expect(')');
    +  
    +          previousStrict = strict;
    +          previousYieldAllowed = yieldAllowed;
    +          yieldAllowed = generator;
    +          body = parseFunctionSourceElements();
    +          if (strict && firstRestricted) {
    +              throwError(firstRestricted, message);
    +          }
    +          if (yieldAllowed && !yieldFound) {
    +              throwError({}, Messages.NoYieldInGenerator);
    +          }
    +          strict = previousStrict;
    +          yieldAllowed = previousYieldAllowed;
    +  
    +          return {
    +              type: Syntax.FunctionDeclaration,
    +              id: id,
    +              params: params,
    +              body: body,
    +              generator: generator
    +          };
    +      }
    +  
    +      function parseFunctionExpression() {
    +          var token, id = null, firstRestricted, message, param, params = [], body, previousStrict, previousYieldAllowed, paramSet, generator;
    +  
    +          expectKeyword('function');
    +  
    +          generator = false;
    +  
    +          if (match('*')) {
    +              lex();
    +              generator = true;
    +          }
    +  
    +          if (!match('(')) {
    +              token = lookahead();
    +              id = parseVariableIdentifier();
    +              if (strict) {
    +                  if (isRestrictedWord(token.value)) {
    +                      throwError(token, Messages.StrictFunctionName);
    +                  }
    +              } else {
    +                  if (isRestrictedWord(token.value)) {
    +                      firstRestricted = token;
    +                      message = Messages.StrictFunctionName;
    +                  } else if (isStrictModeReservedWord(token.value)) {
    +                      firstRestricted = token;
    +                      message = Messages.StrictReservedWord;
    +                  }
    +              }
    +          }
    +  
    +          expect('(');
    +  
    +          if (!match(')')) {
    +              paramSet = {};
    +              while (index < length) {
    +                  token = lookahead();
    +                  param = parseVariableIdentifier();
    +                  if (strict) {
    +                      if (isRestrictedWord(token.value)) {
    +                          throwError(token, Messages.StrictParamName);
    +                      }
    +                      if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
    +                          throwError(token, Messages.StrictParamDupe);
    +                      }
    +                  } else if (!firstRestricted) {
    +                      if (isRestrictedWord(token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictParamName;
    +                      } else if (isStrictModeReservedWord(token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictReservedWord;
    +                      } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
    +                          firstRestricted = token;
    +                          message = Messages.StrictParamDupe;
    +                      }
    +                  }
    +                  params.push(param);
    +                  paramSet[param.name] = true;
    +                  if (match(')')) {
    +                      break;
    +                  }
    +                  expect(',');
    +              }
    +          }
    +  
    +          expect(')');
    +  
    +          previousStrict = strict;
    +          previousYieldAllowed = yieldAllowed;
    +          yieldAllowed = generator;
    +          body = parseFunctionSourceElements();
    +          if (strict && firstRestricted) {
    +              throwError(firstRestricted, message);
    +          }
    +          if (yieldAllowed && !yieldFound) {
    +              throwError({}, Messages.NoYieldInGenerator);
    +          }
    +          strict = previousStrict;
    +          yieldAllowed = previousYieldAllowed;
    +  
    +  
    +          return {
    +              type: Syntax.FunctionExpression,
    +              id: id,
    +              params: params,
    +              body: body,
    +              generator: generator
    +          };
    +      }
    +  
    +      function parseYieldExpression() {
    +          var delegate, expr, previousYieldAllowed;
    +  
    +          expectKeyword('yield');
    +  
    +          if (!yieldAllowed) {
    +              throwErrorTolerant({}, Messages.IllegalYield);
    +          }
    +  
    +          delegate = false;
    +          if (match('*')) {
    +              lex();
    +              delegate = true;
    +          }
    +  
    +          // It is a Syntax Error if any AssignmentExpression Contains YieldExpression.
    +          previousYieldAllowed = yieldAllowed;
    +          yieldAllowed = false;
    +          expr = parseAssignmentExpression();
    +          yieldAllowed = previousYieldAllowed;
    +          yieldFound = true;
    +  
    +          return {
    +              type: Syntax.YieldExpression,
    +              argument: expr,
    +              delegate: delegate
    +          };
    +      }
    +  
    +      // 14 Classes
    +  
    +      function parseMethodDefinition() {
    +          var token, key, param;
    +  
    +          if (match('*')) {
    +              lex();
    +              return {
    +                  type: Syntax.MethodDefinition,
    +                  key: parseObjectPropertyKey(),
    +                  value: parsePropertyMethodFunction({ generator: true }),
    +                  kind: ''
    +              };
    +          }
    +  
    +          token = lookahead();
    +          key = parseObjectPropertyKey();
    +  
    +          if (token.value === 'get' && !match('(')) {
    +              key = parseObjectPropertyKey();
    +              expect('(');
    +              expect(')');
    +              return {
    +                  type: Syntax.MethodDefinition,
    +                  key: key,
    +                  value: parsePropertyFunction([], { generator: false }),
    +                  kind: 'get'
    +              };
    +          } else if (token.value === 'set' && !match('(')) {
    +              key = parseObjectPropertyKey();
    +              expect('(');
    +              token = lookahead();
    +              param = [ parseVariableIdentifier() ];
    +              expect(')');
    +              return {
    +                  type: Syntax.MethodDefinition,
    +                  key: key,
    +                  value: parsePropertyFunction(param, { generator: false, name: token }),
    +                  kind: 'set'
    +              };
    +          } else {
    +              return {
    +                  type: Syntax.MethodDefinition,
    +                  key: key,
    +                  value: parsePropertyMethodFunction({ generator: false }),
    +                  kind: ''
    +              };
    +          }
    +      }
    +  
    +      function parseClassElement() {
    +          if (match(';')) {
    +              lex();
    +              return;
    +          } else {
    +              return parseMethodDefinition();
    +          }
    +      }
    +  
    +      function parseClassBody() {
    +          var classElement, classElements = [];
    +  
    +          expect('{');
    +  
    +          while (index < length) {
    +              if (match('}')) {
    +                  break;
    +              }
    +              classElement = parseClassElement();
    +              if (typeof classElement !== 'undefined') {
    +                  classElements.push(classElement);
    +              }
    +          }
    +  
    +          expect('}');
    +  
    +          return {
    +              type: Syntax.ClassBody,
    +              body: classElements
    +          };
    +      }
    +  
    +      function parseClassExpression() {
    +          var id, body, previousYieldAllowed, superClass;
    +  
    +          expectKeyword('class');
    +  
    +          if (!matchKeyword('extends') && !match('{')) {
    +              id = parseVariableIdentifier();
    +          }
    +  
    +          if (matchKeyword('extends')) {
    +              expectKeyword('extends');
    +              previousYieldAllowed = yieldAllowed;
    +              yieldAllowed = false;
    +              superClass = parseAssignmentExpression();
    +              yieldAllowed = previousYieldAllowed;
    +          }
    +  
    +          body = parseClassBody();
    +          return {
    +              id: id,
    +              type: Syntax.ClassExpression,
    +              body: body,
    +              superClass: superClass
    +          };
    +      }
    +  
    +      function parseClassDeclaration() {
    +          var token, id, body, previousYieldAllowed, superClass;
    +  
    +          expectKeyword('class');
    +  
    +          token = lookahead();
    +          id = parseVariableIdentifier();
    +  
    +          if (matchKeyword('extends')) {
    +              expectKeyword('extends');
    +              previousYieldAllowed = yieldAllowed;
    +              yieldAllowed = false;
    +              superClass = parseAssignmentExpression();
    +              yieldAllowed = previousYieldAllowed;
    +          }
    +  
    +          body = parseClassBody();
    +          return {
    +              id: id,
    +              type: Syntax.ClassDeclaration,
    +              body: body,
    +              superClass: superClass
    +          };
    +      }
    +  
    +      // 15 Program
    +  
    +      function parseSourceElement() {
    +          var token = lookahead();
    +  
    +          if (token.type === Token.Keyword) {
    +              switch (token.value) {
    +              case 'const':
    +              case 'let':
    +                  return parseConstLetDeclaration(token.value);
    +              case 'function':
    +                  return parseFunctionDeclaration();
    +              default:
    +                  return parseStatement();
    +              }
    +          }
    +  
    +          if (token.type !== Token.EOF) {
    +              return parseStatement();
    +          }
    +      }
    +  
    +      function parseProgramElement() {
    +          var token = lookahead(), lineNumber;
    +  
    +          if (token.type === Token.Keyword) {
    +              switch (token.value) {
    +              case 'export':
    +                  return parseExportDeclaration();
    +              case 'import':
    +                  return parseImportDeclaration();
    +              }
    +          }
    +  
    +          if (token.value === 'module' && token.type === Token.Identifier) {
    +              lineNumber = token.lineNumber;
    +              token = lookahead2();
    +              if (token.type === Token.Identifier && token.lineNumber === lineNumber) {
    +                  return parseModuleDeclaration();
    +              }
    +          }
    +  
    +          return parseSourceElement();
    +      }
    +  
    +      function parseProgramElements() {
    +          var sourceElement, sourceElements = [], token, directive, firstRestricted;
    +  
    +          while (index < length) {
    +              token = lookahead();
    +              if (token.type !== Token.StringLiteral) {
    +                  break;
    +              }
    +  
    +              sourceElement = parseProgramElement();
    +              sourceElements.push(sourceElement);
    +              if (sourceElement.expression.type !== Syntax.Literal) {
    +                  // this is not directive
    +                  break;
    +              }
    +              directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
    +              if (directive === 'use strict') {
    +                  strict = true;
    +                  if (firstRestricted) {
    +                      throwError(firstRestricted, Messages.StrictOctalLiteral);
    +                  }
    +              } else {
    +                  if (!firstRestricted && token.octal) {
    +                      firstRestricted = token;
    +                  }
    +              }
    +          }
    +  
    +          while (index < length) {
    +              sourceElement = parseProgramElement();
    +              if (typeof sourceElement === 'undefined') {
    +                  break;
    +              }
    +              sourceElements.push(sourceElement);
    +          }
    +          return sourceElements;
    +      }
    +  
    +      function parseModuleElement() {
    +          return parseProgramElement();
    +      }
    +  
    +      function parseModuleElements() {
    +          var list = [],
    +              statement;
    +  
    +          while (index < length) {
    +              if (match('}')) {
    +                  break;
    +              }
    +              statement = parseModuleElement();
    +              if (typeof statement === 'undefined') {
    +                  break;
    +              }
    +              list.push(statement);
    +          }
    +  
    +          return list;
    +      }
    +  
    +      function parseModuleBlock() {
    +          var block;
    +  
    +          expect('{');
    +  
    +          block = parseModuleElements();
    +  
    +          expect('}');
    +  
    +          return {
    +              type: Syntax.BlockStatement,
    +              body: block
    +          };
    +      }
    +  
    +      function parseProgram() {
    +          var program;
    +          strict = false;
    +          yieldAllowed = false;
    +          yieldFound = false;
    +          program = {
    +              type: Syntax.Program,
    +              body: parseProgramElements()
    +          };
    +          return program;
    +      }
    +  
    +      // The following functions are needed only when the option to preserve
    +      // the comments is active.
    +  
    +      function addComment(type, value, start, end, loc) {
    +          assert(typeof start === 'number', 'Comment must have valid position');
    +  
    +          // Because the way the actual token is scanned, often the comments
    +          // (if any) are skipped twice during the lexical analysis.
    +          // Thus, we need to skip adding a comment if the comment array already
    +          // handled it.
    +          if (extra.comments.length > 0) {
    +              if (extra.comments[extra.comments.length - 1].range[1] > start) {
    +                  return;
    +              }
    +          }
    +  
    +          extra.comments.push({
    +              type: type,
    +              value: value,
    +              range: [start, end],
    +              loc: loc
    +          });
    +      }
    +  
    +      function scanComment() {
    +          var comment, ch, loc, start, blockComment, lineComment;
    +  
    +          comment = '';
    +          blockComment = false;
    +          lineComment = false;
    +  
    +          while (index < length) {
    +              ch = source[index];
    +  
    +              if (lineComment) {
    +                  ch = nextChar();
    +                  if (isLineTerminator(ch)) {
    +                      loc.end = {
    +                          line: lineNumber,
    +                          column: index - lineStart - 1
    +                      };
    +                      lineComment = false;
    +                      addComment('Line', comment, start, index - 1, loc);
    +                      if (ch === '\r' && source[index] === '\n') {
    +                          ++index;
    +                      }
    +                      ++lineNumber;
    +                      lineStart = index;
    +                      comment = '';
    +                  } else if (index >= length) {
    +                      lineComment = false;
    +                      comment += ch;
    +                      loc.end = {
    +                          line: lineNumber,
    +                          column: length - lineStart
    +                      };
    +                      addComment('Line', comment, start, length, loc);
    +                  } else {
    +                      comment += ch;
    +                  }
    +              } else if (blockComment) {
    +                  if (isLineTerminator(ch)) {
    +                      if (ch === '\r' && source[index + 1] === '\n') {
    +                          ++index;
    +                          comment += '\r\n';
    +                      } else {
    +                          comment += ch;
    +                      }
    +                      ++lineNumber;
    +                      ++index;
    +                      lineStart = index;
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                  } else {
    +                      ch = nextChar();
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                      comment += ch;
    +                      if (ch === '*') {
    +                          ch = source[index];
    +                          if (ch === '/') {
    +                              comment = comment.substr(0, comment.length - 1);
    +                              blockComment = false;
    +                              ++index;
    +                              loc.end = {
    +                                  line: lineNumber,
    +                                  column: index - lineStart
    +                              };
    +                              addComment('Block', comment, start, index, loc);
    +                              comment = '';
    +                          }
    +                      }
    +                  }
    +              } else if (ch === '/') {
    +                  ch = source[index + 1];
    +                  if (ch === '/') {
    +                      loc = {
    +                          start: {
    +                              line: lineNumber,
    +                              column: index - lineStart
    +                          }
    +                      };
    +                      start = index;
    +                      index += 2;
    +                      lineComment = true;
    +                      if (index >= length) {
    +                          loc.end = {
    +                              line: lineNumber,
    +                              column: index - lineStart
    +                          };
    +                          lineComment = false;
    +                          addComment('Line', comment, start, index, loc);
    +                      }
    +                  } else if (ch === '*') {
    +                      start = index;
    +                      index += 2;
    +                      blockComment = true;
    +                      loc = {
    +                          start: {
    +                              line: lineNumber,
    +                              column: index - lineStart - 2
    +                          }
    +                      };
    +                      if (index >= length) {
    +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    +                      }
    +                  } else {
    +                      break;
    +                  }
    +              } else if (isWhiteSpace(ch)) {
    +                  ++index;
    +              } else if (isLineTerminator(ch)) {
    +                  ++index;
    +                  if (ch ===  '\r' && source[index] === '\n') {
    +                      ++index;
    +                  }
    +                  ++lineNumber;
    +                  lineStart = index;
    +              } else {
    +                  break;
    +              }
    +          }
    +      }
    +  
    +      function filterCommentLocation() {
    +          var i, entry, comment, comments = [];
    +  
    +          for (i = 0; i < extra.comments.length; ++i) {
    +              entry = extra.comments[i];
    +              comment = {
    +                  type: entry.type,
    +                  value: entry.value
    +              };
    +              if (extra.range) {
    +                  comment.range = entry.range;
    +              }
    +              if (extra.loc) {
    +                  comment.loc = entry.loc;
    +              }
    +              comments.push(comment);
    +          }
    +  
    +          extra.comments = comments;
    +      }
    +  
    +      function collectToken() {
    +          var start, loc, token, range, value;
    +  
    +          skipComment();
    +          start = index;
    +          loc = {
    +              start: {
    +                  line: lineNumber,
    +                  column: index - lineStart
    +              }
    +          };
    +  
    +          token = extra.advance();
    +          loc.end = {
    +              line: lineNumber,
    +              column: index - lineStart
    +          };
    +  
    +          if (token.type !== Token.EOF) {
    +              range = [token.range[0], token.range[1]];
    +              value = sliceSource(token.range[0], token.range[1]);
    +              extra.tokens.push({
    +                  type: TokenName[token.type],
    +                  value: value,
    +                  range: range,
    +                  loc: loc
    +              });
    +          }
    +  
    +          return token;
    +      }
    +  
    +      function collectRegex() {
    +          var pos, loc, regex, token;
    +  
    +          skipComment();
    +  
    +          pos = index;
    +          loc = {
    +              start: {
    +                  line: lineNumber,
    +                  column: index - lineStart
    +              }
    +          };
    +  
    +          regex = extra.scanRegExp();
    +          loc.end = {
    +              line: lineNumber,
    +              column: index - lineStart
    +          };
    +  
    +          // Pop the previous token, which is likely '/' or '/='
    +          if (extra.tokens.length > 0) {
    +              token = extra.tokens[extra.tokens.length - 1];
    +              if (token.range[0] === pos && token.type === 'Punctuator') {
    +                  if (token.value === '/' || token.value === '/=') {
    +                      extra.tokens.pop();
    +                  }
    +              }
    +          }
    +  
    +          extra.tokens.push({
    +              type: 'RegularExpression',
    +              value: regex.literal,
    +              range: [pos, index],
    +              loc: loc
    +          });
    +  
    +          return regex;
    +      }
    +  
    +      function filterTokenLocation() {
    +          var i, entry, token, tokens = [];
    +  
    +          for (i = 0; i < extra.tokens.length; ++i) {
    +              entry = extra.tokens[i];
    +              token = {
    +                  type: entry.type,
    +                  value: entry.value
    +              };
    +              if (extra.range) {
    +                  token.range = entry.range;
    +              }
    +              if (extra.loc) {
    +                  token.loc = entry.loc;
    +              }
    +              tokens.push(token);
    +          }
    +  
    +          extra.tokens = tokens;
    +      }
    +  
    +      function createLiteral(token) {
    +          return {
    +              type: Syntax.Literal,
    +              value: token.value
    +          };
    +      }
    +  
    +      function createRawLiteral(token) {
    +          return {
    +              type: Syntax.Literal,
    +              value: token.value,
    +              raw: sliceSource(token.range[0], token.range[1])
    +          };
    +      }
    +  
    +      function wrapTrackingFunction(range, loc) {
    +  
    +          return function (parseFunction) {
    +  
    +              function isBinary(node) {
    +                  return node.type === Syntax.LogicalExpression ||
    +                      node.type === Syntax.BinaryExpression;
    +              }
    +  
    +              function visit(node) {
    +                  if (isBinary(node.left)) {
    +                      visit(node.left);
    +                  }
    +                  if (isBinary(node.right)) {
    +                      visit(node.right);
    +                  }
    +  
    +                  if (range && typeof node.range === 'undefined') {
    +                      node.range = [node.left.range[0], node.right.range[1]];
    +                  }
    +                  if (loc && typeof node.loc === 'undefined') {
    +                      node.loc = {
    +                          start: node.left.loc.start,
    +                          end: node.right.loc.end
    +                      };
    +                  }
    +              }
    +  
    +              return function () {
    +                  var node, rangeInfo, locInfo;
    +  
    +                  skipComment();
    +                  rangeInfo = [index, 0];
    +                  locInfo = {
    +                      start: {
    +                          line: lineNumber,
    +                          column: index - lineStart
    +                      }
    +                  };
    +  
    +                  node = parseFunction.apply(null, arguments);
    +                  if (typeof node !== 'undefined') {
    +  
    +                      if (range) {
    +                          rangeInfo[1] = index;
    +                          node.range = rangeInfo;
    +                      }
    +  
    +                      if (loc) {
    +                          locInfo.end = {
    +                              line: lineNumber,
    +                              column: index - lineStart
    +                          };
    +                          node.loc = locInfo;
    +                      }
    +  
    +                      if (isBinary(node)) {
    +                          visit(node);
    +                      }
    +  
    +                      if (node.type === Syntax.MemberExpression) {
    +                          if (typeof node.object.range !== 'undefined') {
    +                              node.range[0] = node.object.range[0];
    +                          }
    +                          if (typeof node.object.loc !== 'undefined') {
    +                              node.loc.start = node.object.loc.start;
    +                          }
    +                      }
    +  
    +                      if (node.type === Syntax.CallExpression) {
    +                          if (typeof node.callee.range !== 'undefined') {
    +                              node.range[0] = node.callee.range[0];
    +                          }
    +                          if (typeof node.callee.loc !== 'undefined') {
    +                              node.loc.start = node.callee.loc.start;
    +                          }
    +                      }
    +                      return node;
    +                  }
    +              };
    +  
    +          };
    +      }
    +  
    +      function patch() {
    +  
    +          var wrapTracking;
    +  
    +          if (extra.comments) {
    +              extra.skipComment = skipComment;
    +              skipComment = scanComment;
    +          }
    +  
    +          if (extra.raw) {
    +              extra.createLiteral = createLiteral;
    +              createLiteral = createRawLiteral;
    +          }
    +  
    +          if (extra.range || extra.loc) {
    +  
    +              wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
    +  
    +              extra.parseAdditiveExpression = parseAdditiveExpression;
    +              extra.parseAssignmentExpression = parseAssignmentExpression;
    +              extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
    +              extra.parseBitwiseORExpression = parseBitwiseORExpression;
    +              extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
    +              extra.parseBlock = parseBlock;
    +              extra.parseFunctionSourceElements = parseFunctionSourceElements;
    +              extra.parseCallMember = parseCallMember;
    +              extra.parseCatchClause = parseCatchClause;
    +              extra.parseComputedMember = parseComputedMember;
    +              extra.parseConditionalExpression = parseConditionalExpression;
    +              extra.parseConstLetDeclaration = parseConstLetDeclaration;
    +              extra.parseEqualityExpression = parseEqualityExpression;
    +              extra.parseExportDeclaration = parseExportDeclaration;
    +              extra.parseExportSpecifier = parseExportSpecifier;
    +              extra.parseExportSpecifierSetProperty = parseExportSpecifierSetProperty;
    +              extra.parseExpression = parseExpression;
    +              extra.parseForVariableDeclaration = parseForVariableDeclaration;
    +              extra.parseFunctionDeclaration = parseFunctionDeclaration;
    +              extra.parseFunctionExpression = parseFunctionExpression;
    +              extra.parseGlob = parseGlob;
    +              extra.parseImportDeclaration = parseImportDeclaration;
    +              extra.parseImportSpecifier = parseImportSpecifier;
    +              extra.parseLogicalANDExpression = parseLogicalANDExpression;
    +              extra.parseLogicalORExpression = parseLogicalORExpression;
    +              extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
    +              extra.parseModuleDeclaration = parseModuleDeclaration;
    +              extra.parseModuleBlock = parseModuleBlock;
    +              extra.parseNewExpression = parseNewExpression;
    +              extra.parseNonComputedMember = parseNonComputedMember;
    +              extra.parseNonComputedProperty = parseNonComputedProperty;
    +              extra.parseObjectProperty = parseObjectProperty;
    +              extra.parseObjectPropertyKey = parseObjectPropertyKey;
    +              extra.parsePath = parsePath;
    +              extra.parsePostfixExpression = parsePostfixExpression;
    +              extra.parsePrimaryExpression = parsePrimaryExpression;
    +              extra.parseProgram = parseProgram;
    +              extra.parsePropertyFunction = parsePropertyFunction;
    +              extra.parseRelationalExpression = parseRelationalExpression;
    +              extra.parseStatement = parseStatement;
    +              extra.parseShiftExpression = parseShiftExpression;
    +              extra.parseSwitchCase = parseSwitchCase;
    +              extra.parseUnaryExpression = parseUnaryExpression;
    +              extra.parseVariableDeclaration = parseVariableDeclaration;
    +              extra.parseVariableIdentifier = parseVariableIdentifier;
    +              extra.parseMethodDefinition = parseMethodDefinition;
    +              extra.parseClassDeclaration = parseClassDeclaration;
    +              extra.parseClassExpression = parseClassExpression;
    +              extra.parseClassBody = parseClassBody;
    +  
    +              parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
    +              parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
    +              parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
    +              parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
    +              parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
    +              parseBlock = wrapTracking(extra.parseBlock);
    +              parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
    +              parseCallMember = wrapTracking(extra.parseCallMember);
    +              parseCatchClause = wrapTracking(extra.parseCatchClause);
    +              parseComputedMember = wrapTracking(extra.parseComputedMember);
    +              parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
    +              parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
    +              parseExportDeclaration = wrapTracking(parseExportDeclaration);
    +              parseExportSpecifier = wrapTracking(parseExportSpecifier);
    +              parseExportSpecifierSetProperty = wrapTracking(parseExportSpecifierSetProperty);
    +              parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
    +              parseExpression = wrapTracking(extra.parseExpression);
    +              parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
    +              parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
    +              parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
    +              parseGlob = wrapTracking(extra.parseGlob);
    +              parseImportDeclaration = wrapTracking(extra.parseImportDeclaration);
    +              parseImportSpecifier = wrapTracking(extra.parseImportSpecifier);
    +              parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
    +              parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
    +              parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
    +              parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration);
    +              parseModuleBlock = wrapTracking(extra.parseModuleBlock);
    +              parseNewExpression = wrapTracking(extra.parseNewExpression);
    +              parseNonComputedMember = wrapTracking(extra.parseNonComputedMember);
    +              parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
    +              parseObjectProperty = wrapTracking(extra.parseObjectProperty);
    +              parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
    +              parsePath = wrapTracking(extra.parsePath);
    +              parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
    +              parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
    +              parseProgram = wrapTracking(extra.parseProgram);
    +              parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
    +              parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
    +              parseStatement = wrapTracking(extra.parseStatement);
    +              parseShiftExpression = wrapTracking(extra.parseShiftExpression);
    +              parseSwitchCase = wrapTracking(extra.parseSwitchCase);
    +              parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
    +              parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
    +              parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
    +              parseMethodDefinition = wrapTracking(extra.parseMethodDefinition);
    +              parseClassDeclaration = wrapTracking(extra.parseClassDeclaration);
    +              parseClassExpression = wrapTracking(extra.parseClassExpression);
    +              parseClassBody = wrapTracking(extra.parseClassBody);
    +          }
    +  
    +          if (typeof extra.tokens !== 'undefined') {
    +              extra.advance = advance;
    +              extra.scanRegExp = scanRegExp;
    +  
    +              advance = collectToken;
    +              scanRegExp = collectRegex;
    +          }
    +      }
    +  
    +      function unpatch() {
    +          if (typeof extra.skipComment === 'function') {
    +              skipComment = extra.skipComment;
    +          }
    +  
    +          if (extra.raw) {
    +              createLiteral = extra.createLiteral;
    +          }
    +  
    +          if (extra.range || extra.loc) {
    +              parseAdditiveExpression = extra.parseAdditiveExpression;
    +              parseAssignmentExpression = extra.parseAssignmentExpression;
    +              parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
    +              parseBitwiseORExpression = extra.parseBitwiseORExpression;
    +              parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
    +              parseBlock = extra.parseBlock;
    +              parseFunctionSourceElements = extra.parseFunctionSourceElements;
    +              parseCallMember = extra.parseCallMember;
    +              parseCatchClause = extra.parseCatchClause;
    +              parseComputedMember = extra.parseComputedMember;
    +              parseConditionalExpression = extra.parseConditionalExpression;
    +              parseConstLetDeclaration = extra.parseConstLetDeclaration;
    +              parseEqualityExpression = extra.parseEqualityExpression;
    +              parseExportDeclaration = extra.parseExportDeclaration;
    +              parseExportSpecifier = extra.parseExportSpecifier;
    +              parseExportSpecifierSetProperty = extra.parseExportSpecifierSetProperty;
    +              parseExpression = extra.parseExpression;
    +              parseForVariableDeclaration = extra.parseForVariableDeclaration;
    +              parseFunctionDeclaration = extra.parseFunctionDeclaration;
    +              parseFunctionExpression = extra.parseFunctionExpression;
    +              parseGlob = extra.parseGlob;
    +              parseImportDeclaration = extra.parseImportDeclaration;
    +              parseImportSpecifier = extra.parseImportSpecifier;
    +              parseLogicalANDExpression = extra.parseLogicalANDExpression;
    +              parseLogicalORExpression = extra.parseLogicalORExpression;
    +              parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
    +              parseModuleDeclaration = extra.parseModuleDeclaration;
    +              parseModuleBlock = extra.parseModuleBlock;
    +              parseNewExpression = extra.parseNewExpression;
    +              parseNonComputedMember = extra.parseNonComputedMember;
    +              parseNonComputedProperty = extra.parseNonComputedProperty;
    +              parseObjectProperty = extra.parseObjectProperty;
    +              parseObjectPropertyKey = extra.parseObjectPropertyKey;
    +              parsePath = extra.parsePath;
    +              parsePostfixExpression = extra.parsePostfixExpression;
    +              parsePrimaryExpression = extra.parsePrimaryExpression;
    +              parseProgram = extra.parseProgram;
    +              parsePropertyFunction = extra.parsePropertyFunction;
    +              parseRelationalExpression = extra.parseRelationalExpression;
    +              parseStatement = extra.parseStatement;
    +              parseShiftExpression = extra.parseShiftExpression;
    +              parseSwitchCase = extra.parseSwitchCase;
    +              parseUnaryExpression = extra.parseUnaryExpression;
    +              parseVariableDeclaration = extra.parseVariableDeclaration;
    +              parseVariableIdentifier = extra.parseVariableIdentifier;
    +              parseMethodDefinition = extra.parseMethodDefinition;
    +              parseClassDeclaration = extra.parseClassDeclaration;
    +              parseClassExpression = extra.parseClassExpression;
    +              parseClassBody = extra.parseClassBody;
    +          }
    +  
    +          if (typeof extra.scanRegExp === 'function') {
    +              advance = extra.advance;
    +              scanRegExp = extra.scanRegExp;
    +          }
    +      }
    +  
    +      function stringToArray(str) {
    +          var length = str.length,
    +              result = [],
    +              i;
    +          for (i = 0; i < length; ++i) {
    +              result[i] = str.charAt(i);
    +          }
    +          return result;
    +      }
    +  
    +      function parse(code, options) {
    +          var program, toString;
    +  
    +          toString = String;
    +          if (typeof code !== 'string' && !(code instanceof String)) {
    +              code = toString(code);
    +          }
    +  
    +          source = code;
    +          index = 0;
    +          lineNumber = (source.length > 0) ? 1 : 0;
    +          lineStart = 0;
    +          length = source.length;
    +          buffer = null;
    +          state = {
    +              allowIn: true,
    +              labelSet: {},
    +              parenthesizedCount: 0,
    +              lastParenthesized: null,
    +              inFunctionBody: false,
    +              inIteration: false,
    +              inSwitch: false
    +          };
    +  
    +          extra = {};
    +          if (typeof options !== 'undefined') {
    +              extra.range = (typeof options.range === 'boolean') && options.range;
    +              extra.loc = (typeof options.loc === 'boolean') && options.loc;
    +              extra.raw = (typeof options.raw === 'boolean') && options.raw;
    +              if (typeof options.tokens === 'boolean' && options.tokens) {
    +                  extra.tokens = [];
    +              }
    +              if (typeof options.comment === 'boolean' && options.comment) {
    +                  extra.comments = [];
    +              }
    +              if (typeof options.tolerant === 'boolean' && options.tolerant) {
    +                  extra.errors = [];
    +              }
    +          }
    +  
    +          if (length > 0) {
    +              if (typeof source[0] === 'undefined') {
    +                  // Try first to convert to a string. This is good as fast path
    +                  // for old IE which understands string indexing for string
    +                  // literals only and not for string object.
    +                  if (code instanceof String) {
    +                      source = code.valueOf();
    +                  }
    +  
    +                  // Force accessing the characters via an array.
    +                  if (typeof source[0] === 'undefined') {
    +                      source = stringToArray(code);
    +                  }
    +              }
    +          }
    +  
    +          patch();
    +          try {
    +              program = parseProgram();
    +              if (typeof extra.comments !== 'undefined') {
    +                  filterCommentLocation();
    +                  program.comments = extra.comments;
    +              }
    +              if (typeof extra.tokens !== 'undefined') {
    +                  filterTokenLocation();
    +                  program.tokens = extra.tokens;
    +              }
    +              if (typeof extra.errors !== 'undefined') {
    +                  program.errors = extra.errors;
    +              }
    +          } catch (e) {
    +              throw e;
    +          } finally {
    +              unpatch();
    +              extra = {};
    +          }
    +  
    +          return program;
    +      }
    +  
    +      // Sync with package.json.
    +      exports.version = '1.0.0-dev-harmony';
    +  
    +      exports.parse = parse;
    +  
    +      // Deep copy.
    +      exports.Syntax = (function () {
    +          var name, types = {};
    +  
    +          if (typeof Object.create === 'function') {
    +              types = Object.create(null);
    +          }
    +  
    +          for (name in Syntax) {
    +              if (Syntax.hasOwnProperty(name)) {
    +                  types[name] = Syntax[name];
    +              }
    +          }
    +  
    +          if (typeof Object.freeze === 'function') {
    +              Object.freeze(types);
    +          }
    +  
    +          return types;
    +      }());
    +  
    +  }));
    +  /* vim: set sw=4 ts=4 et tw=80 : */
    + +
    + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/index.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/index.html new file mode 100644 index 000000000..ec2af9c5a --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/index.html @@ -0,0 +1,37 @@ + + + + +Esprima: Unit Tests + + + + + + + +
    + + + +

    Unit Tests ensures the correct implementation

    +

    Esprima version .

    +

    Please wait...

    +
    + +
    + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.html b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.html new file mode 100644 index 000000000..7173a30cc --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.html @@ -0,0 +1,36 @@ + + + + +Esprima: Module Loading Test + + + + +
    + + + +

    Module Loading works also with web browsers

    + +

    The following tests are to ensure that Esprima can be loaded using AMD (Asynchronous Module Definition) loader such as RequireJS.

    +

    +
    + +
    + + + + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.js new file mode 100644 index 000000000..bba84c740 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/module.js @@ -0,0 +1,129 @@ +/*jslint browser:true plusplus:true */ +/*global require:true */ +function runTests() { + 'use strict'; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function reportSuccess(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + } + + function reportFailure(code, expected, actual) { + var report, e; + + report = document.getElementById('report'); + + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Expected type: ' + expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual type: ' + actual); + report.appendChild(e); + } + + + require(['../esprima'], function (ESParser) { + var tick, total, failures, obj, variable, variables, i, entry, entries; + + // We check only the type of some members of ESParser. + variables = { + 'version': 'string', + 'parse': 'function', + 'Syntax': 'object', + 'Syntax.AssignmentExpression': 'string', + 'Syntax.ArrayExpression': 'string', + 'Syntax.BlockStatement': 'string', + 'Syntax.BinaryExpression': 'string', + 'Syntax.BreakStatement': 'string', + 'Syntax.CallExpression': 'string', + 'Syntax.CatchClause': 'string', + 'Syntax.ConditionalExpression': 'string', + 'Syntax.ContinueStatement': 'string', + 'Syntax.DoWhileStatement': 'string', + 'Syntax.DebuggerStatement': 'string', + 'Syntax.EmptyStatement': 'string', + 'Syntax.ExpressionStatement': 'string', + 'Syntax.ForStatement': 'string', + 'Syntax.ForInStatement': 'string', + 'Syntax.FunctionDeclaration': 'string', + 'Syntax.FunctionExpression': 'string', + 'Syntax.Identifier': 'string', + 'Syntax.IfStatement': 'string', + 'Syntax.Literal': 'string', + 'Syntax.LabeledStatement': 'string', + 'Syntax.LogicalExpression': 'string', + 'Syntax.MemberExpression': 'string', + 'Syntax.NewExpression': 'string', + 'Syntax.ObjectExpression': 'string', + 'Syntax.Program': 'string', + 'Syntax.Property': 'string', + 'Syntax.ReturnStatement': 'string', + 'Syntax.SequenceExpression': 'string', + 'Syntax.SwitchStatement': 'string', + 'Syntax.SwitchCase': 'string', + 'Syntax.ThisExpression': 'string', + 'Syntax.ThrowStatement': 'string', + 'Syntax.TryStatement': 'string', + 'Syntax.UnaryExpression': 'string', + 'Syntax.UpdateExpression': 'string', + 'Syntax.VariableDeclaration': 'string', + 'Syntax.VariableDeclarator': 'string', + 'Syntax.WhileStatement': 'string', + 'Syntax.WithStatement': 'string' + }; + + total = failures = 0; + tick = new Date(); + + for (variable in variables) { + if (variables.hasOwnProperty(variable)) { + entries = variable.split('.'); + obj = ESParser; + for (i = 0; i < entries.length; ++i) { + entry = entries[i]; + if (typeof obj[entry] !== 'undefined') { + obj = obj[entry]; + } else { + obj = undefined; + break; + } + } + total++; + if (typeof obj === variables[variable]) { + reportSuccess(variable); + } else { + failures++; + reportFailure(variable, variables[variable], typeof obj); + } + } + } + + tick = (new Date()) - tick; + + if (failures > 0) { + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }); +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/reflect.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/reflect.js new file mode 100644 index 000000000..ffbeb5371 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/reflect.js @@ -0,0 +1,422 @@ +// This is modified from Mozilla Reflect.parse test suite (the file is located +// at js/src/tests/js1_8_5/extensions/reflect-parse.js in the source tree). +// +// Some notable changes: +// * Removed unsupported features (destructuring, let, comprehensions...). +// * Removed tests for E4X (ECMAScript for XML). +// * Removed everything related to builder. +// * Enclosed every 'Pattern' construct with a scope. +// * Tweaked some expected tree to remove generator field. +// * Removed the test for bug 632030 and bug 632024. + +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/licenses/publicdomain/ + */ + +(function (exports) { + +function testReflect(Reflect, Pattern) { + +function program(elts) { return Pattern({ type: "Program", body: elts }) } +function exprStmt(expr) { return Pattern({ type: "ExpressionStatement", expression: expr }) } +function throwStmt(expr) { return Pattern({ type: "ThrowStatement", argument: expr }) } +function returnStmt(expr) { return Pattern({ type: "ReturnStatement", argument: expr }) } +function yieldExpr(expr) { return Pattern({ type: "YieldExpression", argument: expr }) } +function lit(val) { return Pattern({ type: "Literal", value: val }) } +var thisExpr = Pattern({ type: "ThisExpression" }); +function funDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function declarator(id, init) { return Pattern({ type: "VariableDeclarator", id: id, init: init }) } +function varDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "var" }) } +function letDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "let" }) } +function constDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "const" }) } +function ident(name) { return Pattern({ type: "Identifier", name: name }) } +function dotExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: false, object: obj, property: id }) } +function memExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: true, object: obj, property: id }) } +function forStmt(init, test, update, body) { return Pattern({ type: "ForStatement", init: init, test: test, update: update, body: body }) } +function forInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: false }) } +function forEachInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: true }) } +function breakStmt(lab) { return Pattern({ type: "BreakStatement", label: lab }) } +function continueStmt(lab) { return Pattern({ type: "ContinueStatement", label: lab }) } +function blockStmt(body) { return Pattern({ type: "BlockStatement", body: body }) } +var emptyStmt = Pattern({ type: "EmptyStatement" }); +function ifStmt(test, cons, alt) { return Pattern({ type: "IfStatement", test: test, alternate: alt, consequent: cons }) } +function labStmt(lab, stmt) { return Pattern({ type: "LabeledStatement", label: lab, body: stmt }) } +function withStmt(obj, stmt) { return Pattern({ type: "WithStatement", object: obj, body: stmt }) } +function whileStmt(test, stmt) { return Pattern({ type: "WhileStatement", test: test, body: stmt }) } +function doStmt(stmt, test) { return Pattern({ type: "DoWhileStatement", test: test, body: stmt }) } +function switchStmt(disc, cases) { return Pattern({ type: "SwitchStatement", discriminant: disc, cases: cases }) } +function caseClause(test, stmts) { return Pattern({ type: "SwitchCase", test: test, consequent: stmts }) } +function defaultClause(stmts) { return Pattern({ type: "SwitchCase", test: null, consequent: stmts }) } +function catchClause(id, guard, body) { if (guard) { return Pattern({ type: "GuardedCatchClause", param: id, guard: guard, body: body }) } else { return Pattern({ type: "CatchClause", param: id, body: body }) } } +function tryStmt(body, guarded, catches, fin) { return Pattern({ type: "TryStatement", block: body, guardedHandlers: guarded, handlers: catches, finalizer: fin }) } +function letStmt(head, body) { return Pattern({ type: "LetStatement", head: head, body: body }) } +function funExpr(id, args, body, gen) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunExpr(id, args, body) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } + +function unExpr(op, arg) { return Pattern({ type: "UnaryExpression", operator: op, argument: arg }) } +function binExpr(op, left, right) { return Pattern({ type: "BinaryExpression", operator: op, left: left, right: right }) } +function aExpr(op, left, right) { return Pattern({ type: "AssignmentExpression", operator: op, left: left, right: right }) } +function updExpr(op, arg, prefix) { return Pattern({ type: "UpdateExpression", operator: op, argument: arg, prefix: prefix }) } +function logExpr(op, left, right) { return Pattern({ type: "LogicalExpression", operator: op, left: left, right: right }) } + +function condExpr(test, cons, alt) { return Pattern({ type: "ConditionalExpression", test: test, consequent: cons, alternate: alt }) } +function seqExpr(exprs) { return Pattern({ type: "SequenceExpression", expressions: exprs }) } +function newExpr(callee, args) { return Pattern({ type: "NewExpression", callee: callee, arguments: args }) } +function callExpr(callee, args) { return Pattern({ type: "CallExpression", callee: callee, arguments: args }) } +function arrExpr(elts) { return Pattern({ type: "ArrayExpression", elements: elts }) } +function objExpr(elts) { return Pattern({ type: "ObjectExpression", properties: elts }) } +function objProp(key, value, kind) { return Pattern({ type: "Property", key: key, value: value, kind: kind }) } + +function arrPatt(elts) { return Pattern({ type: "ArrayPattern", elements: elts }) } +function objPatt(elts) { return Pattern({ type: "ObjectPattern", properties: elts }) } + +function localSrc(src) { return "(function(){ " + src + " })" } +function localPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([patt])))]) } +function blockSrc(src) { return "(function(){ { " + src + " } })" } +function blockPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([blockStmt([patt])])))]) } + +function assertBlockStmt(src, patt) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src))); +} + +function assertBlockExpr(src, patt) { + assertBlockStmt(src, exprStmt(patt)); +} + +function assertBlockDecl(src, patt, builder) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src), {builder: builder})); +} + +function assertLocalStmt(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertLocalExpr(src, patt) { + assertLocalStmt(src, exprStmt(patt)); +} + +function assertLocalDecl(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertGlobalStmt(src, patt, builder) { + program([patt]).assert(Reflect.parse(src, {builder: builder})); +} + +function assertGlobalExpr(src, patt, builder) { + program([exprStmt(patt)]).assert(Reflect.parse(src, {builder: builder})); + //assertStmt(src, exprStmt(patt)); +} + +function assertGlobalDecl(src, patt) { + program([patt]).assert(Reflect.parse(src)); +} + +function assertProg(src, patt) { + program(patt).assert(Reflect.parse(src)); +} + +function assertStmt(src, patt) { + assertLocalStmt(src, patt); + assertGlobalStmt(src, patt); + assertBlockStmt(src, patt); +} + +function assertExpr(src, patt) { + assertLocalExpr(src, patt); + assertGlobalExpr(src, patt); + assertBlockExpr(src, patt); +} + +function assertDecl(src, patt) { + assertLocalDecl(src, patt); + assertGlobalDecl(src, patt); + assertBlockDecl(src, patt); +} + +function assertError(src, errorType) { + try { + Reflect.parse(src); + } catch (e) { + return; + } + throw new Error("expected " + errorType.name + " for " + uneval(src)); +} + + +// general tests + +// NB: These are useful but for now jit-test doesn't do I/O reliably. + +//program(_).assert(Reflect.parse(snarf('data/flapjax.txt'))); +//program(_).assert(Reflect.parse(snarf('data/jquery-1.4.2.txt'))); +//program(_).assert(Reflect.parse(snarf('data/prototype.js'))); +//program(_).assert(Reflect.parse(snarf('data/dojo.js.uncompressed.js'))); +//program(_).assert(Reflect.parse(snarf('data/mootools-1.2.4-core-nc.js'))); + + +// declarations + +assertDecl("var x = 1, y = 2, z = 3", + varDecl([declarator(ident("x"), lit(1)), + declarator(ident("y"), lit(2)), + declarator(ident("z"), lit(3))])); +assertDecl("var x, y, z", + varDecl([declarator(ident("x"), null), + declarator(ident("y"), null), + declarator(ident("z"), null)])); +assertDecl("function foo() { }", + funDecl(ident("foo"), [], blockStmt([]))); +assertDecl("function foo() { return 42 }", + funDecl(ident("foo"), [], blockStmt([returnStmt(lit(42))]))); + + +// Bug 591437: rebound args have their defs turned into uses +assertDecl("function f(a) { function a() { } }", + funDecl(ident("f"), [ident("a")], blockStmt([funDecl(ident("a"), [], blockStmt([]))]))); +assertDecl("function f(a,b,c) { function b() { } }", + funDecl(ident("f"), [ident("a"),ident("b"),ident("c")], blockStmt([funDecl(ident("b"), [], blockStmt([]))]))); + +// expressions + +assertExpr("true", lit(true)); +assertExpr("false", lit(false)); +assertExpr("42", lit(42)); +assertExpr("(/asdf/)", lit(/asdf/)); +assertExpr("this", thisExpr); +assertExpr("foo", ident("foo")); +assertExpr("foo.bar", dotExpr(ident("foo"), ident("bar"))); +assertExpr("foo[bar]", memExpr(ident("foo"), ident("bar"))); +assertExpr("(function(){})", funExpr(null, [], blockStmt([]))); +assertExpr("(function f() {})", funExpr(ident("f"), [], blockStmt([]))); +assertExpr("(function f(x,y,z) {})", funExpr(ident("f"), [ident("x"),ident("y"),ident("z")], blockStmt([]))); +assertExpr("(++x)", updExpr("++", ident("x"), true)); +assertExpr("(x++)", updExpr("++", ident("x"), false)); +assertExpr("(+x)", unExpr("+", ident("x"))); +assertExpr("(-x)", unExpr("-", ident("x"))); +assertExpr("(!x)", unExpr("!", ident("x"))); +assertExpr("(~x)", unExpr("~", ident("x"))); +assertExpr("(delete x)", unExpr("delete", ident("x"))); +assertExpr("(typeof x)", unExpr("typeof", ident("x"))); +assertExpr("(void x)", unExpr("void", ident("x"))); +assertExpr("(x == y)", binExpr("==", ident("x"), ident("y"))); +assertExpr("(x != y)", binExpr("!=", ident("x"), ident("y"))); +assertExpr("(x === y)", binExpr("===", ident("x"), ident("y"))); +assertExpr("(x !== y)", binExpr("!==", ident("x"), ident("y"))); +assertExpr("(x < y)", binExpr("<", ident("x"), ident("y"))); +assertExpr("(x <= y)", binExpr("<=", ident("x"), ident("y"))); +assertExpr("(x > y)", binExpr(">", ident("x"), ident("y"))); +assertExpr("(x >= y)", binExpr(">=", ident("x"), ident("y"))); +assertExpr("(x << y)", binExpr("<<", ident("x"), ident("y"))); +assertExpr("(x >> y)", binExpr(">>", ident("x"), ident("y"))); +assertExpr("(x >>> y)", binExpr(">>>", ident("x"), ident("y"))); +assertExpr("(x + y)", binExpr("+", ident("x"), ident("y"))); +assertExpr("(w + x + y + z)", binExpr("+", binExpr("+", binExpr("+", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x - y)", binExpr("-", ident("x"), ident("y"))); +assertExpr("(w - x - y - z)", binExpr("-", binExpr("-", binExpr("-", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x * y)", binExpr("*", ident("x"), ident("y"))); +assertExpr("(x / y)", binExpr("/", ident("x"), ident("y"))); +assertExpr("(x % y)", binExpr("%", ident("x"), ident("y"))); +assertExpr("(x | y)", binExpr("|", ident("x"), ident("y"))); +assertExpr("(x ^ y)", binExpr("^", ident("x"), ident("y"))); +assertExpr("(x & y)", binExpr("&", ident("x"), ident("y"))); +assertExpr("(x in y)", binExpr("in", ident("x"), ident("y"))); +assertExpr("(x instanceof y)", binExpr("instanceof", ident("x"), ident("y"))); +assertExpr("(x = y)", aExpr("=", ident("x"), ident("y"))); +assertExpr("(x += y)", aExpr("+=", ident("x"), ident("y"))); +assertExpr("(x -= y)", aExpr("-=", ident("x"), ident("y"))); +assertExpr("(x *= y)", aExpr("*=", ident("x"), ident("y"))); +assertExpr("(x /= y)", aExpr("/=", ident("x"), ident("y"))); +assertExpr("(x %= y)", aExpr("%=", ident("x"), ident("y"))); +assertExpr("(x <<= y)", aExpr("<<=", ident("x"), ident("y"))); +assertExpr("(x >>= y)", aExpr(">>=", ident("x"), ident("y"))); +assertExpr("(x >>>= y)", aExpr(">>>=", ident("x"), ident("y"))); +assertExpr("(x |= y)", aExpr("|=", ident("x"), ident("y"))); +assertExpr("(x ^= y)", aExpr("^=", ident("x"), ident("y"))); +assertExpr("(x &= y)", aExpr("&=", ident("x"), ident("y"))); +assertExpr("(x || y)", logExpr("||", ident("x"), ident("y"))); +assertExpr("(x && y)", logExpr("&&", ident("x"), ident("y"))); +assertExpr("(w || x || y || z)", logExpr("||", logExpr("||", logExpr("||", ident("w"), ident("x")), ident("y")), ident("z"))) +assertExpr("(x ? y : z)", condExpr(ident("x"), ident("y"), ident("z"))); +assertExpr("(x,y)", seqExpr([ident("x"),ident("y")])) +assertExpr("(x,y,z)", seqExpr([ident("x"),ident("y"),ident("z")])) +assertExpr("(a,b,c,d,e,f,g)", seqExpr([ident("a"),ident("b"),ident("c"),ident("d"),ident("e"),ident("f"),ident("g")])); +assertExpr("(new Object)", newExpr(ident("Object"), [])); +assertExpr("(new Object())", newExpr(ident("Object"), [])); +assertExpr("(new Object(42))", newExpr(ident("Object"), [lit(42)])); +assertExpr("(new Object(1,2,3))", newExpr(ident("Object"), [lit(1),lit(2),lit(3)])); +assertExpr("(String())", callExpr(ident("String"), [])); +assertExpr("(String(42))", callExpr(ident("String"), [lit(42)])); +assertExpr("(String(1,2,3))", callExpr(ident("String"), [lit(1),lit(2),lit(3)])); +assertExpr("[]", arrExpr([])); +assertExpr("[1]", arrExpr([lit(1)])); +assertExpr("[1,2]", arrExpr([lit(1),lit(2)])); +assertExpr("[1,2,3]", arrExpr([lit(1),lit(2),lit(3)])); +assertExpr("[1,,2,3]", arrExpr([lit(1),,lit(2),lit(3)])); +assertExpr("[1,,,2,3]", arrExpr([lit(1),,,lit(2),lit(3)])); +assertExpr("[1,,,2,,3]", arrExpr([lit(1),,,lit(2),,lit(3)])); +assertExpr("[1,,,2,,,3]", arrExpr([lit(1),,,lit(2),,,lit(3)])); +assertExpr("[,1,2,3]", arrExpr([,lit(1),lit(2),lit(3)])); +assertExpr("[,,1,2,3]", arrExpr([,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined])); +assertExpr("[,,,1,2,3,,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined,undefined])); +assertExpr("[,,,,,]", arrExpr([undefined,undefined,undefined,undefined,undefined])); +assertExpr("({})", objExpr([])); +assertExpr("({x:1})", objExpr([objProp(ident("x"), lit(1), "init")])); +assertExpr("({x:1, y:2})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init")])); +assertExpr("({x:1, y:2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({x:1, 'y':2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, z:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, 3:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(lit(3), lit(3), "init") ])); + +// Bug 571617: eliminate constant-folding +assertExpr("2 + 3", binExpr("+", lit(2), lit(3))); + +// Bug 632026: constant-folding +assertExpr("typeof(0?0:a)", unExpr("typeof", condExpr(lit(0), lit(0), ident("a")))); + +// Bug 632056: constant-folding +program([exprStmt(ident("f")), + ifStmt(lit(1), + funDecl(ident("f"), [], blockStmt([])), + null)]).assert(Reflect.parse("f; if (1) function f(){}")); + +// statements + +assertStmt("throw 42", throwStmt(lit(42))); +assertStmt("for (;;) break", forStmt(null, null, null, breakStmt(null))); +assertStmt("for (x; y; z) break", forStmt(ident("x"), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x; y; z) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; y; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (x; ; z) break", forStmt(ident("x"), null, ident("z"), breakStmt(null))); +assertStmt("for (var x; ; z) break", forStmt(varDecl([declarator(ident("x"), null)]), null, ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; ; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), null, ident("z"), breakStmt(null))); +assertStmt("for (x; y; ) break", forStmt(ident("x"), ident("y"), null, breakStmt(null))); +assertStmt("for (var x; y; ) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x = 42; y; ) break", forStmt(varDecl([declarator(ident("x"),lit(42))]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x in y) break", forInStmt(varDecl([declarator(ident("x"),null)]), ident("y"), breakStmt(null))); +assertStmt("for (x in y) break", forInStmt(ident("x"), ident("y"), breakStmt(null))); +assertStmt("{ }", blockStmt([])); +assertStmt("{ throw 1; throw 2; throw 3; }", blockStmt([ throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))])); +assertStmt(";", emptyStmt); +assertStmt("if (foo) throw 42;", ifStmt(ident("foo"), throwStmt(lit(42)), null)); +assertStmt("if (foo) throw 42; else true;", ifStmt(ident("foo"), throwStmt(lit(42)), exprStmt(lit(true)))); +assertStmt("if (foo) { throw 1; throw 2; throw 3; }", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + null)); +assertStmt("if (foo) { throw 1; throw 2; throw 3; } else true;", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + exprStmt(lit(true)))); +assertStmt("foo: for(;;) break foo;", labStmt(ident("foo"), forStmt(null, null, null, breakStmt(ident("foo"))))); +assertStmt("foo: for(;;) continue foo;", labStmt(ident("foo"), forStmt(null, null, null, continueStmt(ident("foo"))))); +assertStmt("with (obj) { }", withStmt(ident("obj"), blockStmt([]))); +assertStmt("with (obj) { obj; }", withStmt(ident("obj"), blockStmt([exprStmt(ident("obj"))]))); +assertStmt("while (foo) { }", whileStmt(ident("foo"), blockStmt([]))); +assertStmt("while (foo) { foo; }", whileStmt(ident("foo"), blockStmt([exprStmt(ident("foo"))]))); +assertStmt("do { } while (foo);", doStmt(blockStmt([]), ident("foo"))); +assertStmt("do { foo; } while (foo)", doStmt(blockStmt([exprStmt(ident("foo"))]), ident("foo"))); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]) ])); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; case 42: 42; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]), + caseClause(lit(42), [ exprStmt(lit(42)) ]) ])); +assertStmt("try { } catch (e) { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + null)); +assertStmt("try { } catch (e) { } finally { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + blockStmt([]))); +assertStmt("try { } finally { }", + tryStmt(blockStmt([]), + [], + [], + blockStmt([]))); + +// redeclarations (TOK_NAME nodes with lexdef) + +assertStmt("function f() { function g() { } function g() { } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([]))]))); + +assertStmt("function f() { function g() { } function g() { return 42 } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([returnStmt(lit(42))]))]))); + +assertStmt("function f() { var x = 42; var x = 43; }", + funDecl(ident("f"), [], blockStmt([varDecl([declarator(ident("x"),lit(42))]), + varDecl([declarator(ident("x"),lit(43))])]))); + +// getters and setters + + assertExpr("({ get x() { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [], blockStmt([returnStmt(lit(42))])), + "get" ) ])); + assertExpr("({ set x(v) { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [ident("v")], blockStmt([returnStmt(lit(42))])), + "set" ) ])); + +} + +exports.testReflect = testReflect; + +}(typeof exports === 'undefined' ? this : exports)); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/run.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/run.js new file mode 100644 index 000000000..32ca3faa4 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/run.js @@ -0,0 +1,66 @@ +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint node:true */ + +(function () { + 'use strict'; + + var child = require('child_process'), + nodejs = '"' + process.execPath + '"', + ret = 0, + suites, + index; + + suites = [ + 'runner', + 'compat' + ]; + + function nextTest() { + var suite = suites[index]; + + if (index < suites.length) { + child.exec(nodejs + ' ./test/' + suite + '.js', function (err, stdout, stderr) { + if (stdout) { + process.stdout.write(suite + ': ' + stdout); + } + if (stderr) { + process.stderr.write(suite + ': ' + stderr); + } + if (err) { + ret = err.code; + } + index += 1; + nextTest(); + }); + } else { + process.exit(ret); + } + } + + index = 0; + nextTest(); +}()); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/runner.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/runner.js new file mode 100644 index 000000000..c1a3fc9bf --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/runner.js @@ -0,0 +1,387 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint browser:true node:true */ +/*global esprima:true, testFixture:true */ + +var runTests; + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + 'use strict'; + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +function NotMatchingError(expected, actual) { + 'use strict'; + Error.call(this, 'Expected '); + this.expected = expected; + this.actual = actual; +} +NotMatchingError.prototype = new Error(); + +function errorToObject(e) { + 'use strict'; + var msg = e.toString(); + + // Opera 9.64 produces an non-standard string in toString(). + if (msg.substr(0, 6) !== 'Error:') { + if (typeof e.message === 'string') { + msg = 'Error: ' + e.message; + } + } + + return { + index: e.index, + lineNumber: e.lineNumber, + column: e.column, + message: msg + }; +} + +function testParse(esprima, code, syntax) { + 'use strict'; + var expected, tree, actual, options, StringObject, i, len, err; + + // alias, so that JSLint does not complain. + StringObject = String; + + options = { + comment: (typeof syntax.comments !== 'undefined'), + range: true, + loc: true, + tokens: (typeof syntax.tokens !== 'undefined'), + raw: true, + tolerant: (typeof syntax.errors !== 'undefined') + }; + + if (typeof syntax.tokens !== 'undefined') { + if (syntax.tokens.length > 0) { + options.range = (typeof syntax.tokens[0].range !== 'undefined'); + options.loc = (typeof syntax.tokens[0].loc !== 'undefined'); + } + } + + if (typeof syntax.comments !== 'undefined') { + if (syntax.comments.length > 0) { + options.range = (typeof syntax.comments[0].range !== 'undefined'); + options.loc = (typeof syntax.comments[0].loc !== 'undefined'); + } + } + + expected = JSON.stringify(syntax, null, 4); + try { + tree = esprima.parse(code, options); + tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + + actual = JSON.stringify(tree, adjustRegexLiteral, 4); + + // Only to ensure that there is no error when using string object. + esprima.parse(new StringObject(code), options); + + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } + + function filter(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return (key === 'loc' || key === 'range') ? undefined : value; + } + + if (options.tolerant) { + return; + } + + + // Check again without any location info. + options.range = false; + options.loc = false; + expected = JSON.stringify(syntax, filter, 4); + try { + tree = esprima.parse(code, options); + tree = (options.comment || options.tokens) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + + actual = JSON.stringify(tree, filter, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function testError(esprima, code, exception) { + 'use strict'; + var i, options, expected, actual, handleInvalidRegexFlag; + + // Different parsing options should give the same error. + options = [ + {}, + { comment: true }, + { raw: true }, + { raw: true, comment: true } + ]; + + // If handleInvalidRegexFlag is true, an invalid flag in a regular expression + // will throw an exception. In some old version V8, this is not the case + // and hence handleInvalidRegexFlag is false. + handleInvalidRegexFlag = false; + try { + 'test'.match(new RegExp('[a-z]', 'x')); + } catch (e) { + handleInvalidRegexFlag = true; + } + + expected = JSON.stringify(exception); + + for (i = 0; i < options.length; i += 1) { + + try { + esprima.parse(code, options[i]); + } catch (e) { + actual = JSON.stringify(errorToObject(e)); + } + + if (expected !== actual) { + + // Compensate for old V8 which does not handle invalid flag. + if (exception.message.indexOf('Invalid regular expression') > 0) { + if (typeof actual === 'undefined' && !handleInvalidRegexFlag) { + return; + } + } + + throw new NotMatchingError(expected, actual); + } + + } +} + +function testAPI(esprima, code, result) { + 'use strict'; + var expected, res, actual; + + expected = JSON.stringify(result.result, null, 4); + try { + if (typeof result.property !== 'undefined') { + res = esprima[result.property]; + } else { + res = esprima[result.call].apply(esprima, result.args); + } + actual = JSON.stringify(res, adjustRegexLiteral, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function runTest(esprima, code, result) { + 'use strict'; + if (result.hasOwnProperty('lineNumber')) { + testError(esprima, code, result); + } else if (result.hasOwnProperty('result')) { + testAPI(esprima, code, result); + } else { + testParse(esprima, code, result); + } +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + runTests = function () { + 'use strict'; + var total = 0, + failures = 0, + category, + fixture, + source, + tick, + expected, + index, + len; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function startCategory(category) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('h4'); + setText(e, category); + report.appendChild(e); + } + + function reportSuccess(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + } + + function reportFailure(code, expected, actual) { + var report, e; + + report = document.getElementById('report'); + + e = document.createElement('p'); + setText(e, 'Code:'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Expected'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'expected'); + setText(e, expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'actual'); + setText(e, actual); + report.appendChild(e); + } + + setText(document.getElementById('version'), esprima.version); + + tick = new Date(); + for (category in testFixture) { + if (testFixture.hasOwnProperty(category)) { + startCategory(category); + fixture = testFixture[category]; + for (source in fixture) { + if (fixture.hasOwnProperty(source)) { + expected = fixture[source]; + total += 1; + try { + runTest(esprima, source, expected); + reportSuccess(source, JSON.stringify(expected, null, 4)); + } catch (e) { + failures += 1; + reportFailure(source, e.expected, e.actual); + } + } + } + } + } + tick = (new Date()) - tick; + + if (failures > 0) { + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }; +} else { + (function () { + 'use strict'; + + var esprima = require('../esprima'), + vm = require('vm'), + fs = require('fs'), + total = 0, + failures = [], + tick = new Date(), + expected, + header; + + vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8')); + + Object.keys(testFixture).forEach(function (category) { + Object.keys(testFixture[category]).forEach(function (source) { + total += 1; + expected = testFixture[category][source]; + try { + runTest(esprima, source, expected); + } catch (e) { + e.source = source; + failures.push(e); + } + }); + }); + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + }()); +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/test.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/test.js new file mode 100644 index 000000000..780af55aa --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/node_modules/esprima/test/test.js @@ -0,0 +1,19764 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL 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 testFixture = { + + 'Primary Expression': { + + 'this\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'ThisExpression', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + } + }], + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + }, + tokens: [{ + type: 'Keyword', + value: 'this', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + 'null\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: null, + raw: 'null', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + } + }], + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + }, + tokens: [{ + type: 'Null', + value: 'null', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + '\n 42\n\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [5, 9], + loc: { + start: { line: 2, column: 4 }, + end: { line: 4, column: 0 } + } + }], + range: [5, 9], + loc: { + start: { line: 2, column: 4 }, + end: { line: 4, column: 0 } + }, + tokens: [{ + type: 'Numeric', + value: '42', + range: [5, 7], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }] + }, + + '(1 + 2 ) * 3': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 1, + raw: '1', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'Literal', + value: 2, + raw: '2', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [1, 6], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Literal', + value: 3, + raw: '3', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + } + + }, + + 'Grouping Operator': { + + '(1) + (2 ) + 3': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 1, + raw: '1', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'Literal', + value: 2, + raw: '2', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + right: { + type: 'Literal', + value: 3, + raw: '3', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '4 + 5 << (6)': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 4, + raw: '4', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 5, + raw: '5', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 6, + raw: '6', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + } + + }, + + 'Array Initializer': { + + 'x = []': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + }, + tokens: [{ + type: 'Identifier', + value: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, { + type: 'Punctuator', + value: '=', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Punctuator', + value: '[', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: ']', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }] + }, + + 'x = [ ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x = [ 42 ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }], + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'x = [ 42, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }], + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x = [ ,, 42 ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [ + null, + null, + { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'x = [ 1, 2, 3, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 1, + raw: '1', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Literal', + value: 2, + raw: '2', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, { + type: 'Literal', + value: 3, + raw: '3', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = [ 1, 2,, 3, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 1, + raw: '1', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Literal', + value: 2, + raw: '2', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, null, { + type: 'Literal', + value: 3, + raw: '3', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + '日本語 = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '日本語', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'T\u203F = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u203F', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'T\u200C = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u200C', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'T\u200D = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u200D', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\u2163\u2161 = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '\u2163\u2161', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\u2163\u2161\u200A=\u2009[]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '\u2163\u2161', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Object Initializer': { + + 'x = {}': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x = { }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x = { answer: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'answer', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [14, 16], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 16 } + } + }, + kind: 'init', + range: [6, 16], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 16 } + } + }], + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'x = { if: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + kind: 'init', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x = { true: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + kind: 'init', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = { false: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [6, 11], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 11 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + kind: 'init', + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'x = { null: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + kind: 'init', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = { "answer": 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'answer', + raw: '"answer"', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [16, 18], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 18 } + } + }, + kind: 'init', + range: [6, 18], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 18 } + } + }], + range: [4, 20], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'x = { x: 1, x: 2 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + kind: 'init', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + { + type: 'Property', + key: { + type: 'Identifier', + name: 'x', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + value: { + type: 'Literal', + value: 2, + raw: '2', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + kind: 'init', + range: [12, 16], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 16 } + } + } + ], + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'x = { get width() { return m_width } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'width', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ReturnStatement', + argument: { + type: 'Identifier', + name: 'm_width', + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }, + range: [20, 35], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 35 } + } + }], + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + kind: 'get', + range: [6, 36], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 36 } + } + }], + range: [4, 38], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'x = { get undef() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'undef', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + kind: 'get', + range: [6, 20], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 20 } + } + }], + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'x = { get if() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + kind: 'get', + range: [6, 17], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 17 } + } + }], + range: [4, 19], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'x = { get true() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + kind: 'get', + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'x = { get false() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + kind: 'get', + range: [6, 20], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 20 } + } + }], + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'x = { get null() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + kind: 'get', + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'x = { get "undef"() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'undef', + raw: '"undef"', + range: [10, 17], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 17 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + rest: null, + generator: false, + expression: false, + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + kind: 'get', + range: [6, 22], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 22 } + } + }], + range: [4, 24], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'x = { get 10() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 10, + raw: '10', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + kind: 'get', + range: [6, 17], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 17 } + } + }], + range: [4, 19], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'x = { set width(w) { m_width = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'width', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_width', + range: [21, 28], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set if(w) { m_if = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_if', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + range: [18, 26], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 26 } + } + }, + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }], + range: [16, 28], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 28 } + } + }, + rest: null, + generator: false, + expression: false, + range: [16, 28], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 28 } + } + }, + kind: 'set', + range: [6, 28], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 28 } + } + }], + range: [4, 30], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'x = { set true(w) { m_true = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_true', + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + kind: 'set', + range: [6, 32], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 32 } + } + }], + range: [4, 34], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'x = { set false(w) { m_false = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_false', + range: [21, 28], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set null(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + kind: 'set', + range: [6, 32], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 32 } + } + }], + range: [4, 34], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'x = { set "null"(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'null', + raw: '"null"', + range: [10, 16], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 16 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [22, 28], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [22, 32], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 32 } + } + }, + range: [22, 33], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 33 } + } + }], + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set 10(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 10, + raw: '10', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [18, 24], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 24 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [27, 28], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 28 } + } + }, + range: [18, 28], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 28 } + } + }, + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }], + range: [16, 30], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 30 } + } + }, + rest: null, + generator: false, + expression: false, + range: [16, 30], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 30 } + } + }, + kind: 'set', + range: [6, 30], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 30 } + } + }], + range: [4, 32], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 32 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + + 'x = { get: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'get', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + kind: 'init', + range: [6, 13], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 15], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + 'x = { set: 43 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'set', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + value: { + type: 'Literal', + value: 43, + raw: '43', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + kind: 'init', + range: [6, 13], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 15], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + } + + }, + + 'Comments': { + + '/* block comment */ 42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + + '42 /*The*/ /*Answer*/': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + comments: [{ + type: 'Block', + value: 'The', + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, { + type: 'Block', + value: 'Answer', + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }] + }, + + '42 /*the*/ /*answer*/': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2] + }, + range: [0, 21] + }], + range: [0, 21], + comments: [{ + type: 'Block', + value: 'the', + range: [3, 10] + }, { + type: 'Block', + value: 'answer', + range: [11, 21] + }] + }, + + '/* multiline\ncomment\nshould\nbe\nignored */ 42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [42, 44], + loc: { + start: { line: 5, column: 11 }, + end: { line: 5, column: 13 } + } + }, + range: [42, 44], + loc: { + start: { line: 5, column: 11 }, + end: { line: 5, column: 13 } + } + }, + + '/*a\r\nb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\r\nb', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\rb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\rb', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\nb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\nb', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\nc*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\nc', + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '// line comment\n42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [16, 18], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [16, 18], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + + '42 // line comment': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + comments: [{ + type: 'Line', + value: ' line comment', + range: [3, 18], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 18 } + } + }] + }, + + '// Hello, world!\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '// Hello, world!\n': { + type: 'Program', + body: [], + range: [17, 17], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 0 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '// Hallo, world!\n': { + type: 'Program', + body: [], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 0 } + }, + comments: [{ + type: 'Line', + value: ' Hallo, world!', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '//\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + }, + comments: [{ + type: 'Line', + value: '', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }] + }, + + '//': { + type: 'Program', + body: [], + range: [2, 2], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 2 } + }, + comments: [{ + type: 'Line', + value: '', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }] + }, + + '// ': { + type: 'Program', + body: [], + range: [3, 3], + comments: [{ + type: 'Line', + value: ' ', + range: [0, 3] + }] + }, + + '/**/42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + }, + comments: [{ + type: 'Block', + value: '', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + '// Hello, world!\n\n// Another hello\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + } + }, + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + } + }], + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Line', + value: ' Another hello', + range: [18, 36], + loc: { + start: { line: 3, column: 0 }, + end: { line: 3, column: 18 } + } + }] + }, + + 'if (x) { // Some comment\ndoThat(); }': { + type: 'Program', + body: [{ + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + consequent: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [25, 31], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }, + 'arguments': [], + range: [25, 33], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 8 } + } + }, + range: [25, 34], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 9 } + } + }], + range: [7, 36], + loc: { + start: { line: 1, column: 7 }, + end: { line: 2, column: 11 } + } + }, + alternate: null, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 11 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 11 } + }, + comments: [{ + type: 'Line', + value: ' Some comment', + range: [9, 24], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 24 } + } + }] + }, + + 'switch (answer) { case 42: /* perfect */ bingo() }': { + type: 'Program', + body: [{ + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'bingo', + range: [41, 46], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 46 } + } + }, + 'arguments': [], + range: [41, 48], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 48 } + } + }, + range: [41, 49], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 49 } + } + }], + range: [18, 49], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 49 } + } + }], + range: [0, 50], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 50 } + } + }], + range: [0, 50], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 50 } + }, + comments: [{ + type: 'Block', + value: ' perfect ', + range: [27, 40], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 40 } + } + }] + } + + }, + + 'Numeric Literals': { + + '0': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + + '42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '3': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 3, + raw: '3', + range: [0, 1] + }, + range: [0, 1] + }], + range: [0, 1], + tokens: [{ + type: 'Numeric', + value: '3', + range: [0, 1] + }] + }, + + '5': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 5, + raw: '5', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + }, + tokens: [{ + type: 'Numeric', + value: '5', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }] + }, + + '.14': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0.14, + raw: '.14', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '3.14159': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 3.14159, + raw: '3.14159', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '6.02214179e+23': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 6.02214179e+23, + raw: '6.02214179e+23', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '1.492417830e-10': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 1.49241783e-10, + raw: '1.492417830e-10', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '0x0': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0x0', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '0e+100': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0e+100', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '0xabc': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0xabc, + raw: '0xabc', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0xdef': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0xdef, + raw: '0xdef', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0X1A': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x1A, + raw: '0X1A', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '0x10': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x10, + raw: '0x10', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '0x100': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x100, + raw: '0x100', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0X04': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0X04, + raw: '0X04', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '02': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 2, + raw: '02', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '012': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 10, + raw: '012', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '0012': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 10, + raw: '0012', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + } + + }, + + 'String Literals': { + + '"Hello"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello', + raw: '"Hello"', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '"\\n\\r\\t\\v\\b\\f\\\\\\\'\\"\\0"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: '\n\r\t\v\b\f\\\'"\x00', + raw: '"\\n\\r\\t\\v\\b\\f\\\\\\\'\\"\\0"', + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + '"\\u0061"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'a', + raw: '"\\u0061"', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + '"\\x61"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'a', + raw: '"\\x61"', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '"\\u00"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'u00', + raw: '"\\u00"', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '"\\xt"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'xt', + raw: '"\\xt"', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '"Hello\\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\nworld', + raw: '"Hello\\nworld"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '"Hello\\\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Helloworld', + raw: '"Hello\\\nworld"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 14 } + } + }, + + '"Hello\\02World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0002World', + raw: '"Hello\\02World"', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '"Hello\\012World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u000AWorld', + raw: '"Hello\\012World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\122World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\122World', + raw: '"Hello\\122World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\0122World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u000A2World', + raw: '"Hello\\0122World"', + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + '"Hello\\312World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u00CAWorld', + raw: '"Hello\\312World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\412World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\412World', + raw: '"Hello\\412World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\812World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello812World', + raw: '"Hello\\812World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\712World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\712World', + raw: '"Hello\\712World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\0World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0000World', + raw: '"Hello\\0World"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '"Hello\\\r\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Helloworld', + raw: '"Hello\\\r\nworld"', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + + '"Hello\\1World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0001World', + raw: '"Hello\\1World"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + }, + + 'Regular Expression Literals': { + + 'var x = /[a-z]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[a-z]/i', + raw: '/[a-z]/i', + range: [8, 16], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }, + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }], + kind: 'var', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[a-z]/i', + range: [8, 16], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }] + }, + + 'var x = /[x-z]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5] + }, + init: { + type: 'Literal', + value: '/[x-z]/i', + raw: '/[x-z]/i', + range: [8, 16] + }, + range: [4, 16] + }], + kind: 'var', + range: [0, 16] + }], + range: [0, 16], + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3] + }, { + type: 'Identifier', + value: 'x', + range: [4, 5] + }, { + type: 'Punctuator', + value: '=', + range: [6, 7] + }, { + type: 'RegularExpression', + value: '/[x-z]/i', + range: [8, 16] + }] + }, + + 'var x = /[a-c]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[a-c]/i', + raw: '/[a-c]/i', + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }, + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }], + kind: 'var', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[a-c]/i', + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }] + }, + + 'var x = /[P QR]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/i', + raw: '/[P QR]/i', + range: [8, 17], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 17 } + } + }, + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }], + kind: 'var', + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }], + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/i', + range: [8, 17], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 17 } + } + }] + }, + + 'var x = /foo\\/bar/': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/foo\\/bar/', + raw: '/foo\\/bar/', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }, + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }], + kind: 'var', + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/foo\\/bar/', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }] + }, + + 'var x = /=([^=\\s])+/g': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/=([^=\\s])+/g', + raw: '/=([^=\\s])+/g', + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }, + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }], + kind: 'var', + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/=([^=\\s])+/g', + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }] + }, + + 'var x = /[P QR]/\\u0067': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/g', + raw: '/[P QR]/\\u0067', + range: [8, 22], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 22 } + } + }, + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/\\u0067', + range: [8, 22], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 22 } + } + }] + }, + + 'var x = /[P QR]/\\g': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/g', + raw: '/[P QR]/\\g', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }, + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }], + kind: 'var', + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/\\g', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }] + } + + }, + + 'Left-Hand-Side Expression': { + + 'new Button': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'Button', + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + 'arguments': [], + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'new Button()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'Button', + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + 'arguments': [], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + 'new new foo': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'new new foo()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'new foo().bar()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [10, 13], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + 'arguments': [], + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + 'new foo[bar]': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + range: [4, 12], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + 'new foo.bar()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + '( new foo).bar()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + 'arguments': [], + range: [2, 9], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 9 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [11, 14], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + 'arguments': [], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'foo(bar, baz)': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'bar', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Identifier', + name: 'baz', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + '( foo )()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'universe.milkyway': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'universe.milkyway.solarsystem': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + property: { + type: 'Identifier', + name: 'solarsystem', + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'universe.milkyway.solarsystem.Earth': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + property: { + type: 'Identifier', + name: 'solarsystem', + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + property: { + type: 'Identifier', + name: 'Earth', + range: [30, 35], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + + 'universe[galaxyName, otherUselessName]': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'SequenceExpression', + expressions: [{ + type: 'Identifier', + name: 'galaxyName', + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, { + type: 'Identifier', + name: 'otherUselessName', + range: [21, 37], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 37 } + } + }], + range: [9, 37], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 37 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'universe[galaxyName]': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'galaxyName', + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'universe[42].galaxies': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'universe(42).galaxies': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'universe(42).galaxies(14, 3, 77).milkyway': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 14, + raw: '14', + range: [22, 24], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 24 } + } + }, { + type: 'Literal', + value: 3, + raw: '3', + range: [26, 27], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 27 } + } + }, { + type: 'Literal', + value: 77, + raw: '77', + range: [29, 31], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 31 } + } + }], + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [33, 41], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 41 } + } + }, + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + + 'earth.asia.Indonesia.prepareForElection(2014)': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'earth', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + property: { + type: 'Identifier', + name: 'asia', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + property: { + type: 'Identifier', + name: 'Indonesia', + range: [11, 20], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + property: { + type: 'Identifier', + name: 'prepareForElection', + range: [21, 39], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 39 } + } + }, + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 2014, + raw: '2014', + range: [40, 44], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 44 } + } + }], + range: [0, 45], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 45 } + } + }, + range: [0, 45], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 45 } + } + }, + + 'universe.if': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'if', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'universe.true': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'true', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'universe.false': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'false', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'universe.null': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'null', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + } + + }, + + 'Postfix Expressions': { + + 'x++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + prefix: false, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'x--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + prefix: false, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'eval++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + prefix: false, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'eval--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + prefix: false, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'arguments++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + prefix: false, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'arguments--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + prefix: false, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + } + + }, + + 'Unary Operators': { + + '++x': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + prefix: true, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '--x': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + prefix: true, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '++eval': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }, + prefix: true, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '--eval': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }, + prefix: true, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '++arguments': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, + prefix: true, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + '--arguments': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, + prefix: true, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + '+x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '+', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '-x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '-', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '~x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '~', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '!x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '!', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + 'void x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'void', + argument: { + type: 'Identifier', + name: 'x', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'delete x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'delete', + argument: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'typeof x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'typeof', + argument: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + } + + }, + + 'Multiplicative Operators': { + + 'x * y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x / y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x % y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Additive Operators': { + + 'x + y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x - y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Bitwise Shift Operator': { + + 'x << y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >> y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >>> y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>>>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Relational Operators': { + + 'x < y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x > y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x <= y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >= y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x in y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: 'in', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x instanceof y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: 'instanceof', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x < y < z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Equality Operators': { + + 'x == y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '==', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x != y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '!=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x === y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '===', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x !== y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '!==', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Binary Bitwise Operators': { + + 'x & y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x ^ y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x | y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Binary Expressions': { + + 'x + y + z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y + z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y - z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y - z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y / z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y % z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y / z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y % z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x % y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x << y << z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x | y | z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x & y & z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x ^ y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x & y | z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x | y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x | y & z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Binary Logical Operators': { + + 'x || y': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x && y': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x || y || z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x && y && z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x || y && z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [5, 11], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x || y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + } + + }, + + 'Conditional Operator': { + + 'y ? 1 : 2': { + type: 'ExpressionStatement', + expression: { + type: 'ConditionalExpression', + test: { + type: 'Identifier', + name: 'y', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + consequent: { + type: 'Literal', + value: 1, + raw: '1', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + alternate: { + type: 'Literal', + value: 2, + raw: '2', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x && y ? 1 : 2': { + type: 'ExpressionStatement', + expression: { + type: 'ConditionalExpression', + test: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + consequent: { + type: 'Literal', + value: 1, + raw: '1', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + alternate: { + type: 'Literal', + value: 2, + raw: '2', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + + }, + + 'Assignment Operators': { + + 'x = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'eval = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'arguments = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x *= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '*=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x /= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '/=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x %= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '%=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x += 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '+=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x -= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '-=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x <<= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '<<=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'x >>= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '>>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'x >>>= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '>>>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x &= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '&=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x ^= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '^=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x |= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '|=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Block': { + + '{ foo }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'foo', + range: [2, 5], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 5 } + } + }, + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '{ doThis(); doThat(); }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThis', + range: [2, 8], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [], + range: [2, 10], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 10 } + } + }, + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [12, 18], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 18 } + } + }, + 'arguments': [], + range: [12, 20], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 20 } + } + }, + range: [12, 21], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '{}': { + type: 'BlockStatement', + body: [], + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + } + + }, + + 'Variable Statement': { + + 'var x': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'var', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'var x, y;': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + init: null, + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }], + kind: 'var', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'var x = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 10 } + } + }, + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }], + kind: 'var', + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'var eval = 42, arguments = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'eval', + range: [4, 8], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 8 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'arguments', + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + range: [15, 29], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 29 } + } + }], + kind: 'var', + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'var x = 14, y = 3, z = 1977': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [8, 10], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 10 } + } + }, + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [12, 17], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 17 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [23, 27], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 27 } + } + }, + range: [19, 27], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 27 } + } + }], + kind: 'var', + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'var implements, interface, package': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'implements', + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, + init: null, + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'interface', + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, + init: null, + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'package', + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }, + init: null, + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }], + kind: 'var', + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'var private, protected, public, static': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'private', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + init: null, + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'protected', + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, + init: null, + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'public', + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, + init: null, + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'static', + range: [32, 38], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 38 } + } + }, + init: null, + range: [32, 38], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 38 } + } + }], + kind: 'var', + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + } + + }, + + 'Let Statement': { + + 'let x': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'let', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '{ let x }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: null, + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }], + kind: 'let', + range: [2, 8], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 8 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + '{ let x = 42 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + kind: 'let', + range: [2, 13], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 13 } + } + }], + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '{ let x = 14, y = 3, z = 1977 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + range: [14, 19], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 19 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [25, 29], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 29 } + } + }, + range: [21, 29], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 29 } + } + }], + kind: 'let', + range: [2, 30], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 30 } + } + }], + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + } + + }, + + 'Const Statement': { + + 'const x = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + kind: 'const', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + '{ const x = 42 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }], + kind: 'const', + range: [2, 15], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 15 } + } + }], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '{ const x = 14, y = 3, z = 1977 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + range: [16, 21], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 21 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [23, 31], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 31 } + } + }], + kind: 'const', + range: [2, 32], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 32 } + } + }], + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + } + + }, + + 'Empty Statement': { + + ';': { + type: 'EmptyStatement', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + } + + }, + + 'Expression Statement': { + + 'x': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + + 'x, y': { + type: 'ExpressionStatement', + expression: { + type: 'SequenceExpression', + expressions: [{ + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, { + type: 'Identifier', + name: 'y', + range: [3, 4], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 4 } + } + }], + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '\\u0061': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'a', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'a\\u0061': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'aa', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\\ua': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'ua', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'a\\u': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'au', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + } + + }, + + 'If Statement': { + + 'if (morning) goodMorning()': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodMorning', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + alternate: null, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'if (morning) (function(){})': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [24, 26], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 26 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: null, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'if (morning) var x = 0;': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [17, 22], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [13, 23], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 23 } + } + }, + alternate: null, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + 'if (morning) function a(){}': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'a', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [25, 27], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 27 } + } + }, + rest: null, + generator: false, + expression: false, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: null, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'if (morning) goodMorning(); else goodDay()': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodMorning', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodDay', + range: [33, 40], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 40 } + } + }, + 'arguments': [], + range: [33, 42], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 42 } + } + }, + range: [33, 42], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 42 } + } + }, + range: [0, 42], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 42 } + } + } + + }, + + 'Iteration Statements': { + + 'do keep(); while (true)': { + type: 'DoWhileStatement', + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'keep', + range: [3, 7], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [3, 9], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 9 } + } + }, + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + 'do keep(); while (true);': { + type: 'DoWhileStatement', + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'keep', + range: [3, 7], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [3, 9], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 9 } + } + }, + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'do { x++; y--; } while (x < 10)': { + type: 'DoWhileStatement', + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + prefix: false, + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + range: [5, 9], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 9 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + prefix: false, + range: [10, 13], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 13 } + } + }, + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }], + range: [3, 16], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 16 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + right: { + type: 'Literal', + value: 10, + raw: '10', + range: [28, 30], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 30 } + } + }, + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + '{ do { } while (false) false }': { + type: 'BlockStatement', + body: [{ + type: 'DoWhileStatement', + body: { + type: 'BlockStatement', + body: [], + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + test: { + type: 'Literal', + value: false, + raw: 'false', + range: [16, 21], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 21 } + } + }, + range: [2, 22], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 22 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: false, + raw: 'false', + range: [23, 28], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 28 } + } + }, + range: [23, 29], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 29 } + } + }], + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'while (true) doSomething()': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doSomething', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'while (x < 10) { x++; y--; }': { + type: 'WhileStatement', + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + right: { + type: 'Literal', + value: 10, + raw: '10', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + range: [7, 13], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 13 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }, + prefix: false, + range: [17, 20], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 20 } + } + }, + range: [17, 21], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 21 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + prefix: false, + range: [22, 25], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 25 } + } + }, + range: [22, 26], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 26 } + } + }], + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + }, + + 'for(;;);': { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'for(;;){}': { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'BlockStatement', + body: [], + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'for(x = 0;;);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'for(var x = 0;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }], + kind: 'var', + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'for(let x = 0;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }], + kind: 'let', + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'for(var x = 0, y = 1;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + init: { + type: 'Literal', + value: 1, + raw: '1', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }], + kind: 'var', + range: [4, 20], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 20 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'for(x = 0; x < 42;);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: null, + body: { + type: 'EmptyStatement', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'for(x = 0; x < 42; x++);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + prefix: false, + range: [19, 22], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 22 } + } + }, + body: { + type: 'EmptyStatement', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'for(x = 0; x < 42; x++) process(x);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + prefix: false, + range: [19, 22], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 22 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [24, 31], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 31 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [32, 33], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 33 } + } + }], + range: [24, 34], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 34 } + } + }, + range: [24, 35], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + + 'for(x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [15, 22], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 22 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }], + range: [15, 25], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 25 } + } + }, + range: [15, 26], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 26 } + } + }, + each: false, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'for (var x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: null, + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }], + kind: 'var', + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }], + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + each: false, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + 'for (var x = 42 in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + range: [9, 15], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 15 } + } + }], + kind: 'var', + range: [5, 15], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [19, 23], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 23 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [25, 32], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 32 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [25, 35], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 35 } + } + }, + range: [25, 36], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 36 } + } + }, + each: false, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'for (let x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: null, + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }], + kind: 'let', + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }], + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + each: false, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + 'for (let x = 42 in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + range: [9, 15], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 15 } + } + }], + kind: 'let', + range: [5, 15], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [19, 23], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 23 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [25, 32], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 32 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [25, 35], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 35 } + } + }, + range: [25, 36], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 36 } + } + }, + each: false, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'for (var i = function() { return 10 in [] } in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'i', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ReturnStatement', + argument: { + type: 'BinaryExpression', + operator: 'in', + left: { + type: 'Literal', + value: 10, + raw: '10', + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + range: [33, 41], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 41 } + } + }, + range: [26, 42], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 42 } + } + }], + range: [24, 43], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 43 } + } + }, + rest: null, + generator: false, + expression: false, + range: [13, 43], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 43 } + } + }, + range: [9, 43], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 43 } + } + }], + kind: 'var', + range: [5, 43], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 43 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [47, 51], + loc: { + start: { line: 1, column: 47 }, + end: { line: 1, column: 51 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [53, 60], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 60 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [61, 62], + loc: { + start: { line: 1, column: 61 }, + end: { line: 1, column: 62 } + } + }], + range: [53, 63], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 63 } + } + }, + range: [53, 64], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 64 } + } + }, + each: false, + range: [0, 64], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 64 } + } + } + + }, + + 'continue statement': { + + 'while (true) { continue; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: null, + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + } + ], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'while (true) { continue }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: null, + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + } + ], + range: [13, 25], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 25 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + 'done: while (true) { continue done }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: { + type: 'Identifier', + name: 'done', + range: [30, 34], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 34 } + } + }, + range: [21, 35], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 35 } + } + } + ], + range: [19, 36], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 36 } + } + }, + range: [6, 36], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'done: while (true) { continue done; }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: { + type: 'Identifier', + name: 'done', + range: [30, 34], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 34 } + } + }, + range: [21, 35], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 35 } + } + } + ], + range: [19, 37], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 37 } + } + }, + range: [6, 37], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 37 } + } + }, + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + } + } + + }, + + 'break statement': { + + 'while (true) { break }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: null, + range: [15, 21], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 21 } + } + } + ], + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'done: while (true) { break done }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'done', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + } + ], + range: [19, 33], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 33 } + } + }, + range: [6, 33], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 33 } + } + }, + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + }, + + 'done: while (true) { break done; }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'done', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + } + ], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + } + + }, + + 'return statement': { + + '(function(){ return })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 20], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 20 } + } + } + ], + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 21], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + '(function(){ return; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 20], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 20 } + } + } + ], + range: [11, 22], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 22 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 22], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '(function(){ return x; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + } + ], + range: [11, 24], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + '(function(){ return x * y })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + range: [20, 25], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 25 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + } + ], + range: [11, 27], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 27 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 27], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 27 } + } + }, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + } + }, + + 'with statement': { + + 'with (x) foo = bar': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [15, 18], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'with (x) foo = bar;': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [15, 18], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'with (x) { foo = bar }': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [11, 14], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 14 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [17, 20], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 20 } + } + }, + range: [11, 20], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 20 } + } + }, + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }], + range: [9, 22], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + } + + }, + + 'switch statement': { + + 'switch (x) {}': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'switch (answer) { case 42: hi(); break; }': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'hi', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + 'arguments': [], + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, { + type: 'BreakStatement', + label: null, + range: [33, 39], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 39 } + } + }], + range: [18, 39], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + + 'switch (answer) { case 42: hi(); break; default: break }': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'hi', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + 'arguments': [], + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, { + type: 'BreakStatement', + label: null, + range: [33, 39], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 39 } + } + }], + range: [18, 39], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 39 } + } + }, { + type: 'SwitchCase', + test: null, + consequent: [{ + type: 'BreakStatement', + label: null, + range: [49, 55], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 55 } + } + }], + range: [40, 55], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 55 } + } + }], + range: [0, 56], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 56 } + } + } + + }, + + 'Labelled Statements': { + + 'start: for (;;) break start': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'start', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + body: { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'start', + range: [22, 27], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 27 } + } + }, + range: [16, 27], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 27 } + } + }, + range: [7, 27], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 27 } + } + }, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'start: while (true) break start': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'start', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'start', + range: [26, 31], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 31 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + range: [7, 31], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 31 } + } + }, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + } + + }, + + 'throw statement': { + + 'throw x;': { + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'throw x * y': { + type: 'ThrowStatement', + argument: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [6, 11], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'throw { message: "Error" }': { + type: 'ThrowStatement', + argument: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'message', + range: [8, 15], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'Literal', + value: 'Error', + raw: '"Error"', + range: [17, 24], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 24 } + } + }, + kind: 'init', + range: [8, 24], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 24 } + } + }], + range: [6, 26], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + } + + }, + + 'try statement': { + + 'try { } catch (e) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [18, 21], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 21 } + } + }, + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }], + finalizer: null, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'try { } catch (eval) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'eval', + range: [15, 19], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 19 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + range: [8, 24], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 24 } + } + }], + finalizer: null, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'try { } catch (arguments) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'arguments', + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [26, 29], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 29 } + } + }, + range: [8, 29], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 29 } + } + }], + finalizer: null, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'try { } catch (e) { say(e) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }], + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }], + range: [18, 28], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 28 } + } + }, + range: [8, 28], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 28 } + } + }], + finalizer: null, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + }, + + 'try { } finally { cleanup(stuff) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [], + finalizer: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'cleanup', + range: [18, 25], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 25 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'stuff', + range: [26, 31], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + range: [18, 33], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 33 } + } + }], + range: [16, 34], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'try { doThat(); } catch (e) { say(e) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [34, 35], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 35 } + } + }], + range: [30, 36], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 36 } + } + }, + range: [30, 37], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 37 } + } + }], + range: [28, 38], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 38 } + } + }, + range: [18, 38], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 38 } + } + }], + finalizer: null, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'try { doThat(); } catch (e) { say(e) } finally { cleanup(stuff) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [34, 35], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 35 } + } + }], + range: [30, 36], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 36 } + } + }, + range: [30, 37], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 37 } + } + }], + range: [28, 38], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 38 } + } + }, + range: [18, 38], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 38 } + } + }], + finalizer: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'cleanup', + range: [49, 56], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 56 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'stuff', + range: [57, 62], + loc: { + start: { line: 1, column: 57 }, + end: { line: 1, column: 62 } + } + }], + range: [49, 63], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 63 } + } + }, + range: [49, 64], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 64 } + } + }], + range: [47, 65], + loc: { + start: { line: 1, column: 47 }, + end: { line: 1, column: 65 } + } + }, + range: [0, 65], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 65 } + } + } + + }, + + 'debugger statement': { + + 'debugger;': { + type: 'DebuggerStatement', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Function Definition': { + + 'function hello() { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [19, 24], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [19, 26], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 26 } + } + }, + range: [19, 27], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 27 } + } + }], + range: [17, 29], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 29 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'function eval() { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [16, 19], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'function arguments() { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'arguments', + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'function test(t, t) { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'test', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [{ + type: 'Identifier', + name: 't', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, { + type: 'Identifier', + name: 't', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '(function test(t, t) { })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'test', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 't', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Identifier', + name: 't', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + 'function eval() { function inner() { "use strict" } }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'inner', + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\"use strict\"', + range: [37, 49], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 49 } + } + }, + range: [37, 50], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 50 } + } + }], + range: [35, 51], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 51 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 51], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 51 } + } + }], + range: [16, 53], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 53 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 53], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 53 } + } + }, + + 'function hello(a) { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 'a', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [20, 25], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 25 } + } + }, + 'arguments': [], + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + range: [20, 28], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 28 } + } + }], + range: [18, 30], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 30 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'function hello(a, b) { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 'a', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Identifier', + name: 'b', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [23, 28], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 28 } + } + }, + 'arguments': [], + range: [23, 30], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 30 } + } + }, + range: [23, 31], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 31 } + } + }], + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + }, + + 'var hi = function() { sayHi() };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [22, 27], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [], + range: [22, 29], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 29 } + } + }, + range: [22, 30], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 30 } + } + }], + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 31], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 31 } + } + }, + range: [4, 31], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 31 } + } + }], + kind: 'var', + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + + 'var hi = function eval() { };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'eval', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [25, 28], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 28 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 28], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 28 } + } + }, + range: [4, 28], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 28 } + } + }], + kind: 'var', + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'var hi = function arguments() { };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'arguments', + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 33], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 33 } + } + }, + range: [4, 33], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 33 } + } + }], + kind: 'var', + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'var hello = function hi() { sayHi() };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hello', + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'hi', + range: [21, 23], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 23 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [28, 33], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [], + range: [28, 35], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 35 } + } + }, + range: [28, 36], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 36 } + } + }], + range: [26, 37], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [12, 37], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 37 } + } + }, + range: [4, 37], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 37 } + } + }], + kind: 'var', + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + '(function(){})': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 13], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + + }, + + 'Automatic semicolon insertion': { + + '{ x\n++y }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + range: [2, 4], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 2, column: 2 }, + end: { line: 2, column: 3 } + } + }, + prefix: true, + range: [4, 7], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 3 } + } + }, + range: [4, 8], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 4 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '{ x\n--y }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + range: [2, 4], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 2, column: 2 }, + end: { line: 2, column: 3 } + } + }, + prefix: true, + range: [4, 7], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 3 } + } + }, + range: [4, 8], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 4 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + 'var x /* comment */;': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'var', + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + '{ var x = 14, y = 3\nz; }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + range: [14, 19], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 19 } + } + }], + kind: 'var', + range: [2, 20], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'z', + range: [20, 21], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [20, 22], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 4 } + } + }, + + 'while (true) { continue\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [24, 29], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [24, 30], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 32], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { continue // Comment\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [35, 40], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [35, 41], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 43], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { continue /* Multiline\nComment */there; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [47, 52], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [47, 53], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [13, 55], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 18 } + } + }, + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + }, + + 'while (true) { break\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [21, 26], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [21, 27], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 29], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { break // Comment\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [32, 37], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [32, 38], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 40], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { break /* Multiline\nComment */there; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [44, 49], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [44, 50], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [13, 52], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 18 } + } + }, + range: [0, 52], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + }, + + '(function(){ return\nx; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [20, 22], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + } + ], + range: [11, 24], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 4 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 4 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '(function(){ return // Comment\nx; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [31, 32], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [31, 33], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + } + ], + range: [11, 35], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 4 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 35], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 4 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '(function(){ return/* Multiline\nComment */x; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [42, 43], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 11 } + } + }, + range: [42, 44], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 12 } + } + } + ], + range: [11, 46], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 14 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 46], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 14 } + } + }, + range: [0, 47], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + + '{ throw error\nerror; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 14], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [14, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [14, 20], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + '{ throw error// Comment\nerror; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 24], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [24, 29], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [24, 30], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + '{ throw error/* Multiline\nComment */error; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 36], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 10 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [36, 41], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [36, 42], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [0, 44], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + } + + }, + + 'Source elements': { + + '': { + type: 'Program', + body: [], + range: [0, 0], + loc: { + start: { line: 0, column: 0 }, + end: { line: 0, column: 0 } + }, + tokens: [] + } + }, + + 'Invalid syntax': { + + '{': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected end of input' + }, + + '}': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token }' + }, + + '3ea': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3in []': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e+': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e-': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3x': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3x0': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '0x': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '09': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '018': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '01a': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3in[]': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '0x3in[]': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"Hello\nWorld"': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\u005c': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\u002a': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'var x = /(s/g': { + index: 13, + lineNumber: 1, + column: 14, + message: 'Error: Line 1: Invalid regular expression' + }, + + '/': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + '/test': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + 'var x = /[a-z]/\\ux': { + index: 18, + lineNumber: 1, + column: 19, + message: 'Error: Line 1: Invalid regular expression' + }, + + '3 = 4': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + 'func() = 4': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '(1 + 1) = 10': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1++': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1--': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '++1': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '--1': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + 'for((1 + 1) in list) process(x);': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + '[': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected end of input' + }, + + '[,': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + {': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + { t:t ': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + { t:t,': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'var x = /\n/': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + 'var x = "\n': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'var if = 42': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token if' + }, + + 'i + 2 = 42': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '+i = 42': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1 + (': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + '\n\n\n{': { + index: 4, + lineNumber: 4, + column: 2, + message: 'Error: Line 4: Unexpected end of input' + }, + + '\n/* Some multiline\ncomment */\n)': { + index: 30, + lineNumber: 4, + column: 1, + message: 'Error: Line 4: Unexpected token )' + }, + + '{ set 1 }': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + '{ get 2 }': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + '({ set: s(if) { } })': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token if' + }, + + '({ set s(.) { } })': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token .' + }, + + '({ set: s() { } })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ set: s(a, b) { } })': { + index: 16, + lineNumber: 1, + column: 17, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ get: g(d) { } })': { + index: 13, + lineNumber: 1, + column: 14, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ get i() { }, i: 42 })': { + index: 21, + lineNumber: 1, + column: 22, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ i: 42, get i() { } })': { + index: 21, + lineNumber: 1, + column: 22, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ set i(x) { }, i: 42 })': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ i: 42, set i(x) { } })': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ get i() { }, get i() { } })': { + index: 27, + lineNumber: 1, + column: 28, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }, + + '({ set i(x) { }, set i(x) { } })': { + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }, + + 'function t(if) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token if' + }, + + 'function t(true) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token true' + }, + + 'function t(false) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token false' + }, + + 'function t(null) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token null' + }, + + 'function null() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token null' + }, + + 'function true() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token true' + }, + + 'function false() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token false' + }, + + 'function if() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token if' + }, + + 'a b;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected identifier' + }, + + 'if.a;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token .' + }, + + 'a if;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token if' + }, + + 'a class;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected reserved word' + }, + + 'break\n': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal break statement' + }, + + 'break 1;': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + 'continue\n': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'continue 2;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected number' + }, + + 'throw': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'throw;': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'throw\n': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal newline after throw' + }, + + 'for (var i, i2 in {});': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Unexpected token in' + }, + + 'for ((i in {}));': { + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Unexpected token )' + }, + + 'for (i + 1 in {});': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + 'for (+i in {});': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + 'if(false)': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'if(false) doThis(); else': { + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'do': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'while(false)': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'for(;;)': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'with(x)': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'try { }': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Missing catch or finally after try' + }, + + '\u203F = 10': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'const x = 12, y;': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'const x, y = 12;': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ,' + }, + + 'const x;': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'if(true) let a = 1;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token let' + }, + + 'if(true) const a = 1;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token const' + }, + + 'switch (c) { default: default: }': { + index: 30, + lineNumber: 1, + column: 31, + message: 'Error: Line 1: More than one default clause in switch statement' + }, + + 'new X()."s"': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Unexpected string' + }, + + '/*': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*\n\n\n': { + index: 5, + lineNumber: 4, + column: 1, + message: 'Error: Line 4: Unexpected token ILLEGAL' + }, + + '/**': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*\n\n*': { + index: 5, + lineNumber: 3, + column: 2, + message: 'Error: Line 3: Unexpected token ILLEGAL' + }, + + '/*hello': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*hello *': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\n]': { + index: 1, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\r]': { + index: 1, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\r\n]': { + index: 2, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\n\r]': { + index: 2, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '//\r\n]': { + index: 4, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '//\n\r]': { + index: 4, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/a\\\n/': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + '//\r \n]': { + index: 5, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/*\r\n*/]': { + index: 6, + lineNumber: 2, + column: 3, + message: 'Error: Line 2: Unexpected token ]' + }, + + '/*\n\r*/]': { + index: 6, + lineNumber: 3, + column: 3, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/*\r \n*/]': { + index: 7, + lineNumber: 3, + column: 3, + message: 'Error: Line 3: Unexpected token ]' + }, + + '\\\\': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\\u005c': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + + '\\x': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\\u0000': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\u200C = []': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\u200D = []': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"\\': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"\\u': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'return': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Illegal return statement' + }, + + 'break': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal break statement' + }, + + 'continue': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'switch (x) { default: continue; }': { + index: 31, + lineNumber: 1, + column: 32, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'do { x } *': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token *' + }, + + 'while (true) { break x; }': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'while (true) { continue x; }': { + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { break x; }); }': { + index: 40, + lineNumber: 1, + column: 41, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { continue x; }); }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { break; }); }': { + index: 39, + lineNumber: 1, + column: 40, + message: 'Error: Line 1: Illegal break statement' + }, + + 'x: while (true) { (function () { continue; }); }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'x: while (true) { x: while (true) { } }': { + index: 20, + lineNumber: 1, + column: 21, + message: 'Error: Line 1: Label \'x\' has already been declared' + }, + + '(function () { \'use strict\'; delete i; }())': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Delete of an unqualified identifier in strict mode.' + }, + + '(function () { \'use strict\'; with (i); }())': { + index: 28, + lineNumber: 1, + column: 29, + message: 'Error: Line 1: Strict mode code may not include a with statement' + }, + + 'function hello() {\'use strict\'; ({ i: 42, i: 42 }) }': { + index: 47, + lineNumber: 1, + column: 48, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ hasOwnProperty: 42, hasOwnProperty: 42 }) }': { + index: 73, + lineNumber: 1, + column: 74, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; var eval = 10; }': { + index: 40, + lineNumber: 1, + column: 41, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; var arguments = 10; }': { + index: 45, + lineNumber: 1, + column: 46, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; try { } catch (eval) { } }': { + index: 51, + lineNumber: 1, + column: 52, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; try { } catch (arguments) { } }': { + index: 56, + lineNumber: 1, + column: 57, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; eval = 10; }': { + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; arguments = 10; }': { + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ++eval; }': { + index: 38, + lineNumber: 1, + column: 39, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; --eval; }': { + index: 38, + lineNumber: 1, + column: 39, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; ++arguments; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; --arguments; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; eval++; }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; eval--; }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; arguments++; }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; arguments--; }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; function eval() { } }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; function arguments() { } }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function eval() {\'use strict\'; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function arguments() {\'use strict\'; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; (function eval() { }()) }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; (function arguments() { }()) }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function eval() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function arguments() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; ({ s: function eval() { } }); }': { + index: 47, + lineNumber: 1, + column: 48, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function package() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() {\'use strict\'; ({ i: 10, set s(eval) { } }); }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ set s(eval) { } }); }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ s: function s(eval) { } }); }': { + index: 49, + lineNumber: 1, + column: 50, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello(eval) {\'use strict\';}': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello(arguments) {\'use strict\';}': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() { \'use strict\'; function inner(eval) {} }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() { \'use strict\'; function inner(arguments) {} }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + ' "\\1"; \'use strict\';': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; "\\1"; }': { + index: 33, + lineNumber: 1, + column: 34, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; 021; }': { + index: 33, + lineNumber: 1, + column: 34, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; ({ "\\1": 42 }); }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; ({ 021: 42 }); }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "octal directive\\1"; "use strict"; }': { + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "octal directive\\1"; "octal directive\\2"; "use strict"; }': { + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "use strict"; function inner() { "octal directive\\1"; } }': { + index: 52, + lineNumber: 1, + column: 53, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "use strict"; var implements; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var interface; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var package; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var private; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var protected; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var public; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var static; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var yield; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var let; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello(static) { "use strict"; }': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function static() { "use strict"; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'var yield': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token yield' + }, + + 'var let': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token let' + }, + + '"use strict"; function static() { }': { + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function a(t, t) { "use strict"; }': { + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + 'function a(eval) { "use strict"; }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function a(package) { "use strict"; }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function a() { "use strict"; function b(t, t) { }; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + '(function a(t, t) { "use strict"; })': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + 'function a() { "use strict"; (function b(t, t) { }); }': { + index: 44, + lineNumber: 1, + column: 45, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + '(function a(eval) { "use strict"; })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + '(function a(package) { "use strict"; })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Use of future reserved word in strict mode' + } + + }, + + 'API': { + 'parse()': { + call: 'parse', + args: [], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'undefined' + } + }] + } + }, + + 'parse(null)': { + call: 'parse', + args: [null], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: null + } + }] + } + }, + + 'parse(42)': { + call: 'parse', + args: [42], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42 + } + }] + } + }, + + 'parse(true)': { + call: 'parse', + args: [true], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: true + } + }] + } + }, + + 'parse(undefined)': { + call: 'parse', + args: [void 0], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'undefined' + } + }] + } + }, + + 'parse(new String("test"))': { + call: 'parse', + args: [new String('test')], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'test' + } + }] + } + }, + + 'parse(new Number(42))': { + call: 'parse', + args: [new Number(42)], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42 + } + }] + } + }, + + 'parse(new Boolean(true))': { + call: 'parse', + args: [new Boolean(true)], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: true + } + }] + } + }, + + 'Syntax': { + property: 'Syntax', + result: { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + } + } + + }, + + 'Tolerant parse': { + 'return': { + type: 'Program', + body: [{ + type: 'ReturnStatement', + 'argument': null, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + }, + errors: [{ + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Illegal return statement' + }] + }, + + '(function () { \'use strict\'; with (i); }())': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [15, 27], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 27 } + } + }, + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'i', + range: [35, 36], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 36 } + } + }, + body: { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }, + range: [29, 38], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 38 } + } + }], + range: [13, 40], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 40 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 40], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 40 } + } + }, + 'arguments': [], + range: [1, 42], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 42 } + } + }, + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + } + }], + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + }, + errors: [{ + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Strict mode code may not include a with statement' + }] + }, + + '(function () { \'use strict\'; 021 }())': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [15, 27], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 27 } + } + }, + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 17, + raw: "021", + range: [29, 32], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 32 } + } + }, + range: [29, 33], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 33 } + } + }], + range: [13, 34], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 34], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 34 } + } + }, + 'arguments': [], + range: [1, 36], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + } + }], + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + }, + errors: [{ + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; delete x': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'delete', + argument: { + type: 'Identifier', + name: 'x', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + }, + errors: [{ + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Delete of an unqualified identifier in strict mode.' + }] + }, + + '"use strict"; try {} catch (eval) {}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'eval', + range: [28, 32], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 32 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [34, 36], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 36 } + } + }, + range: [21, 36], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 36 } + } + }], + finalizer: null, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; try {} catch (arguments) {}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'arguments', + range: [28, 37], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 37 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + range: [21, 41], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 41 } + } + }], + finalizer: null, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; var eval;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'eval', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + init: null, + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + }, + errors: [{ + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; var arguments;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'arguments', + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }, + init: null, + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }], + kind: 'var', + range: [14, 28], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 28 } + } + }], + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + }, + errors: [{ + index: 27, + lineNumber: 1, + column: 28, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; eval = 0;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'eval', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + }, + errors: [{ + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; eval++;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + prefix: false, + range: [14, 20], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 20 } + } + }, + range: [14, 21], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + errors: [{ + index: 18, + lineNumber: 1, + column: 19, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; --eval;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [16, 20], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 20 } + } + }, + prefix: true, + range: [14, 20], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 20 } + } + }, + range: [14, 21], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + errors: [{ + index: 20, + lineNumber: 1, + column: 21, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; arguments = 0;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'arguments', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [26, 27], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 27 } + } + }, + range: [14, 27], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 27 } + } + }, + range: [14, 28], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 28 } + } + }], + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + }, + errors: [{ + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; arguments--;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }, + prefix: false, + range: [14, 25], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 25 } + } + }, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }], + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; ++arguments;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, + prefix: true, + range: [14, 25], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 25 } + } + }, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }], + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + + '"use strict";x={y:1,y:1}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'y', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + kind: 'init', + range: [16, 19], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 19 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'y', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + kind: 'init', + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }], + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }], + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }] + }, + + '"use strict"; function eval() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [23, 27], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 27 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [30, 32], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 32], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 32 } + } + }, { + type: 'EmptyStatement', + range: [32, 33], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 33 } + } + }], + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; function arguments() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'arguments', + range: [23, 32], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [35, 37], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 37], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 37 } + } + }, { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }], + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; function interface() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'interface', + range: [23, 32], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [35, 37], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 37], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 37 } + } + }, { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }], + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }] + }, + + '"use strict"; (function eval() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'eval', + range: [24, 28], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 28 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [31, 33], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 33], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 33 } + } + }, + range: [14, 35], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 35 } + } + }], + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; (function arguments() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'arguments', + range: [24, 33], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 33 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 38], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 38 } + } + }, + range: [14, 40], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 40 } + } + }], + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 40 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; (function interface() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'interface', + range: [24, 33], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 33 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 38], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 38 } + } + }, + range: [14, 40], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 40 } + } + }], + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 40 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }] + }, + + '"use strict"; function f(eval) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'eval', + range: [25, 29], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 29 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [31, 33], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 33], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 33 } + } + }, { + type: 'EmptyStatement', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; function f(arguments) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'arguments', + range: [25, 34], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 34 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 38], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 38 } + } + }, { + type: 'EmptyStatement', + range: [38, 39], + loc: { + start: { line: 1, column: 38 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; function f(foo, foo) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'foo', + range: [25, 28], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 28 } + } + }, { + type: 'Identifier', + name: 'foo', + range: [31, 34], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 34 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 38], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 38 } + } + }, { + type: 'EmptyStatement', + range: [38, 39], + loc: { + start: { line: 1, column: 38 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + }, + errors: [{ + index: 31, + lineNumber: 1, + column: 32, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }] + }, + + '"use strict"; (function f(eval) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'eval', + range: [26, 30], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 30 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 34], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 34 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + + '"use strict"; (function f(arguments) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'arguments', + range: [26, 35], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 35 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [37, 39], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 39 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 39], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 39 } + } + }, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; (function f(foo, foo) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'foo', + range: [26, 29], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 29 } + } + }, { + type: 'Identifier', + name: 'foo', + range: [32, 35], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 35 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [37, 39], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 39 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 39], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 39 } + } + }, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }] + }, + + '"use strict"; x = { set f(eval) {} }' : { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + value : { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'eval', + range: [26, 30], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 30 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }], + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + 'function hello() { "octal directive\\1"; "use strict"; }': { + type: 'Program', + body: [{ + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'octal directive\u0001', + raw: '"octal directive\\1"', + range: [19, 38], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 38 } + } + }, + range: [19, 39], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 39 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [40, 52], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 52 } + } + }, + range: [40, 53], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 53 } + } + }], + range: [17, 55], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 55 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 55 } + } + }], + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 55 } + }, + errors: [{ + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"\\1"; \'use strict\';': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: '\u0001', + raw: '"\\1"', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [6, 18], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 18 } + } + }, + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + }, + errors: [{ + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; var x = { 014: 3}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 12, + raw: '014', + range: [24, 27], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 27 } + } + }, + value: { + type: 'Literal', + value: 3, + raw: '3', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + kind: 'init', + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }], + range: [22, 31], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 31 } + } + }, + range: [18, 31], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 31 } + } + }], + kind: 'var', + range: [14, 31], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 31 } + } + }], + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; var x = { get i() {}, get i() {} }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + kind: 'get', + range: [24, 34], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 34 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [40, 41], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 41 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [44, 46], + loc: { + start: { line: 1, column: 44 }, + end: { line: 1, column: 46 } + } + }, + rest: null, + generator: false, + expression: false, + range: [44, 46], + loc: { + start: { line: 1, column: 44 }, + end: { line: 1, column: 46 } + } + }, + kind: 'get', + range: [36, 46], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 46 } + } + }], + range: [22, 48], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 48 } + } + }, + range: [18, 48], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 48 } + } + }], + kind: 'var', + range: [14, 48], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 48 } + } + }], + range: [0, 48], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 48 } + }, + errors: [{ + index: 46, + lineNumber: 1, + column: 47, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }] + }, + + '"use strict"; var x = { i: 42, get i() {} }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + kind: 'init', + range: [24, 29], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 29 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [35, 36], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 36 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + rest: null, + generator: false, + expression: false, + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + kind: 'get', + range: [31, 41], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 41 } + } + }], + range: [22, 43], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 43 } + } + }, + range: [18, 43], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 43 } + } + }], + kind: 'var', + range: [14, 43], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 43 } + } + }], + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + }, + errors: [{ + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }] + }, + + '"use strict"; var x = { set i(x) {}, i: 42 }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'x', + range: [30, 31], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 31 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + rest: null, + generator: false, + expression: false, + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + kind: 'set', + range: [24, 35], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 35 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [40, 42], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 42 } + } + }, + kind: 'init', + range: [37, 42], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 42 } + } + }], + range: [22, 44], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 44 } + } + }, + range: [18, 44], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 44 } + } + }], + kind: 'var', + range: [14, 44], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 44 } + } + }], + range: [0, 44], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 44 } + }, + errors: [{ + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }] + + + } + + + } +}; + diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/package.json b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/package.json new file mode 100644 index 000000000..7d8856bd8 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/package.json @@ -0,0 +1,53 @@ +{ + "name": "astw", + "version": "0.0.0", + "description": "walk the ast with references to parent nodes", + "main": "index.js", + "dependencies": { + "esprima": "1.0.2" + }, + "devDependencies": { + "tape": "~0.2.2", + "tap": "~0.4.0", + "escodegen": "~0.0.17" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "chrome/20..latest", + "firefox/10..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/astw.git" + }, + "homepage": "https://github.com/substack/astw", + "keywords": [ + "ast", + "walk", + "source", + "esprima" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# astw\n\nwalk the ast\n\n[![browser support](http://ci.testling.com/substack/astw.png)](http://ci.testling.com/substack/astw)\n\n[![build status](https://secure.travis-ci.org/substack/astw.png)](http://travis-ci.org/substack/astw)\n\nThis module is a faster version of\n[falafel](https://github.com/substack/node-falafel)\nthat only does ast walking and `.parent` tracking, not source transforms.\n\n# example\n\n``` js\nvar astw = require('astw');\nvar deparse = require('escodegen').generate;\nvar walk = astw('4 + beep(5 * 2)');\n\nwalk(function (node) {\n var src = deparse(node);\n console.log(node.type + ' :: ' + JSON.stringify(src));\n});\n```\n\n# methods\n\n``` js\nvar astw = require('astw')\n```\n\n## var walk = astw(src)\n\nReturn a `walk()` function from the source string or ast object `src`.\n\n## walk(cb)\n\nWalk the nodes in the ast with `cb(node)` where `node` is each element in the\nast from [esprima](http://esprima.org/) but with an additional `.parent`\nreference to the parent node.\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install astw\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/astw/issues" + }, + "_id": "astw@0.0.0", + "_from": "astw@~0.0.0" +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/readme.markdown b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/readme.markdown new file mode 100644 index 000000000..807b5ad65 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/readme.markdown @@ -0,0 +1,52 @@ +# astw + +walk the ast + +[![browser support](http://ci.testling.com/substack/astw.png)](http://ci.testling.com/substack/astw) + +[![build status](https://secure.travis-ci.org/substack/astw.png)](http://travis-ci.org/substack/astw) + +This module is a faster version of +[falafel](https://github.com/substack/node-falafel) +that only does ast walking and `.parent` tracking, not source transforms. + +# example + +``` js +var astw = require('astw'); +var deparse = require('escodegen').generate; +var walk = astw('4 + beep(5 * 2)'); + +walk(function (node) { + var src = deparse(node); + console.log(node.type + ' :: ' + JSON.stringify(src)); +}); +``` + +# methods + +``` js +var astw = require('astw') +``` + +## var walk = astw(src) + +Return a `walk()` function from the source string or ast object `src`. + +## walk(cb) + +Walk the nodes in the ast with `cb(node)` where `node` is each element in the +ast from [esprima](http://esprima.org/) but with an additional `.parent` +reference to the parent node. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install astw +``` + +# license + +MIT diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/test/parent.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/test/parent.js new file mode 100644 index 000000000..a7403d30a --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/node_modules/astw/test/parent.js @@ -0,0 +1,25 @@ +var astw = require('../'); +var test = require('tape'); +var generate = require('escodegen').generate; + +function unparse (s) { + return generate(s, { format: { compact: true } }); +} + +test('parent', function (t) { + t.plan(4); + + var walk = astw('(' + function () { + var xs = [ 1, 2, 3 ]; + fn(ys); + } + ')()'); + + walk(function (node) { + if (node.type === 'ArrayExpression') { + t.equal(node.parent.type, 'VariableDeclarator'); + t.equal(unparse(node.parent), 'xs=[1,2,3]'); + t.equal(node.parent.parent.type, 'VariableDeclaration'); + t.equal(unparse(node.parent.parent), 'var xs=[1,2,3];'); + } + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/package.json b/node_modules/jade/node_modules/with/node_modules/lexical-scope/package.json new file mode 100644 index 000000000..2bcf13113 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/package.json @@ -0,0 +1,77 @@ +{ + "name": "lexical-scope", + "version": "0.0.12", + "description": "detect global and local lexical identifiers from javascript source code", + "main": "index.js", + "dependencies": { + "astw": "~0.0.0" + }, + "devDependencies": { + "tap": "~0.4.0", + "tape": "~0.2.2", + "browserify": "~2.10.2", + "brfs": "~0.0.3" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6", + "ie/7", + "ie/8", + "ie/9", + "ie/10", + "chrome/20", + "chrome/latest", + "firefox/10", + "firefox/15", + "firefox/latest", + "safari/latest", + "opera/11.0", + "opera/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/lexical-scope.git" + }, + "homepage": "https://github.com/substack/lexical-scope", + "keywords": [ + "ast", + "variable", + "name", + "lexical", + "local", + "global", + "implicit", + "exported" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "_id": "lexical-scope@0.0.12", + "dist": { + "shasum": "bd6ac00814445411d88a96307a42978c2d2fae80", + "tarball": "http://registry.npmjs.org/lexical-scope/-/lexical-scope-0.0.12.tgz" + }, + "_from": "lexical-scope@0.0.12", + "_npmVersion": "1.2.2", + "_npmUser": { + "name": "substack", + "email": "mail@substack.net" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "directories": {}, + "_shasum": "bd6ac00814445411d88a96307a42978c2d2fae80", + "_resolved": "https://registry.npmjs.org/lexical-scope/-/lexical-scope-0.0.12.tgz" +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/readme.markdown b/node_modules/jade/node_modules/with/node_modules/lexical-scope/readme.markdown new file mode 100644 index 000000000..258bdb868 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/readme.markdown @@ -0,0 +1,99 @@ +# lexical-scope + +detect global and local lexical identifiers from javascript source code + +[![browser support](http://ci.testling.com/substack/lexical-scope.png)](http://ci.testling.com/substack/lexical-scope) + +[![build status](https://secure.travis-ci.org/substack/lexical-scope.png)](http://travis-ci.org/substack/lexical-scope) + +# example + +``` js +var detect = require('lexical-scope'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/src.js'); + +var scope = detect(src); +console.dir(scope); +``` + +input: + +``` +var x = 5; +var y = 3, z = 2; + +w.foo(); +w = 2; + +RAWR=444; +RAWR.foo(); + +BLARG=3; + +foo(function () { + var BAR = 3; + process.nextTick(function (ZZZZZZZZZZZZ) { + console.log('beep boop'); + var xyz = 4; + x += 10; + x.zzzzzz; + ZZZ=6; + }); + function doom () { + } + ZZZ.foo(); + +}); + +console.log(xyz); +``` + +output: + +``` +$ node example/detect.js +{ locals: + { '': [ 'x', 'y', 'z' ], + 'body.7.arguments.0': [ 'BAR', 'doom' ], + 'body.7.arguments.0.body.1.arguments.0': [ 'xyz' ], + 'body.7.arguments.0.body.2': [] }, + globals: + { implicit: [ 'w', 'foo', 'process', 'console', 'xyz' ], + exported: [ 'w', 'RAWR', 'BLARG', 'ZZZ' ] } } +``` + +# live demo + +If you are using a modern browser, you can go to http://lexical-scope.forbeslindesay.co.uk/ for a live demo. + +# methods + +``` js +var detect = require('lexical-scope') +``` + +## var scope = detect(src) + +Return a `scope` structure from a javascript source string `src`. + +`scope.locals` maps scope name keys to an array of local variable names declared +with `var`. The key name `''` refers to the top-level scope. + +`scope.globals.implicit` contains the global variable names that are expected to +already exist in the environment by the script. + +`scope.globals.explicit` contains the global variable names that are exported by +the script. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install lexical-scope +``` + +# license + +MIT diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/argument.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/argument.js new file mode 100644 index 000000000..ddfd54941 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/argument.js @@ -0,0 +1,17 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/argument.js'); + +test('parameters from inline arguments', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, []); + t.same(scope.globals.exported, []); + t.same(scope.locals, { + 'body.0': [ 'a' ], + '': [ 'foo' ], + 'body.0.body.body.1.argument': [ 'c' ] + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/assign_implicit.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/assign_implicit.js new file mode 100644 index 000000000..cd8cb4b3f --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/assign_implicit.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/assign_implicit.js'); + +test('assign from an implicit global', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, [ 'bar' ]); + t.same(scope.globals.exported, []); + t.same(scope.locals, { '': [ 'foo' ] }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/detect.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/detect.js new file mode 100644 index 000000000..0230ad6d5 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/detect.js @@ -0,0 +1,17 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/detect.js'); + +test('check locals and globals', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, [ + 'w', 'foo', 'process', 'console', 'AAA', 'BBB', 'CCC', 'xyz' + ]); + t.same(scope.globals.exported, [ + 'w', 'RAWR', 'BLARG', 'ZZZ' + ]); + t.same(scope.locals[''], [ 'x', 'y', 'z', 'beep' ]); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/argument.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/argument.js new file mode 100644 index 000000000..55d20e392 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/argument.js @@ -0,0 +1,6 @@ +function foo () { + var a; + return function (c) { + a = c; + }; +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/assign_implicit.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/assign_implicit.js new file mode 100644 index 000000000..a731d1e8f --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/assign_implicit.js @@ -0,0 +1,2 @@ +var foo; +foo = bar; diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/detect.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/detect.js new file mode 100644 index 000000000..cb9c6f2a3 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/detect.js @@ -0,0 +1,32 @@ +var x = 5; +var y = 3, z = 2; + +w.foo(); +w = 2; + +RAWR=444; +RAWR.foo(); + +BLARG=3; + +foo(function () { + var BAR = 3; + process.nextTick(function (ZZZZZZZZZZZZ) { + console.log('beep boop'); + var xyz = 4; + x += 10; + x.zzzzzz; + ZZZ=6; + }); + function doom () { + if (AAA.aaa) {} + BBB.bbb = 3; + var z = 2 + CCC.x * 5; + } + ZZZ.foo(); + +}); + +function beep () {} + +console.log(xyz); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/multiple-exports.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/multiple-exports.js new file mode 100644 index 000000000..df549c127 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/multiple-exports.js @@ -0,0 +1,6 @@ +exports.foo = function () { + return bar; +}; +exports.bar = function (bar) { + return bar; +}; \ No newline at end of file diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/named_arg.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/named_arg.js new file mode 100644 index 000000000..af6c2752d --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/named_arg.js @@ -0,0 +1,6 @@ +function foo (x) { + var a = x; + return function (c) { + a += c; + }; +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/obj.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/obj.js new file mode 100644 index 000000000..1e6900e43 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/obj.js @@ -0,0 +1 @@ +module.exports = {foo: bar} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/return_hash.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/return_hash.js new file mode 100644 index 000000000..8cdd57b51 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/return_hash.js @@ -0,0 +1,5 @@ +function foo() { + return { + bar: true + } +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/right_hand.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/right_hand.js new file mode 100644 index 000000000..85dc112bf --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/files/right_hand.js @@ -0,0 +1,2 @@ +exports.filename = __filename; +exports.dirname = __dirname; diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/multiple-exports.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/multiple-exports.js new file mode 100644 index 000000000..990d0685f --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/multiple-exports.js @@ -0,0 +1,18 @@ + +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/multiple-exports.js'); + +test('multiple-exports', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit.sort(), ['bar', 'exports'].sort()); + t.same(scope.globals.exported, []); + t.same(scope.locals, { + '':[], + 'body.1.expression.right': ['bar'], + 'body.0.expression.right': [] + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/named_arg.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/named_arg.js new file mode 100644 index 000000000..421d711a0 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/named_arg.js @@ -0,0 +1,17 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/named_arg.js'); + +test('named argument parameter', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, []); + t.same(scope.globals.exported, []); + t.same(scope.locals, { + 'body.0': [ 'a', 'x' ], + '': [ 'foo' ], + 'body.0.body.body.1.argument': [ 'c' ] + }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/obj.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/obj.js new file mode 100644 index 000000000..64b8d5ecc --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/obj.js @@ -0,0 +1,16 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/obj.js'); + +test('globals on the right-hand of a colon in an object literal', function (t) { + t.plan(3); + + var scope = detect(src); + t.same( + scope.globals.implicit.sort(), + [ 'bar', 'module' ].sort() + ); + t.same(scope.globals.exported, []); + t.same(scope.locals, { '': [] }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/package.json b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/package.json new file mode 100644 index 000000000..10dcae1c1 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/package.json @@ -0,0 +1,5 @@ +{ + "name": "lexical-scope-test", + "version": "0.0.0", + "browserify": { "transform": "brfs" } +} diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/return_hash.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/return_hash.js new file mode 100644 index 000000000..442d91a90 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/return_hash.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/return_hash.js'); + +test('return hash', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, []); + t.same(scope.globals.exported, []); + t.same(scope.locals, { 'body.0': [], '': [ 'foo' ] }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/right_hand.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/right_hand.js new file mode 100644 index 000000000..28b283dd0 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/right_hand.js @@ -0,0 +1,16 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/files/right_hand.js'); + +test('globals on the right-hand of assignment', function (t) { + t.plan(3); + + var scope = detect(src); + t.same( + scope.globals.implicit.sort(), + [ 'exports', '__dirname', '__filename' ].sort() + ); + t.same(scope.globals.exported, []); + t.same(scope.locals, { '': [] }); +}); diff --git a/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/shebang.js b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/shebang.js new file mode 100644 index 000000000..544558059 --- /dev/null +++ b/node_modules/jade/node_modules/with/node_modules/lexical-scope/test/shebang.js @@ -0,0 +1,19 @@ +var test = require('tape'); +var detect = require('../'); +var fs = require('fs'); +var src = '#!/beep/boop blah\n' + + fs.readFileSync(__dirname + '/files/detect.js') +; + +test('shebangs', function (t) { + t.plan(3); + + var scope = detect(src); + t.same(scope.globals.implicit, [ + 'w', 'foo', 'process', 'console', 'AAA', 'BBB', 'CCC', 'xyz' + ]); + t.same(scope.globals.exported, [ + 'w', 'RAWR', 'BLARG', 'ZZZ' + ]); + t.same(scope.locals[''], [ 'x', 'y', 'z', 'beep' ]); +}); diff --git a/node_modules/jade/node_modules/with/package.json b/node_modules/jade/node_modules/with/package.json new file mode 100644 index 000000000..1bae5c679 --- /dev/null +++ b/node_modules/jade/node_modules/with/package.json @@ -0,0 +1,43 @@ +{ + "name": "with", + "version": "1.0.4", + "description": "Compile time `with` for strict mode JavaScript", + "main": "index.js", + "scripts": { + "test": "mocha -R spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/ForbesLindesay/with.git" + }, + "author": { + "name": "ForbesLindesay" + }, + "license": "MIT", + "dependencies": { + "lexical-scope": "0.0.12" + }, + "devDependencies": { + "mocha": "~1.9.0" + }, + "_id": "with@1.0.4", + "dist": { + "shasum": "67b70e967742b915b1934507628151194e34daeb", + "tarball": "http://registry.npmjs.org/with/-/with-1.0.4.tgz" + }, + "_from": "with@1.0.4", + "_npmVersion": "1.2.10", + "_npmUser": { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + }, + "maintainers": [ + { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + } + ], + "directories": {}, + "_shasum": "67b70e967742b915b1934507628151194e34daeb", + "_resolved": "https://registry.npmjs.org/with/-/with-1.0.4.tgz" +} diff --git a/node_modules/jade/node_modules/with/test/index.js b/node_modules/jade/node_modules/with/test/index.js new file mode 100644 index 000000000..3bfc6ca1c --- /dev/null +++ b/node_modules/jade/node_modules/with/test/index.js @@ -0,0 +1,107 @@ +var assert = require('assert') + +var addWith = require('../') + +var sentinel = {} +var sentinel2 = {} +describe('addWith("obj", "console.log(a)")', function () { + it('adds the necessary variable declarations', function (done) { + var src = addWith('obj', 'console.log(a)') + // var a = obj.a;console.log(a) + Function('console,obj', src)( + { + log: function (a) { + assert(a === sentinel) + done() + } + }, + {a: sentinel}) + }) +}) +describe('addWith("obj || {}", "console.log(a)")', function () { + it('adds the necessary variable declarations', function (done) { + var src = addWith('obj || {}', 'console.log(a)') + // var locals = (obj || {}),a = locals.a;console.log(a) + var expected = 2 + Function('console,obj', src)( + { + log: function (a) { + assert(a === sentinel) + if (0 === --expected) done() + } + }, + {a: sentinel}) + Function('console,obj', src)( + { + log: function (a) { + assert(a === undefined) + if (0 === --expected) done() + } + }) + }) +}) +describe('addWith("obj", "console.log(helper(a))", ["helper"])', function () { + it('adds the necessary variable declarations', function (done) { + var src = addWith('obj', 'console.log(helper(a))', ['helper']) + // var a = obj.a;console.log(helper(a)) + Function('console,obj,helper', src)( + { + log: function (a) { + assert(a === sentinel) + done() + } + }, + {a: sentinel2}, + function (a) { + assert(a === sentinel2) + return sentinel + }) + }) +}) +describe('addWith("obj || {}", "console.log(locals(a))", ["locals_"])', function () { + it('adds the necessary variable declarations', function (done) { + var src = addWith('obj || {}', 'console.log(locals(a))', ['locals_']) + // var locals__ = (obj || {}),locals = locals__.locals,a = locals__.a;console.log(locals(a)) + Function('console,obj', src)( + { + log: function (a) { + assert(a === sentinel) + done() + } + }, + { + a: sentinel2, + locals: function (a) { + assert(a === sentinel2) + return sentinel + } + }) + }) +}) + +describe('addWith("obj || {}", "console.log(\'foo\')")', function () { + it('passes through', function (done) { + var src = addWith('obj || {}', 'console.log("foo")') + // console.log(\'foo\') + Function('console,obj', src)( + { + log: function (a) { + assert(a === 'foo') + done() + } + }) + }) +}) + +describe('addWith("obj || {}", "obj.foo")', function () { + it('passes through', function (done) { + var src = addWith('obj || {}', 'obj.bar = obj.foo') + // obj.bar = obj.foo + var obj = { + foo: 'ding' + } + Function('obj', src)(obj) + assert(obj.bar === 'ding') + done() + }) +}) \ No newline at end of file diff --git a/node_modules/jade/package.json b/node_modules/jade/package.json new file mode 100644 index 000000000..591f939a3 --- /dev/null +++ b/node_modules/jade/package.json @@ -0,0 +1,64 @@ +{ + "name": "jade", + "description": "Jade template engine", + "version": "0.31.2", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/jade" + }, + "main": "./index.js", + "bin": { + "jade": "./bin/jade" + }, + "man": [ + "./jade.1" + ], + "dependencies": { + "commander": "1.1.1", + "mkdirp": "0.3.x", + "transformers": "2.0.1", + "character-parser": "1.0.2", + "monocle": "0.1.48", + "with": "1.0.4" + }, + "devDependencies": { + "coffee-script": "*", + "mocha": "*", + "markdown": "*", + "stylus": "*", + "uubench": "*", + "should": "*", + "less": "*", + "uglify-js": "*", + "browserify": "*", + "win-spawn": "*" + }, + "component": { + "scripts": { + "jade": "runtime.js" + } + }, + "scripts": { + "test": "mocha -R spec", + "prepublish": "npm prune && cd bin && win-line-endings && cd ..", + "build": "npm run compile", + "compile": "npm run compile-full && npm run compile-runtime", + "compile-full": "browserify ./lib/jade.js --standalone jade -x ./node_modules/transformers > jade.js", + "compile-runtime": "browserify ./lib/runtime.js --standalone jade > runtime.js" + }, + "browser": { + "./lib/filters.js": "./lib/filters-client.js" + }, + "readme": "# Jade - template engine \r\n[![Build Status](https://secure.travis-ci.org/visionmedia/jade.png)](http://travis-ci.org/visionmedia/jade)\r\n[![Dependency Status](https://gemnasium.com/visionmedia/jade.png)](https://gemnasium.com/visionmedia/jade)\r\n[![NPM version](https://badge.fury.io/js/jade.png)](http://badge.fury.io/js/jade)\r\n\r\n Jade is a high performance template engine heavily influenced by [Haml](http://haml-lang.com)\r\n and implemented with JavaScript for [node](http://nodejs.org). For discussion join the [Google Group](http://groups.google.com/group/jadejs).\r\n\r\n## Announcement\r\n\r\nJade version 0.31.0 deprecated implicit text only support for scripts and styles. To fix this all you need to do is add a `.` character after the script or style tag.\r\n\r\nIt is hoped that this change will make Jade easier for newcomers to learn without affecting the power of the language or leading to excessive verboseness.\r\n\r\nIf you have a lot of Jade files that need fixing you can use [fix-jade](https://github.com/ForbesLindesay/fix-jade) to attempt to automate the process.\r\n\r\n## Test drive\r\n\r\n You can test drive Jade online [here](http://naltatis.github.com/jade-syntax-docs).\r\n\r\n## README Contents\r\n\r\n- [Features](#a1)\r\n- [Implementations](#a2)\r\n- [Installation](#a3)\r\n- [Browser Support](#a4)\r\n- [Public API](#a5)\r\n- [Syntax](#a6)\r\n - [Line Endings](#a6-1)\r\n - [Tags](#a6-2)\r\n - [Tag Text](#a6-3)\r\n - [Comments](#a6-4)\r\n - [Block Comments](#a6-5)\r\n - [Nesting](#a6-6)\r\n - [Block Expansion](#a6-7)\r\n - [Case](#a6-8)\r\n - [Attributes](#a6-9)\r\n - [HTML](#a6-10)\r\n - [Doctypes](#a6-11)\r\n- [Filters](#a7)\r\n- [Code](#a8)\r\n- [Iteration](#a9)\r\n- [Conditionals](#a10)\r\n- [Template inheritance](#a11)\r\n- [Block append / prepend](#a12)\r\n- [Includes](#a13)\r\n- [Mixins](#a14)\r\n- [Generated Output](#a15)\r\n- [Example Makefile](#a16)\r\n- [jade(1)](#a17)\r\n- [Tutorials](#a18)\r\n- [License](#a19)\r\n\r\n\r\n## Features\r\n\r\n - client-side support\r\n - great readability\r\n - flexible indentation\r\n - block-expansion\r\n - mixins\r\n - static includes\r\n - attribute interpolation\r\n - code is escaped by default for security\r\n - contextual error reporting at compile & run time\r\n - executable for compiling jade templates via the command line\r\n - html 5 mode (the default doctype)\r\n - optional memory caching\r\n - combine dynamic and static tag classes\r\n - parse tree manipulation via _filters_\r\n - template inheritance\r\n - block append / prepend\r\n - supports [Express JS](http://expressjs.com) out of the box\r\n - transparent iteration over objects, arrays, and even non-enumerables via `each`\r\n - block comments\r\n - no tag prefix\r\n - filters\r\n - :stylus must have [stylus](http://github.com/LearnBoost/stylus) installed\r\n - :less must have [less.js](http://github.com/cloudhead/less.js) installed\r\n - :markdown must have [markdown-js](http://github.com/evilstreak/markdown-js), [node-discount](http://github.com/visionmedia/node-discount), or [marked](http://github.com/chjj/marked) installed\r\n - :cdata\r\n - :coffeescript must have [coffee-script](http://jashkenas.github.com/coffee-script/) installed\r\n - [Emacs Mode](https://github.com/brianc/jade-mode)\r\n - [Vim Syntax](https://github.com/digitaltoad/vim-jade)\r\n - [TextMate Bundle](http://github.com/miksago/jade-tmbundle)\r\n - [Coda/SubEtha syntax Mode](https://github.com/aaronmccall/jade.mode)\r\n - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs)\r\n - [html2jade](https://github.com/donpark/html2jade) converter\r\n\r\n\r\n## Implementations\r\n\r\n - [php](http://github.com/everzet/jade.php)\r\n - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html)\r\n - [ruby](https://github.com/slim-template/slim)\r\n - [python](https://github.com/SyrusAkbary/pyjade)\r\n - [java](https://github.com/neuland/jade4j)\r\n\r\n\r\n## Installation\r\n\r\nvia npm:\r\n\r\n```bash\r\n$ npm install jade\r\n```\r\n\r\n\r\n## Browser Support\r\n\r\n To compile jade to a single file compatible for client-side use simply execute:\r\n\r\n```bash\r\n$ make jade.js\r\n```\r\n\r\n Alternatively, if uglifyjs is installed via npm (`npm install uglify-js`) you may execute the following which will create both files. However each release builds these for you.\r\n\r\n```bash\r\n$ make jade.min.js\r\n```\r\n\r\n By default Jade instruments templates with line number statements such as `__.lineno = 3` for debugging purposes. When used in a browser it's useful to minimize this boiler plate, you can do so by passing the option `{ compileDebug: false }`. The following template\r\n\r\n```jade\r\np Hello #{name}\r\n```\r\n\r\n Can then be as small as the following generated function:\r\n\r\n```js\r\nfunction anonymous(locals, attrs, escape, rethrow) {\r\n var buf = [];\r\n with (locals || {}) {\r\n var interp;\r\n buf.push('\\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\\n

    ');\r\n }\r\n return buf.join(\"\");\r\n}\r\n```\r\n\r\n Through the use of Jade's `./runtime.js` you may utilize these pre-compiled templates on the client-side _without_ Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as `jade.attrs`, `jade.escape` etc. To enable this you should pass `{ client: true }` to `jade.compile()` to tell Jade to reference the helper functions\r\n via `jade.attrs`, `jade.escape` etc.\r\n\r\n```js\r\nfunction anonymous(locals, attrs, escape, rethrow) {\r\n var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\r\n var buf = [];\r\n with (locals || {}) {\r\n var interp;\r\n buf.push('\\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\\n

    ');\r\n }\r\n return buf.join(\"\");\r\n}\r\n```\r\n\r\n
    \r\n## Public API\r\n\r\n```js\r\nvar jade = require('jade');\r\n\r\n// Compile a function\r\nvar fn = jade.compile('string of jade', options);\r\nfn(locals);\r\n```\r\n\r\n### Options\r\n\r\n - `self` Use a `self` namespace to hold the locals _(false by default)_\r\n - `locals` Local variable object\r\n - `filename` Used in exceptions, and required when using includes\r\n - `debug` Outputs tokens and function body generated\r\n - `compiler` Compiler to replace jade's default\r\n - `compileDebug` When `false` no debug instrumentation is compiled\r\n - `pretty` Add pretty-indentation whitespace to output _(false by default)_\r\n\r\n\r\n## Syntax\r\n\r\n\r\n### Line Endings\r\n\r\n**CRLF** and **CR** are converted to **LF** before parsing.\r\n\r\n\r\n### Tags\r\n\r\nA tag is simply a leading word:\r\n\r\n```jade\r\nhtml\r\n```\r\n\r\nfor example is converted to ``\r\n\r\ntags can also have ids:\r\n\r\n```jade\r\ndiv#container\r\n```\r\n\r\nwhich would render `
    `\r\n\r\nhow about some classes?\r\n\r\n```jade\r\ndiv.user-details\r\n```\r\n\r\nrenders `
    `\r\n\r\nmultiple classes? _and_ an id? sure:\r\n\r\n```jade\r\ndiv#foo.bar.baz\r\n```\r\n\r\nrenders `
    `\r\n\r\ndiv div div sure is annoying, how about:\r\n\r\n```jade\r\n#foo\r\n.bar\r\n```\r\n\r\nwhich is syntactic sugar for what we have already been doing, and outputs:\r\n\r\n```html\r\n
    \r\n```\r\n\r\n
    \r\n### Tag Text\r\n\r\nSimply place some content after the tag:\r\n\r\n```jade\r\np wahoo!\r\n```\r\n\r\nrenders `

    wahoo!

    `.\r\n\r\nwell cool, but how about large bodies of text:\r\n\r\n```jade\r\np\r\n | foo bar baz\r\n | rawr rawr\r\n | super cool\r\n | go jade go\r\n```\r\n\r\nrenders `

    foo bar baz rawr.....

    `\r\n\r\ninterpolation? yup! both types of text can utilize interpolation,\r\nif we passed `{ name: 'tj', email: 'tj@vision-media.ca' }` to the compiled function we can do the following:\r\n\r\n```jade\r\n#user #{name} <#{email}>\r\n```\r\n\r\noutputs `
    tj <tj@vision-media.ca>
    `\r\n\r\nActually want `#{}` for some reason? escape it!\r\n\r\n```jade\r\np \\#{something}\r\n```\r\n\r\nnow we have `

    #{something}

    `\r\n\r\nWe can also utilize the unescaped variant `!{html}`, so the following\r\nwill result in a literal script tag:\r\n\r\n```jade\r\n- var html = \"\"\r\n| !{html}\r\n```\r\n\r\nNested tags that also contain text can optionally use a text block:\r\n\r\n```jade\r\nlabel\r\n | Username:\r\n input(name='user[name]')\r\n```\r\n\r\nor immediate tag text:\r\n\r\n```jade\r\nlabel Username:\r\n input(name='user[name]')\r\n```\r\n\r\nAs an alternative, we may use a trailing `.` to indicate a text block, for example:\r\n\r\n```jade\r\np.\r\n foo asdf\r\n asdf\r\n asdfasdfaf\r\n asdf\r\n asd.\r\n```\r\n\r\noutputs:\r\n\r\n```html\r\n

    foo asdf\r\nasdf\r\n asdfasdfaf\r\n asdf\r\nasd.\r\n

    \r\n```\r\n\r\nThis however differs from a trailing `.` followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal:\r\n\r\n```jade\r\np .\r\n```\r\n\r\noutputs:\r\n\r\n```html\r\n

    .

    \r\n```\r\n\r\nIt should be noted that text blocks should be doubled escaped. For example if you desire the following output.\r\n\r\n```html\r\n

    foo\\bar

    \r\n```\r\n\r\nuse:\r\n\r\n```jade\r\np.\r\n foo\\\\bar\r\n```\r\n\r\n
    \r\n### Comments\r\n\r\nSingle line comments currently look the same as JavaScript comments,\r\naka `//` and must be placed on their own line:\r\n\r\n```jade\r\n// just some paragraphs\r\np foo\r\np bar\r\n```\r\n\r\nwould output\r\n\r\n```html\r\n\r\n

    foo

    \r\n

    bar

    \r\n```\r\n\r\nJade also supports unbuffered comments, by simply adding a hyphen:\r\n\r\n```jade\r\n//- will not output within markup\r\np foo\r\np bar\r\n```\r\n\r\noutputting\r\n\r\n```html\r\n

    foo

    \r\n

    bar

    \r\n```\r\n\r\n
    \r\n### Block Comments\r\n\r\n A block comment is legal as well:\r\n\r\n```jade\r\nbody\r\n //\r\n #content\r\n h1 Example\r\n```\r\n\r\noutputting\r\n\r\n```html\r\n\r\n \r\n\r\n```\r\n\r\nJade supports conditional-comments as well, for example:\r\n\r\n```jade\r\nhead\r\n //if lt IE 8\r\n script(src='/ie-sucks.js')\r\n```\r\n\r\noutputs:\r\n\r\n```html\r\n\r\n \r\n\r\n```\r\n\r\n\r\n### Nesting\r\n\r\n Jade supports nesting to define the tags in a natural way:\r\n\r\n```jade\r\nul\r\n li.first\r\n a(href='#') foo\r\n li\r\n a(href='#') bar\r\n li.last\r\n a(href='#') baz\r\n```\r\n\r\n\r\n### Block Expansion\r\n\r\n Block expansion allows you to create terse single-line nested tags,\r\n the following example is equivalent to the nesting example above.\r\n\r\n```jade\r\nul\r\n li.first: a(href='#') foo\r\n li: a(href='#') bar\r\n li.last: a(href='#') baz\r\n```\r\n\r\n\r\n### Case\r\n\r\n The case statement takes the following form:\r\n\r\n```jade\r\nhtml\r\n body\r\n friends = 10\r\n case friends\r\n when 0\r\n p you have no friends\r\n when 1\r\n p you have a friend\r\n default\r\n p you have #{friends} friends\r\n```\r\n\r\n Block expansion may also be used:\r\n\r\n```jade\r\nfriends = 5\r\n\r\nhtml\r\n body\r\n case friends\r\n when 0: p you have no friends\r\n when 1: p you have a friend\r\n default: p you have #{friends} friends\r\n```\r\n\r\n\r\n### Attributes\r\n\r\nJade currently supports `(` and `)` as attribute delimiters.\r\n\r\n```jade\r\na(href='/login', title='View login page') Login\r\n```\r\n\r\nWhen a value is `undefined` or `null` the attribute is _not_ added,\r\nso this is fine, it will not compile `something=\"null\"`.\r\n\r\n```jade\r\ndiv(something=null)\r\n```\r\n\r\nBoolean attributes are also supported:\r\n\r\n```jade\r\ninput(type=\"checkbox\", checked)\r\n```\r\n\r\nBoolean attributes with code will only output the attribute when `true`:\r\n\r\n```jade\r\ninput(type=\"checkbox\", checked=someValue)\r\n```\r\n\r\nMultiple lines work too:\r\n\r\n```jade\r\ninput(type='checkbox',\r\n name='agreement',\r\n checked)\r\n```\r\n\r\nMultiple lines without the comma work fine:\r\n\r\n```jade\r\ninput(type='checkbox'\r\n name='agreement'\r\n checked)\r\n```\r\n\r\nFunky whitespace? fine:\r\n\r\n```jade\r\ninput(\r\n type='checkbox'\r\n name='agreement'\r\n checked)\r\n```\r\n\r\nColons work:\r\n\r\n```jade\r\nrss(xmlns:atom=\"atom\")\r\n```\r\n\r\nSuppose we have the `user` local `{ id: 12, name: 'tobi' }`\r\nand we wish to create an anchor tag with `href` pointing to \"/user/12\"\r\nwe could use regular javascript concatenation:\r\n\r\n```jade\r\na(href='/user/' + user.id)= user.name\r\n```\r\n\r\nor we could use jade's interpolation, which I added because everyone\r\nusing Ruby or CoffeeScript seems to think this is legal js..:\r\n\r\n```jade\r\na(href='/user/#{user.id}')= user.name\r\n```\r\n\r\nThe `class` attribute is special-cased when an array is given,\r\nallowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly:\r\n\r\n```jade\r\nbody(class=bodyClasses)\r\n```\r\n\r\n\r\n### HTML\r\n\r\n Inline html is fine, we can use the pipe syntax to\r\n write arbitrary text, in this case some html:\r\n\r\n```jade\r\nhtml\r\n body\r\n |

    Title

    \r\n |

    foo bar baz

    \r\n```\r\n\r\n Or we can use the trailing `.` to indicate to Jade that we\r\n only want text in this block, allowing us to omit the pipes:\r\n\r\n```jade\r\nhtml\r\n body.\r\n

    Title

    \r\n

    foo bar baz

    \r\n```\r\n\r\n Both of these examples yield the same result:\r\n\r\n```html\r\n

    Title

    \r\n

    foo bar baz

    \r\n\r\n```\r\n\r\n The same rule applies for anywhere you can have text\r\n in jade, raw html is fine:\r\n\r\n```jade\r\nhtml\r\n body\r\n h1 User #{name}\r\n```\r\n\r\n
    \r\n### Doctypes\r\n\r\nTo add a doctype simply use `!!!`, or `doctype` followed by an optional value:\r\n\r\n```jade\r\n!!!\r\n```\r\n\r\nor\r\n\r\n```jade\r\ndoctype\r\n```\r\n\r\nWill output the _html 5_ doctype, however:\r\n\r\n```jade\r\n!!! transitional\r\n```\r\n\r\nWill output the _transitional_ doctype.\r\n\r\nDoctypes are case-insensitive, so the following are equivalent:\r\n\r\n```jade\r\ndoctype Basic\r\ndoctype basic\r\n```\r\n\r\nit's also possible to simply pass a doctype literal:\r\n\r\n```jade\r\ndoctype html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\"\r\n```\r\n\r\nyielding:\r\n\r\n```html\r\n\r\n```\r\n\r\nBelow are the doctypes defined by default, which can easily be extended:\r\n\r\n```js\r\nvar doctypes = exports.doctypes = {\r\n '5': '',\r\n 'default': '',\r\n 'xml': '',\r\n 'transitional': '',\r\n 'strict': '',\r\n 'frameset': '',\r\n '1.1': '',\r\n 'basic': '',\r\n 'mobile': ''\r\n};\r\n```\r\n\r\nTo alter the default simply change:\r\n\r\n```js\r\njade.doctypes.default = 'whatever you want';\r\n```\r\n\r\n\r\n## Filters\r\n\r\nFilters are prefixed with `:`, for example `:markdown` and\r\npass the following block of text to an arbitrary function for processing. View the _features_\r\nat the top of this document for available filters.\r\n\r\n```jade\r\nbody\r\n :markdown\r\n Woah! jade _and_ markdown, very **cool**\r\n we can even link to [stuff](http://google.com)\r\n```\r\n\r\nRenders:\r\n\r\n```html\r\n

    Woah! jade and markdown, very cool we can even link to stuff

    \r\n```\r\n\r\n\r\n## Code\r\n\r\nJade currently supports three classifications of executable code. The first\r\nis prefixed by `-`, and is not buffered:\r\n\r\n```jade\r\n- var foo = 'bar';\r\n```\r\n\r\nThis can be used for conditionals, or iteration:\r\n\r\n```jade\r\n- for (var key in obj)\r\n p= obj[key]\r\n```\r\n\r\nDue to Jade's buffering techniques the following is valid as well:\r\n\r\n```jade\r\n- if (foo)\r\n ul\r\n li yay\r\n li foo\r\n li worked\r\n- else\r\n p oh no! didnt work\r\n```\r\n\r\nHell, even verbose iteration:\r\n\r\n```jade\r\n- if (items.length)\r\n ul\r\n - items.forEach(function(item){\r\n li= item\r\n - })\r\n```\r\n\r\nAnything you want!\r\n\r\nNext up we have _escaped_ buffered code, which is used to\r\nbuffer a return value, which is prefixed by `=`:\r\n\r\n```jade\r\n- var foo = 'bar'\r\n= foo\r\nh1= foo\r\n```\r\n\r\nWhich outputs `bar

    bar

    `. Code buffered by `=` is escaped\r\nby default for security, however to output unescaped return values\r\nyou may use `!=`:\r\n\r\n```jade\r\np!= aVarContainingMoreHTML\r\n```\r\n\r\n Jade also has designer-friendly variants, making the literal JavaScript\r\n more expressive and declarative. For example the following assignments\r\n are equivalent, and the expression is still regular javascript:\r\n\r\n```jade\r\n- var foo = 'foo ' + 'bar'\r\nfoo = 'foo ' + 'bar'\r\n```\r\n\r\n Likewise Jade has first-class `if`, `else if`, `else`, `until`, `while`, `unless` among others, however you must remember that the expressions are still regular javascript:\r\n\r\n```jade\r\nif foo == 'bar'\r\n ul\r\n li yay\r\n li foo\r\n li worked\r\nelse\r\n p oh no! didnt work\r\n```\r\n\r\n
    \r\n## Iteration\r\n\r\n Along with vanilla JavaScript Jade also supports a subset of\r\n constructs that allow you to create more designer-friendly templates,\r\n one of these constructs is `each`, taking the form:\r\n\r\n```jade\r\neach VAL[, KEY] in OBJ\r\n```\r\n\r\nAn example iterating over an array:\r\n\r\n```jade\r\n- var items = [\"one\", \"two\", \"three\"]\r\neach item in items\r\n li= item\r\n```\r\n\r\noutputs:\r\n\r\n```html\r\n
  • one
  • \r\n
  • two
  • \r\n
  • three
  • \r\n```\r\n\r\niterating an array with index:\r\n\r\n```jade\r\nitems = [\"one\", \"two\", \"three\"]\r\neach item, i in items\r\n li #{item}: #{i}\r\n```\r\n\r\noutputs:\r\n\r\n```html\r\n
  • one: 0
  • \r\n
  • two: 1
  • \r\n
  • three: 2
  • \r\n```\r\n\r\niterating an object's keys and values:\r\n\r\n```jade\r\nobj = { foo: 'bar' }\r\neach val, key in obj\r\n li #{key}: #{val}\r\n```\r\n\r\nwould output `
  • foo: bar
  • `\r\n\r\nInternally Jade converts these statements to regular\r\nJavaScript loops such as `users.forEach(function(user){`,\r\nso lexical scope and nesting applies as it would with regular\r\nJavaScript:\r\n\r\n```jade\r\neach user in users\r\n each role in user.roles\r\n li= role\r\n```\r\n\r\n You may also use `for` if you prefer:\r\n\r\n```jade\r\nfor user in users\r\n for role in user.roles\r\n li= role\r\n```\r\n\r\n
    \r\n## Conditionals\r\n\r\n Jade conditionals are equivalent to those using the code (`-`) prefix,\r\n however allow you to ditch parenthesis to become more designer friendly,\r\n however keep in mind the expression given is _regular_ JavaScript:\r\n\r\n```jade\r\nfor user in users\r\n if user.role == 'admin'\r\n p #{user.name} is an admin\r\n else\r\n p= user.name\r\n```\r\n\r\n is equivalent to the following using vanilla JavaScript literals:\r\n\r\n```jade\r\nfor user in users\r\n - if (user.role == 'admin')\r\n p #{user.name} is an admin\r\n - else\r\n p= user.name\r\n```\r\n\r\n Jade also provides `unless` which is equivalent to `if (!(expr))`:\r\n\r\n```jade\r\nfor user in users\r\n unless user.isAnonymous\r\n p\r\n | Click to view\r\n a(href='/users/' + user.id)= user.name\r\n```\r\n\r\n\r\n## Template inheritance\r\n\r\n Jade supports template inheritance via the `block` and `extends` keywords. A block is simply a \"block\" of Jade that may be replaced within a child template, this process is recursive. To activate template inheritance in Express 2.x you must add: `app.set('view options', { layout: false });`.\r\n\r\n Jade blocks can provide default content if desired, however optional as shown below by `block scripts`, `block content`, and `block foot`.\r\n\r\n```jade\r\nhtml\r\n head\r\n h1 My Site - #{title}\r\n block scripts\r\n script(src='/jquery.js')\r\n body\r\n block content\r\n block foot\r\n #footer\r\n p some footer content\r\n```\r\n\r\n Now to extend the layout, simply create a new file and use the `extends` directive as shown below, giving the path (with or without the .jade extension). You may now define one or more blocks that will override the parent block content, note that here the `foot` block is _not_ redefined and will output \"some footer content\".\r\n\r\n```jade\r\nextends layout\r\n\r\nblock scripts\r\n script(src='/jquery.js')\r\n script(src='/pets.js')\r\n\r\nblock content\r\n h1= title\r\n each pet in pets\r\n include pet\r\n```\r\n\r\n It's also possible to override a block to provide additional blocks, as shown in the following example where `content` now exposes a `sidebar` and `primary` block for overriding, or the child template could override `content` all together.\r\n\r\n```jade\r\nextends regular-layout\r\n\r\nblock content\r\n .sidebar\r\n block sidebar\r\n p nothing\r\n .primary\r\n block primary\r\n p nothing\r\n```\r\n\r\n\r\n## Block append / prepend\r\n\r\n Jade allows you to _replace_ (default), _prepend_, or _append_ blocks. Suppose for example you have default scripts in a \"head\" block that you wish to utilize on _every_ page, you might do this:\r\n\r\n```jade\r\nhtml\r\n head\r\n block head\r\n script(src='/vendor/jquery.js')\r\n script(src='/vendor/caustic.js')\r\n body\r\n block content\r\n```\r\n\r\n Now suppose you have a page of your application for a JavaScript game, you want some game related scripts as well as these defaults, you can simply `append` the block:\r\n\r\n```jade\r\nextends layout\r\n\r\nblock append head\r\n script(src='/vendor/three.js')\r\n script(src='/game.js')\r\n```\r\n\r\n When using `block append` or `block prepend` the `block` is optional:\r\n\r\n```jade\r\nextends layout\r\n\r\nappend head\r\n script(src='/vendor/three.js')\r\n script(src='/game.js')\r\n```\r\n\r\n\r\n## Includes\r\n\r\n Includes allow you to statically include chunks of Jade,\r\n or other content like css, or html which lives in separate files. The classical example is including a header and footer. Suppose we have the following directory structure:\r\n\r\n ./layout.jade\r\n ./includes/\r\n ./head.jade\r\n ./foot.jade\r\n\r\nand the following _layout.jade_:\r\n\r\n```jade\r\nhtml\r\n include includes/head\r\n body\r\n h1 My Site\r\n p Welcome to my super amazing site.\r\n include includes/foot\r\n```\r\n\r\nboth includes _includes/head_ and _includes/foot_ are\r\nread relative to the `filename` option given to _layout.jade_,\r\nwhich should be an absolute path to this file, however Express\r\ndoes this for you. Include then parses these files, and injects\r\nthe AST produced to render what you would expect:\r\n\r\n```html\r\n\r\n \r\n My Site\r\n \r\n \r\n \r\n

    My Site

    \r\n

    Welcome to my super lame site.

    \r\n
    \r\n

    Copyright>(c) foobar

    \r\n
    \r\n \r\n\r\n```\r\n\r\nAs mentioned `include` can be used to include other content\r\nsuch as html or css. By providing an extension, Jade will\r\nread that file in, apply any [filter](#a7) matching the file's\r\nextension, and insert that content into the output.\r\n\r\n```jade\r\nhtml\r\n head\r\n //- css and js have simple filters that wrap them in\r\n + + + + + + diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/test/test.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/test/test.js new file mode 100644 index 000000000..246922561 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/test/test.js @@ -0,0 +1,228 @@ +if (!this.uuid) { + // node.js + uuid = require('../uuid'); +} + +// +// x-platform log/assert shims +// + +function _log(msg, type) { + type = type || 'log'; + + if (typeof(document) != 'undefined') { + document.write('
    ' + msg.replace(/\n/g, '
    ') + '
    '); + } + if (typeof(console) != 'undefined') { + var color = { + log: '\033[39m', + warn: '\033[33m', + error: '\033[31m' + }; + console[type](color[type] + msg + color.log); + } +} + +function log(msg) {_log(msg, 'log');} +function warn(msg) {_log(msg, 'warn');} +function error(msg) {_log(msg, 'error');} + +function assert(res, msg) { + if (!res) { + error('FAIL: ' + msg); + } else { + log('Pass: ' + msg); + } +} + +// +// Unit tests +// + +// Verify ordering of v1 ids created with explicit times +var TIME = 1321644961388; // 2011-11-18 11:36:01.388-08:00 + +function compare(name, ids) { + ids = ids.map(function(id) { + return id.split('-').reverse().join('-'); + }).sort(); + var sorted = ([].concat(ids)).sort(); + + assert(sorted.toString() == ids.toString(), name + ' have expected order'); +} + +// Verify ordering of v1 ids created using default behavior +compare('uuids with current time', [ + uuid.v1(), + uuid.v1(), + uuid.v1(), + uuid.v1(), + uuid.v1() +]); + +// Verify ordering of v1 ids created with explicit times +compare('uuids with time option', [ + uuid.v1({msecs: TIME - 10*3600*1000}), + uuid.v1({msecs: TIME - 1}), + uuid.v1({msecs: TIME}), + uuid.v1({msecs: TIME + 1}), + uuid.v1({msecs: TIME + 28*24*3600*1000}) +]); + +assert( + uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}), + 'IDs created at same msec are different' +); + +// Verify throw if too many ids created +var thrown = false; +try { + uuid.v1({msecs: TIME, nsecs: 10000}); +} catch (e) { + thrown = true; +} +assert(thrown, 'Exception thrown when > 10K ids created in 1 ms'); + +// Verify clock regression bumps clockseq +var uidt = uuid.v1({msecs: TIME}); +var uidtb = uuid.v1({msecs: TIME - 1}); +assert( + parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1, + 'Clock regression by msec increments the clockseq' +); + +// Verify clock regression bumps clockseq +var uidtn = uuid.v1({msecs: TIME, nsecs: 10}); +var uidtnb = uuid.v1({msecs: TIME, nsecs: 9}); +assert( + parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1, + 'Clock regression by nsec increments the clockseq' +); + +// Verify explicit options produce expected id +var id = uuid.v1({ + msecs: 1321651533573, + nsecs: 5432, + clockseq: 0x385c, + node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ] +}); +assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id'); + +// Verify adjacent ids across a msec boundary are 1 time unit apart +var u0 = uuid.v1({msecs: TIME, nsecs: 9999}); +var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0}); + +var before = u0.split('-')[0], after = u1.split('-')[0]; +var dt = parseInt(after, 16) - parseInt(before, 16); +assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart'); + +// +// Test parse/unparse +// + +id = '00112233445566778899aabbccddeeff'; +assert(uuid.unparse(uuid.parse(id.substr(0,10))) == + '00112233-4400-0000-0000-000000000000', 'Short parse'); +assert(uuid.unparse(uuid.parse('(this is the uuid -> ' + id + id)) == + '00112233-4455-6677-8899-aabbccddeeff', 'Dirty parse'); + +// +// Perf tests +// + +var generators = { + v1: uuid.v1, + v4: uuid.v4 +}; + +var UUID_FORMAT = { + v1: /[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i, + v4: /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i +}; + +var N = 1e4; + +// Get %'age an actual value differs from the ideal value +function divergence(actual, ideal) { + return Math.round(100*100*(actual - ideal)/ideal)/100; +} + +function rate(msg, t) { + log(msg + ': ' + (N / (Date.now() - t) * 1e3 | 0) + ' uuids\/second'); +} + +for (var version in generators) { + var counts = {}, max = 0; + var generator = generators[version]; + var format = UUID_FORMAT[version]; + + log('\nSanity check ' + N + ' ' + version + ' uuids'); + for (var i = 0, ok = 0; i < N; i++) { + id = generator(); + if (!format.test(id)) { + throw Error(id + ' is not a valid UUID string'); + } + + if (id != uuid.unparse(uuid.parse(id))) { + assert(fail, id + ' is not a valid id'); + } + + // Count digits for our randomness check + if (version == 'v4') { + var digits = id.replace(/-/g, '').split(''); + for (var j = digits.length-1; j >= 0; j--) { + var c = digits[j]; + max = Math.max(max, counts[c] = (counts[c] || 0) + 1); + } + } + } + + // Check randomness for v4 UUIDs + if (version == 'v4') { + // Limit that we get worried about randomness. (Purely empirical choice, this!) + var limit = 2*100*Math.sqrt(1/N); + + log('\nChecking v4 randomness. Distribution of Hex Digits (% deviation from ideal)'); + + for (var i = 0; i < 16; i++) { + var c = i.toString(16); + var bar = '', n = counts[c], p = Math.round(n/max*100|0); + + // 1-3,5-8, and D-F: 1:16 odds over 30 digits + var ideal = N*30/16; + if (i == 4) { + // 4: 1:1 odds on 1 digit, plus 1:16 odds on 30 digits + ideal = N*(1 + 30/16); + } else if (i >= 8 && i <= 11) { + // 8-B: 1:4 odds on 1 digit, plus 1:16 odds on 30 digits + ideal = N*(1/4 + 30/16); + } else { + // Otherwise: 1:16 odds on 30 digits + ideal = N*30/16; + } + var d = divergence(n, ideal); + + // Draw bar using UTF squares (just for grins) + var s = n/max*50 | 0; + while (s--) bar += '='; + + assert(Math.abs(d) < limit, c + ' |' + bar + '| ' + counts[c] + ' (' + d + '% < ' + limit + '%)'); + } + } +} + +// Perf tests +for (var version in generators) { + log('\nPerformance testing ' + version + ' UUIDs'); + var generator = generators[version]; + var buf = new uuid.BufferClass(16); + + for (var i = 0, t = Date.now(); i < N; i++) generator(); + rate('uuid.' + version + '()', t); + + for (var i = 0, t = Date.now(); i < N; i++) generator('binary'); + rate('uuid.' + version + '(\'binary\')', t); + + for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf); + rate('uuid.' + version + '(\'binary\', buffer)', t); +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/uuid.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/uuid.js new file mode 100644 index 000000000..2fac6dc4b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/node-uuid/uuid.js @@ -0,0 +1,245 @@ +// uuid.js +// +// Copyright (c) 2010-2012 Robert Kieffer +// MIT License - http://opensource.org/licenses/mit-license.php + +(function() { + var _global = this; + + // Unique ID creation requires a high quality random # generator. We feature + // detect to determine the best RNG source, normalizing to a function that + // returns 128-bits of randomness, since that's what's usually required + var _rng; + + // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html + // + // Moderately fast, high quality + if (typeof(require) == 'function') { + try { + var _rb = require('crypto').randomBytes; + _rng = _rb && function() {return _rb(16);}; + } catch(e) {} + } + + if (!_rng && _global.crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + _rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } + + if (!_rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + _rng = function() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return _rnds; + }; + } + + // Buffer class to use + var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array; + + // Maps for number <-> hex string conversion + var _byteToHex = []; + var _hexToByte = {}; + for (var i = 0; i < 256; i++) { + _byteToHex[i] = (i + 0x100).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; + } + + // **`parse()` - Parse a UUID into it's component bytes** + function parse(s, buf, offset) { + var i = (buf && offset) || 0, ii = 0; + + buf = buf || []; + s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { + if (ii < 16) { // Don't overflow! + buf[i + ii++] = _hexToByte[oct]; + } + }); + + // Zero out remaining bytes if string was short + while (ii < 16) { + buf[i + ii++] = 0; + } + + return buf; + } + + // **`unparse()` - Convert UUID byte array (ala parse()) into a string** + function unparse(buf, offset) { + var i = offset || 0, bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; + } + + // **`v1()` - Generate time-based UUID** + // + // Inspired by https://github.com/LiosK/UUID.js + // and http://docs.python.org/library/uuid.html + + // random #'s we need to init node and clockseq + var _seedBytes = _rng(); + + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + var _nodeId = [ + _seedBytes[0] | 0x01, + _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] + ]; + + // Per 4.2.2, randomize (14 bit) clockseq + var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; + + // Previous uuid creation time + var _lastMSecs = 0, _lastNSecs = 0; + + // See https://github.com/broofa/node-uuid for API details + function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + + var clockseq = options.clockseq != null ? options.clockseq : _clockseq; + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs != null ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq == null) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; n++) { + b[i + n] = node[n]; + } + + return buf ? buf : unparse(b); + } + + // **`v4()` - Generate random UUID** + + // See https://github.com/broofa/node-uuid for API details + function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options == 'binary' ? new BufferClass(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || _rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ii++) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || unparse(rnds); + } + + // Export public API + var uuid = v4; + uuid.v1 = v1; + uuid.v4 = v4; + uuid.parse = parse; + uuid.unparse = unparse; + uuid.BufferClass = BufferClass; + + if (typeof define === 'function' && define.amd) { + // Publish as AMD module + define(function() {return uuid;}); + } else if (typeof(module) != 'undefined' && module.exports) { + // Publish as node.js module + module.exports = uuid; + } else { + // Publish as global (in browsers) + var _previousRoot = _global.uuid; + + // **`noConflict()` - (browser only) to reset global 'uuid' var** + uuid.noConflict = function() { + _global.uuid = _previousRoot; + return uuid; + }; + + _global.uuid = uuid; + } +}).call(this); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/LICENSE b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/LICENSE new file mode 100644 index 000000000..a4a9aee0c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/README.md new file mode 100644 index 000000000..34c4a85d2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/README.md @@ -0,0 +1,4 @@ +oauth-sign +========== + +OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module. diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/index.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/index.js new file mode 100644 index 000000000..e35bfa670 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/index.js @@ -0,0 +1,43 @@ +var crypto = require('crypto') + , qs = require('querystring') + ; + +function sha1 (key, body) { + return crypto.createHmac('sha1', key).update(body).digest('base64') +} + +function rfc3986 (str) { + return encodeURIComponent(str) + .replace(/!/g,'%21') + .replace(/\*/g,'%2A') + .replace(/\(/g,'%28') + .replace(/\)/g,'%29') + .replace(/'/g,'%27') + ; +} + +function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { + // adapted from https://dev.twitter.com/docs/auth/oauth and + // https://dev.twitter.com/docs/auth/creating-signature + + var querystring = Object.keys(params).sort().map(function(key){ + // big WTF here with the escape + encoding but it's what twitter wants + return escape(rfc3986(key)) + "%3D" + escape(rfc3986(params[key])) + }).join('%26') + + var base = [ + httpMethod ? httpMethod.toUpperCase() : 'GET', + rfc3986(base_uri), + querystring + ].join('&') + + var key = [ + consumer_secret, + token_secret || '' + ].map(rfc3986).join('&') + + return sha1(key, base) +} + +exports.hmacsign = hmacsign +exports.rfc3986 = rfc3986 diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/package.json new file mode 100644 index 000000000..dc99a4ec7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/package.json @@ -0,0 +1,31 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "oauth-sign", + "description": "OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module.", + "version": "0.3.0", + "repository": { + "url": "https://github.com/mikeal/oauth-sign" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "scripts": { + "test": "node test.js" + }, + "readme": "oauth-sign\n==========\n\nOAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module. \n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mikeal/oauth-sign/issues" + }, + "homepage": "https://github.com/mikeal/oauth-sign", + "_id": "oauth-sign@0.3.0", + "_from": "oauth-sign@~0.3.0" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/test.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/test.js new file mode 100644 index 000000000..46955ff69 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/oauth-sign/test.js @@ -0,0 +1,49 @@ +var hmacsign = require('./index').hmacsign + , assert = require('assert') + , qs = require('querystring') + ; + +// Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth + +var reqsign = hmacsign('POST', 'https://api.twitter.com/oauth/request_token', + { oauth_callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11' + , oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' + , oauth_nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk' + , oauth_signature_method: 'HMAC-SHA1' + , oauth_timestamp: '1272323042' + , oauth_version: '1.0' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") + +console.log(reqsign) +console.log('8wUi7m5HFQy76nowoCThusfgB+Q=') +assert.equal(reqsign, '8wUi7m5HFQy76nowoCThusfgB+Q=') + +var accsign = hmacsign('POST', 'https://api.twitter.com/oauth/access_token', + { oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' + , oauth_nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8' + , oauth_signature_method: 'HMAC-SHA1' + , oauth_token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc' + , oauth_timestamp: '1272323047' + , oauth_verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY' + , oauth_version: '1.0' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") + +console.log(accsign) +console.log('PUw/dHA4fnlJYM6RhXk5IU/0fCc=') +assert.equal(accsign, 'PUw/dHA4fnlJYM6RhXk5IU/0fCc=') + +var upsign = hmacsign('POST', 'http://api.twitter.com/1/statuses/update.json', + { oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" + , oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" + , oauth_signature_method: "HMAC-SHA1" + , oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" + , oauth_timestamp: "1272325550" + , oauth_version: "1.0" + , status: 'setting up my twitter 私のさえずりを設定する' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") + +console.log(upsign) +console.log('yOahq5m0YjDDjfjxHaXEsW9D+X0=') +assert.equal(upsign, 'yOahq5m0YjDDjfjxHaXEsW9D+X0=') + + diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintignore b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintrc b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintrc new file mode 100644 index 000000000..997b3f7d4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.jshintrc @@ -0,0 +1,10 @@ +{ + "node": true, + + "curly": true, + "latedef": true, + "quotmark": true, + "undef": true, + "unused": true, + "trailing": true +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.npmignore b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.npmignore new file mode 100644 index 000000000..7e1574dc5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.travis.yml b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.travis.yml new file mode 100644 index 000000000..c891dd0e0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/.travis.yml @@ -0,0 +1,4 @@ +language: node_js + +node_js: + - 0.10 \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/LICENSE b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/LICENSE new file mode 100644 index 000000000..d4569487a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/Makefile b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/Makefile new file mode 100644 index 000000000..600a700ec --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/Makefile @@ -0,0 +1,8 @@ +test: + @node node_modules/lab/bin/lab +test-cov: + @node node_modules/lab/bin/lab -t 100 +test-cov-html: + @node node_modules/lab/bin/lab -r html -o coverage.html + +.PHONY: test test-cov test-cov-html \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/README.md new file mode 100644 index 000000000..f86ffc9b1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/README.md @@ -0,0 +1,120 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was original created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Objects + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, depth)`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', 1); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +### Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/index.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/index.js new file mode 100644 index 000000000..bb0a047c4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/index.js @@ -0,0 +1 @@ +module.exports = require('./lib'); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/index.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/index.js new file mode 100644 index 000000000..0e094933d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/parse.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/parse.js new file mode 100644 index 000000000..fdd2a01bf --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/parse.js @@ -0,0 +1,151 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + depth: 5, + arrayLimit: 20, + parametersLimit: 1000 +}; + + +internals.parseValues = function (str) { + + var obj = {}; + var parts = str.split('&').slice(0, internals.parametersLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!obj[key]) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj = {}; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val)); + } + else { + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + if (!isNaN(index) && + root !== cleanRoot && + index <= internals.arrayLimit) { + + obj = []; + obj[index] = internals.parseObject(chain, val); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, depth) { + + if (!key) { + return; + } + + depth = typeof depth === 'undefined' ? internals.depth : depth; + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Don't allow them to overwrite object prototype properties + + if (Object.prototype.hasOwnProperty(segment[1])) { + return; + } + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < depth) { + + ++i; + if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + keys.push(segment[1]); + } + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val); +}; + + +module.exports = function (str, depth) { + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str) : Utils.clone(str); + var obj = {}; + + // Iterate over the keys and setup the new object + + for (var key in tempObj) { + if (tempObj.hasOwnProperty(key)) { + var newObj = internals.parseKeys(key, tempObj[key], depth); + obj = Utils.merge(obj, newObj); + } + } + + return Utils.compact(obj); +}; + + diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/stringify.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/stringify.js new file mode 100644 index 000000000..3bf14085f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/stringify.js @@ -0,0 +1,52 @@ +// Load modules + + +// Declare internals + +var internals = {}; + + +internals.stringify = function (obj, prefix) { + + if (Buffer.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [prefix + '=' + encodeURIComponent(obj)]; + } + + if (obj === null) { + return [prefix]; + } + + var values = []; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + values = values.concat(internals.stringify(obj[key], prefix + '[' + encodeURIComponent(key) + ']')); + } + } + + return values; +}; + + +module.exports = function (obj) { + + var keys = []; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys = keys.concat(internals.stringify(obj[key], encodeURIComponent(key))); + } + } + + return keys.join('&'); +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/utils.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/utils.js new file mode 100644 index 000000000..b5ffa6bf6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/lib/utils.js @@ -0,0 +1,131 @@ +// Load modules + + +// Declare internals + +var internals = {}; + + +exports.arrayToObject = function (source) { + + var obj = {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (source[i] !== undefined && + source[i] !== null) { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.clone = function (source) { + + if (typeof source !== 'object' || + source === null) { + + return source; + } + + if (Buffer.isBuffer(source)) { + return source.toString(); + } + + var obj = Array.isArray(source) ? [] : {}; + for (var i in source) { + if (source.hasOwnProperty(i)) { + obj[i] = exports.clone(source[i]); + } + } + + return obj; +}; + + +exports.merge = function (target, source) { + + if (!source) { + return target; + } + + var obj = exports.clone(target); + + if (Array.isArray(source)) { + for (var i = 0, il = source.length; i < il; ++i) { + if (source[i] !== undefined) { + obj[i] = source[i]; + } + } + + return obj; + } + + if (Array.isArray(obj)) { + obj = exports.arrayToObject(obj); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (value && + typeof value === 'object') { + + if (!obj[key]) { + obj[key] = exports.clone(value); + } + else { + obj[key] = exports.merge(obj[key], value); + } + } + else { + obj[key] = value; + } + } + + return obj; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + + +exports.compact = function (obj) { + + if (typeof obj !== 'object') { + return obj; + } + + var compacted = {}; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + if (Array.isArray(obj[key])) { + compacted[key] = []; + + for (var i = 0, l = obj[key].length; i < l; i++) { + if (obj[key].hasOwnProperty(i) && + obj[key][i]) { + + compacted[key].push(obj[key][i]); + } + } + } + else { + compacted[key] = exports.compact(obj[key]); + } + } + } + + return compacted; +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/package.json new file mode 100644 index 000000000..852611486 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/package.json @@ -0,0 +1,41 @@ +{ + "name": "qs", + "version": "1.0.2", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "lab": "3.x.x" + }, + "scripts": { + "test": "make test-cov" + }, + "repository": { + "type": "git", + "url": "https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "author": { + "name": "Nathan LaFreniere", + "email": "quitlahok@gmail.com" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/hapijs/qs/raw/master/LICENSE" + } + ], + "readme": "# qs\n\nA querystring parsing and stringifying library with some added security.\n\n[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs)\n\nLead Maintainer: [Nathan LaFreniere](https://github.com/nlf)\n\nThe **qs** module was original created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).\n\n## Usage\n\n```javascript\nvar Qs = require('qs');\n\nvar obj = Qs.parse('a=c'); // { a: 'c' }\nvar str = Qs.stringify(obj); // 'a=c'\n```\n\n### Objects\n\n**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.\nFor example, the string `'foo[bar]=baz'` converts to:\n\n```javascript\n{\n foo: {\n bar: 'baz'\n }\n}\n```\n\nYou can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:\n\n```javascript\n{\n foo: {\n bar: {\n baz: 'foobarbaz'\n }\n }\n}\n```\n\nBy default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like\n`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:\n\n```javascript\n{\n a: {\n b: {\n c: {\n d: {\n e: {\n f: {\n '[g][h][i]': 'j'\n }\n }\n }\n }\n }\n }\n}\n```\n\nThis depth can be overridden by passing a `depth` option to `Qs.parse(string, depth)`:\n\n```javascript\nQs.parse('a[b][c][d][e][f][g][h][i]=j', 1);\n// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }\n```\n\nThe depth limit mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number.\n\n### Arrays\n\n**qs** can also parse arrays using a similar `[]` notation:\n\n```javascript\nQs.parse('a[]=b&a[]=c');\n// { a: ['b', 'c'] }\n```\n\nYou may specify an index as well:\n\n```javascript\nQs.parse('a[1]=c&a[0]=b');\n// { a: ['b', 'c'] }\n```\n\nNote that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number\nto create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving\ntheir order:\n\n```javascript\nQs.parse('a[1]=b&a[15]=c');\n// { a: ['b', 'c'] }\n```\n\n**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will\ninstead be converted to an object with the index as the key:\n\n```javascript\nQs.parse('a[100]=b');\n// { a: { '100': 'b' } }\n```\n\nIf you mix notations, **qs** will merge the two items into an object:\n\n```javascript\nQs.parse('a[0]=b&a[b]=c');\n// { a: { '0': 'b', b: 'c' } }\n```\n\nYou can also create arrays of objects:\n\n```javascript\nQs.parse('a[][b]=c');\n// { a: [{ b: 'c' }] }\n```", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@1.0.2", + "_shasum": "50a93e2b5af6691c31bcea5dae78ee6ea1903768", + "_from": "qs@~1.0.0", + "_resolved": "https://registry.npmjs.org/qs/-/qs-1.0.2.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/parse.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/parse.js new file mode 100644 index 000000000..8999c8f0e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/parse.js @@ -0,0 +1,236 @@ +// Load modules + +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var expect = Lab.expect; +var before = Lab.before; +var after = Lab.after; +var describe = Lab.experiment; +var it = Lab.test; + + +describe('#parse', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', 1)).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', 1)).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot override prototypes', function (done) { + + var obj = Qs.parse('toString=bad&bad[toString]=bad&constructor=bad'); + expect(typeof obj.toString).to.equal('function'); + expect(typeof obj.bad.toString).to.equal('function'); + expect(typeof obj.constructor).to.equal('function'); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('should compact sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers to strings', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b.toString() }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + expect(Qs.parse.bind(null, 'test')).to.not.throw(); + delete Object.prototype.crash; + done(); + }); +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/stringify.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/stringify.js new file mode 100644 index 000000000..1e5666825 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/qs/test/stringify.js @@ -0,0 +1,123 @@ +// Load modules + +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var expect = Lab.expect; +var before = Lab.before; +var after = Lab.after; +var describe = Lab.experiment; +var it = Lab.test; + + +describe('#stringify', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a[b]=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a[b][c][d]=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a[0]=b&a[1]=c&a[2]=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a[b][0]=c&a[b][1]=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a[0][b]=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a[0][b][c][0]=1'); + done(); + }); + + it('stringifies a complicated object', function (done) { + + expect(Qs.stringify({ a: { b: 'c', d: 'e' } })).to.equal('a[b]=c&a[d]=e'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null })).to.equal('a'); + expect(Qs.stringify({ a: { b: null } })).to.equal('a[b]'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + expect(Qs.stringify({ a: { b: undefined, c: null } })).to.equal('a[c]'); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': 'q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b'})).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a[b]=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a[b]=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b[c]=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a[b]=test'); + done(); + }); +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.npmignore b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.npmignore new file mode 100644 index 000000000..7dccd9707 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.travis.yml b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.travis.yml new file mode 100644 index 000000000..f1d0f13c8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/LICENSE.txt b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/LICENSE.txt new file mode 100644 index 000000000..eac188156 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/LICENSE.txt @@ -0,0 +1,4 @@ +Copyright 2012 Michael Hart (michael.hart.au@gmail.com) + +This project is free software released under the MIT license: +http://www.opensource.org/licenses/mit-license.php diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/README.md new file mode 100644 index 000000000..32fc98255 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/README.md @@ -0,0 +1,38 @@ +# Decode streams into strings The Right Way(tm) + +```javascript +var fs = require('fs') +var zlib = require('zlib') +var strs = require('stringstream') + +var utf8Stream = fs.createReadStream('massiveLogFile.gz') + .pipe(zlib.createGunzip()) + .pipe(strs('utf8')) +``` + +No need to deal with `setEncoding()` weirdness, just compose streams +like they were supposed to be! + +Handles input and output encoding: + +```javascript +// Stream from utf8 to hex to base64... Why not, ay. +var hex64Stream = fs.createReadStream('myFile') + .pipe(strs('utf8', 'hex')) + .pipe(strs('hex', 'base64')) +``` + +Also deals with `base64` output correctly by aligning each emitted data +chunk so that there are no dangling `=` characters: + +```javascript +var stream = fs.createReadStream('myFile').pipe(strs('base64')) + +var base64Str = '' + +stream.on('data', function(data) { base64Str += data }) +stream.on('end', function() { + console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding() + console.log('Original file is: ' + new Buffer(base64Str, 'base64')) +}) +``` diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/example.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/example.js new file mode 100644 index 000000000..f82b85edc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/example.js @@ -0,0 +1,27 @@ +var fs = require('fs') +var zlib = require('zlib') +var strs = require('stringstream') + +var utf8Stream = fs.createReadStream('massiveLogFile.gz') + .pipe(zlib.createGunzip()) + .pipe(strs('utf8')) + +utf8Stream.pipe(process.stdout) + +// Stream from utf8 to hex to base64... Why not, ay. +var hex64Stream = fs.createReadStream('myFile') + .pipe(strs('utf8', 'hex')) + .pipe(strs('hex', 'base64')) + +hex64Stream.pipe(process.stdout) + +// Deals with base64 correctly by aligning chunks +var stream = fs.createReadStream('myFile').pipe(strs('base64')) + +var base64Str = '' + +stream.on('data', function(data) { base64Str += data }) +stream.on('end', function() { + console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding() + console.log('Original file is: ' + new Buffer(base64Str, 'base64')) +}) diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/package.json new file mode 100644 index 000000000..fe4e16bf6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/package.json @@ -0,0 +1,32 @@ +{ + "name": "stringstream", + "version": "0.0.4", + "description": "Encode and decode streams into string streams", + "author": { + "name": "Michael Hart", + "email": "michael.hart.au@gmail.com", + "url": "http://github.com/mhart" + }, + "main": "stringstream.js", + "keywords": [ + "string", + "stream", + "base64", + "gzip" + ], + "repository": { + "type": "git", + "url": "https://github.com/mhart/StringStream.git" + }, + "license": "MIT", + "readme": "# Decode streams into strings The Right Way(tm)\n\n```javascript\nvar fs = require('fs')\nvar zlib = require('zlib')\nvar strs = require('stringstream')\n\nvar utf8Stream = fs.createReadStream('massiveLogFile.gz')\n .pipe(zlib.createGunzip())\n .pipe(strs('utf8'))\n```\n\nNo need to deal with `setEncoding()` weirdness, just compose streams\nlike they were supposed to be!\n\nHandles input and output encoding:\n\n```javascript\n// Stream from utf8 to hex to base64... Why not, ay.\nvar hex64Stream = fs.createReadStream('myFile')\n .pipe(strs('utf8', 'hex'))\n .pipe(strs('hex', 'base64'))\n```\n\nAlso deals with `base64` output correctly by aligning each emitted data\nchunk so that there are no dangling `=` characters:\n\n```javascript\nvar stream = fs.createReadStream('myFile').pipe(strs('base64'))\n\nvar base64Str = ''\n\nstream.on('data', function(data) { base64Str += data })\nstream.on('end', function() {\n console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding()\n console.log('Original file is: ' + new Buffer(base64Str, 'base64'))\n})\n```\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mhart/StringStream/issues" + }, + "homepage": "https://github.com/mhart/StringStream", + "_id": "stringstream@0.0.4", + "_shasum": "0f0e3423f942960b5692ac324a57dd093bc41a92", + "_from": "stringstream@~0.0.4", + "_resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.4.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/stringstream.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/stringstream.js new file mode 100644 index 000000000..4ece1275f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/stringstream/stringstream.js @@ -0,0 +1,102 @@ +var util = require('util') +var Stream = require('stream') +var StringDecoder = require('string_decoder').StringDecoder + +module.exports = StringStream +module.exports.AlignedStringDecoder = AlignedStringDecoder + +function StringStream(from, to) { + if (!(this instanceof StringStream)) return new StringStream(from, to) + + Stream.call(this) + + if (from == null) from = 'utf8' + + this.readable = this.writable = true + this.paused = false + this.toEncoding = (to == null ? from : to) + this.fromEncoding = (to == null ? '' : from) + this.decoder = new AlignedStringDecoder(this.toEncoding) +} +util.inherits(StringStream, Stream) + +StringStream.prototype.write = function(data) { + if (!this.writable) { + var err = new Error('stream not writable') + err.code = 'EPIPE' + this.emit('error', err) + return false + } + if (this.fromEncoding) { + if (Buffer.isBuffer(data)) data = data.toString() + data = new Buffer(data, this.fromEncoding) + } + var string = this.decoder.write(data) + if (string.length) this.emit('data', string) + return !this.paused +} + +StringStream.prototype.flush = function() { + if (this.decoder.flush) { + var string = this.decoder.flush() + if (string.length) this.emit('data', string) + } +} + +StringStream.prototype.end = function() { + if (!this.writable && !this.readable) return + this.flush() + this.emit('end') + this.writable = this.readable = false + this.destroy() +} + +StringStream.prototype.destroy = function() { + this.decoder = null + this.writable = this.readable = false + this.emit('close') +} + +StringStream.prototype.pause = function() { + this.paused = true +} + +StringStream.prototype.resume = function () { + if (this.paused) this.emit('drain') + this.paused = false +} + +function AlignedStringDecoder(encoding) { + StringDecoder.call(this, encoding) + + switch (this.encoding) { + case 'base64': + this.write = alignedWrite + this.alignedBuffer = new Buffer(3) + this.alignedBytes = 0 + break + } +} +util.inherits(AlignedStringDecoder, StringDecoder) + +AlignedStringDecoder.prototype.flush = function() { + if (!this.alignedBuffer || !this.alignedBytes) return '' + var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes) + this.alignedBytes = 0 + return leftover +} + +function alignedWrite(buffer) { + var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length + if (!rem && !this.alignedBytes) return buffer.toString(this.encoding) + + var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem) + + this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes) + buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem) + + buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length) + this.alignedBytes = rem + + return returnBuffer.toString(this.encoding) +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.jshintrc b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.jshintrc new file mode 100644 index 000000000..fb11913a4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.jshintrc @@ -0,0 +1,70 @@ +{ + "passfail" : false, + "maxerr" : 100, + + "browser" : false, + "node" : true, + "rhino" : false, + "couch" : false, + "wsh" : false, + + "jquery" : false, + "prototypejs" : false, + "mootools" : false, + "dojo" : false, + + "debug" : false, + "devel" : false, + + "esnext" : true, + "strict" : true, + "globalstrict" : true, + + "asi" : false, + "laxbreak" : false, + "bitwise" : true, + "boss" : false, + "curly" : true, + "eqeqeq" : false, + "eqnull" : true, + "evil" : false, + "expr" : false, + "forin" : false, + "immed" : true, + "lastsemic" : true, + "latedef" : false, + "loopfunc" : false, + "noarg" : true, + "regexp" : false, + "regexdash" : false, + "scripturl" : false, + "shadow" : false, + "supernew" : false, + "undef" : true, + "unused" : true, + + "newcap" : true, + "noempty" : true, + "nonew" : true, + "nomen" : false, + "onevar" : false, + "onecase" : true, + "plusplus" : false, + "proto" : false, + "sub" : true, + "trailing" : true, + "white" : false, + + "predef": [ + "describe", + "it", + "before", + "beforeEach", + "after", + "afterEach", + "expect", + "setTimeout", + "clearTimeout" + ], + "maxlen": 0 +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.npmignore b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.npmignore new file mode 100644 index 000000000..54efff98f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.npmignore @@ -0,0 +1,3 @@ +node_modules/ +.*.sw[nmop] +npm-debug.log diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.travis.yml b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.travis.yml new file mode 100644 index 000000000..5d892654f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: +- "0.10" +- "0.11" +matrix: + fast_finish: true + allow_failures: + - node_js: 0.11 diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/LICENSE b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/LICENSE new file mode 100644 index 000000000..3fac4c85c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/LICENSE @@ -0,0 +1,78 @@ +Copyright GoInstant, Inc. and other contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +The following exceptions apply: + +=== + +`pubSufTest()` of generate-pubsuffix.js is in the public domain. + + // Any copyright is dedicated to the Public Domain. + // http://creativecommons.org/publicdomain/zero/1.0/ + +=== + +`public-suffix.txt` was obtained from + +via . + +That file contains the usual Mozilla triple-license, for which this project uses it +under the terms of the MPL 1.1: + + // ***** BEGIN LICENSE BLOCK ***** + // Version: MPL 1.1/GPL 2.0/LGPL 2.1 + // + // The contents of this file are subject to the Mozilla Public License Version + // 1.1 (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // http://www.mozilla.org/MPL/ + // + // Software distributed under the License is distributed on an "AS IS" basis, + // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + // for the specific language governing rights and limitations under the + // License. + // + // The Original Code is the Public Suffix List. + // + // The Initial Developer of the Original Code is + // Jo Hermans . + // Portions created by the Initial Developer are Copyright (C) 2007 + // the Initial Developer. All Rights Reserved. + // + // Contributor(s): + // Ruben Arakelyan + // Gervase Markham + // Pamela Greene + // David Triendl + // Jothan Frakes + // The kind representatives of many TLD registries + // + // Alternatively, the contents of this file may be used under the terms of + // either the GNU General Public License Version 2 or later (the "GPL"), or + // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + // in which case the provisions of the GPL or the LGPL are applicable instead + // of those above. If you wish to allow use of your version of this file only + // under the terms of either the GPL or the LGPL, and not to allow others to + // use your version of this file under the terms of the MPL, indicate your + // decision by deleting the provisions above and replace them with the notice + // and other provisions required by the GPL or the LGPL. If you do not delete + // the provisions above, a recipient may use your version of this file under + // the terms of any one of the MPL, the GPL or the LGPL. + // + // ***** END LICENSE BLOCK ***** diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/README.md new file mode 100644 index 000000000..9e6caee18 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/README.md @@ -0,0 +1,412 @@ +[RFC6265](http://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js + +![Tough Cookie](http://www.goinstant.com.s3.amazonaws.com/tough-cookie.jpg) + +[![Build Status](https://travis-ci.org/goinstant/node-cookie.png?branch=master)](https://travis-ci.org/goinstant/node-cookie) + +[![NPM Stats](https://nodei.co/npm/tough-cookie.png?downloads=true&stars=true)](https://npmjs.org/package/tough-cookie) +![NPM Downloads](https://nodei.co/npm-dl/tough-cookie.png?months=9) + +# Synopsis + +``` javascript +var tough = require('tough-cookie'); // note: not 'cookie', 'cookies' or 'node-cookie' +var Cookie = tough.Cookie; +var cookie = Cookie.parse(header); +cookie.value = 'somethingdifferent'; +header = cookie.toString(); + +var cookiejar = new tough.CookieJar(); +cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); +// ... +cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { + res.headers['cookie'] = cookies.join('; '); +}); +``` + +# Installation + +It's _so_ easy! + +`npm install tough-cookie` + +Requires `punycode`, which should get installed automatically for you. Note that node.js v0.6.2+ bundles punycode by default. + +Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. + +# API + +tough +===== + +Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". + +parseDate(string[,strict]) +----------------- + +Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. If strict is set to true then leading/trailing non-seperator characters around the time part will cause the parsing to fail (e.g. "Thu, 01 Jan 1970 00:00:010 GMT" has an extra trailing zero but Chrome, an assumedly RFC-compliant browser, treats this as valid). + +formatDate(date) +---------------- + +Format a Date into a RFC1123 string (the RFC6265-recommended format). + +canonicalDomain(str) +-------------------- + +Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). + +domainMatch(str,domStr[,canonicalize=true]) +------------------------------------------- + +Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". + +The `canonicalize` parameter will run the other two paramters through `canonicalDomain` or not. + +defaultPath(path) +----------------- + +Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. + +The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. + +pathMatch(reqPath,cookiePath) +----------------------------- + +Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. + +This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. + +parse(header[,strict=false]) +---------------------------- + +alias for `Cookie.parse(header[,strict])` + +fromJSON(string) +---------------- + +alias for `Cookie.fromJSON(string)` + +getPublicSuffix(hostname) +------------------------- + +Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. + +For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. + +For further information, see http://publicsuffix.org/. This module derives its list from that site. + +cookieCompare(a,b) +------------------ + +For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). Longest `.path`s go first, then sorted oldest to youngest. + +``` javascript +var cookies = [ /* unsorted array of Cookie objects */ ]; +cookies = cookies.sort(cookieCompare); +``` + +permuteDomain(domain) +--------------------- + +Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. + + +permutePath(path) +----------------- + +Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. + +Cookie +====== + +Cookie.parse(header[,strict=false]) +----------------------------------- + +Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. If in strict mode, returns `undefined` if the cookie doesn't follow the guidelines in section 4 of RFC6265. Generally speaking, strict mode can be used to validate your own generated Set-Cookie headers, but acting as a client you want to be lenient and leave strict mode off. + +Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: + +``` javascript +if (res.headers['set-cookie'] instanceof Array) + cookies = res.headers['set-cookie'].map(function (c) { return (Cookie.parse(c)); }); +else + cookies = [Cookie.parse(res.headers['set-cookie'])]; +``` + +Cookie.fromJSON(string) +----------------------- + +Convert a JSON string to a `Cookie` object. Does a `JSON.parse()` and converts the `.created`, `.lastAccessed` and `.expires` properties into `Date` objects. + +Properties +========== + + * _key_ - string - the name or key of the cookie (default "") + * _value_ - string - the value of the cookie (default "") + * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` + * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` + * _domain_ - string - the `Domain=` attribute of the cookie + * _path_ - string - the `Path=` of the cookie + * _secure_ - boolean - the `Secure` cookie flag + * _httpOnly_ - boolean - the `HttpOnly` cookie flag + * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) + +After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: + + * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) + * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. + * _created_ - `Date` - when this cookie was added to the jar + * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. + +Construction([{options}]) +------------ + +Receives an options object that can contain any Cookie properties, uses the default for unspecified properties. + +.toString() +----------- + +encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. + +.cookieString() +--------------- + +encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). + +.setExpires(String) +------------------- + +sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. + +.setMaxAge(number) +------------------- + +sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. + +.expiryTime([now=Date.now()]) +----------------------------- + +.expiryDate([now=Date.now()]) +----------------------------- + +expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. + +Max-Age takes precedence over Expires (as per the RFC). The `.created` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute. + +If Expires (`.expires`) is set, that's returned. + +Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). + +.TTL([now=Date.now()]) +--------- + +compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. + +The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. + +.canonicalizedDoman() +--------------------- + +.cdomain() +---------- + +return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. + +.validate() +----------- + +Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. + +validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: + +``` javascript +if (cookie.validate() === true) { + // it's tasty +} else { + // yuck! +} +``` + +CookieJar +========= + +Construction([store = new MemoryCookieStore()][, rejectPublicSuffixes]) +------------ + +Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. + + +Attributes +---------- + + * _rejectPublicSuffixes_ - boolean - reject cookies with domains like "com" and "co.uk" (default: `true`) + +Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. + +.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie)) +------------------------------------------------------------------- + +Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.created`, `.lastAccessed` and `.hostOnly` properties. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _strict_ - boolean - default `false` - perform extra checks + * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. CookieStore errors aren't ignored by this option. + +As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). + +.setCookieSync(cookieOrString, currentUrl, [{options}]) +------------------------------------------------------- + +Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.storeCookie(cookie, [{options},] cb(err,cookie)) +------------------------------------------------- + +__REMOVED__ removed in lieu of the CookieStore API below + +.getCookies(currentUrl, [{options},] cb(err,cookies)) +----------------------------------------------------- + +Retrieve the list of cookies that can be sent in a Cookie header for the current url. + +If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). + * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the CookieStore `fetchCookies` function (the default MemoryCookieStore supports it). + +The `.lastAccessed` property of the returned cookies will have been updated. + +.getCookiesSync(currentUrl, [{options}]) +---------------------------------------- + +Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.getCookieString(...) +--------------------- + +Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. + +.getCookieStringSync(...) +------------------------- + +Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.getSetCookieStrings(...) +------------------------- + +Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. + +.getSetCookieStringsSync(...) +----------------------------- + +Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +Store +===== + +Base class for CookieJar stores. + +# CookieStore API + +The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. + +Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set, then the `*Sync` methods on the CookieJar can be used. + +All `domain` parameters will have been normalized before calling. + +The Cookie store must have all of the following methods. + +store.findCookie(domain, path, key, cb(err,cookie)) +--------------------------------------------------- + +Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. + +Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). + +store.findCookies(domain, path, cb(err,cookies)) +------------------------------------------------ + +Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. + +If no cookies are found, the callback MUST be passed an empty array. + +The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. + +As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). + +store.putCookie(cookie, cb(err)) +-------------------------------- + +Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. + +The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. + +Pass an error if the cookie cannot be stored. + +store.updateCookie(oldCookie, newCookie, cb(err)) +------------------------------------------------- + +Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. + +The `.lastAccessed` property will always be different between the two objects and `.created` will always be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are sorted (or selected for deletion). + +Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. + +The `newCookie` and `oldCookie` objects MUST NOT be modified. + +Pass an error if the newCookie cannot be stored. + +store.removeCookie(domain, path, key, cb(err)) +---------------------------------------------- + +Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). + +The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. + +store.removeCookies(domain, path, cb(err)) +------------------------------------------ + +Removes matching cookies from the store. The `path` paramter is optional, and if missing means all paths in a domain should be removed. + +Pass an error ONLY if removing any existing cookies failed. + +# TODO + + * _full_ RFC5890/RFC5891 canonicalization for domains in `cdomain()` + * the optional `punycode` requirement implements RFC3492, but RFC6265 requires RFC5891 + * better tests for `validate()`? + +# Copyright and License + +(tl;dr: MIT with some MPL/1.1) + +Copyright 2012- GoInstant, Inc. and other contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +Portions may be licensed under different licenses (in particular public-suffix.txt is MPL/1.1); please read the LICENSE file for full details. diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js new file mode 100644 index 000000000..74d76aa1c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js @@ -0,0 +1,239 @@ +/* + * Copyright GoInstant, Inc. and other contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +'use strict'; +var fs = require('fs'); +var assert = require('assert'); +var punycode = require('punycode'); + +fs.readFile('./public-suffix.txt', 'utf8', function(err,string) { + if (err) { + throw err; + } + var lines = string.split("\n"); + process.nextTick(function() { + processList(lines); + }); +}); + +var index = {}; + +var COMMENT = new RegExp('//.+'); +function processList(lines) { + while (lines.length) { + var line = lines.shift(); + line = line.replace(COMMENT,'').trim(); + if (!line) { + continue; + } + addToIndex(index,line); + } + + pubSufTest(); + + var w = fs.createWriteStream('./lib/pubsuffix.js',{ + flags: 'w', + encoding: 'utf8', + mode: parseInt('644',8) + }); + w.on('end', process.exit); + w.write("/****************************************************\n"); + w.write(" * AUTOMATICALLY GENERATED by generate-pubsuffix.js *\n"); + w.write(" * DO NOT EDIT! *\n"); + w.write(" ****************************************************/\n\n"); + + w.write("module.exports.getPublicSuffix = "); + w.write(getPublicSuffix.toString()); + w.write(";\n\n"); + + w.write("// The following generated structure is used under the MPL version 1.1\n"); + w.write("// See public-suffix.txt for more information\n\n"); + w.write("var index = module.exports.index = Object.freeze(\n"); + w.write(JSON.stringify(index)); + w.write(");\n\n"); + w.write("// END of automatically generated file\n"); + + w.end(); +} + +function addToIndex(index,line) { + var prefix = ''; + if (line.replace(/^(!|\*\.)/)) { + prefix = RegExp.$1; + line = line.slice(prefix.length); + } + line = prefix + punycode.toASCII(line); + + if (line.substr(0,1) == '!') { + index[line.substr(1)] = false; + } else { + index[line] = true; + } +} + +// include the licence in the function since it gets written to pubsuffix.js +function getPublicSuffix(domain) { + /* + * Copyright GoInstant, Inc. and other contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + if (!domain) { + return null; + } + if (domain.match(/^\./)) { + return null; + } + + domain = domain.toLowerCase(); + var parts = domain.split('.').reverse(); + + var suffix = ''; + var suffixLen = 0; + for (var i=0; i suffixLen) { + return parts.slice(0,suffixLen+1).reverse().join('.'); + } + + return null; +} + +function checkPublicSuffix(give,get) { + var got = getPublicSuffix(give); + assert.equal(got, get, give+' should be '+(get==null?'NULL':get)+' but got '+got); +} + +// pubSufTest() was converted to JavaScript from http://publicsuffix.org/list/test.txt +function pubSufTest() { + // For this function-scope and this function-scope ONLY: + // Any copyright is dedicated to the Public Domain. + // http://creativecommons.org/publicdomain/zero/1.0/ + + // NULL input. + checkPublicSuffix(null, null); + // Mixed case. + checkPublicSuffix('COM', null); + checkPublicSuffix('example.COM', 'example.com'); + checkPublicSuffix('WwW.example.COM', 'example.com'); + // Leading dot. + checkPublicSuffix('.com', null); + checkPublicSuffix('.example', null); + checkPublicSuffix('.example.com', null); + checkPublicSuffix('.example.example', null); + // Unlisted TLD. + checkPublicSuffix('example', null); + checkPublicSuffix('example.example', null); + checkPublicSuffix('b.example.example', null); + checkPublicSuffix('a.b.example.example', null); + // Listed, but non-Internet, TLD. + checkPublicSuffix('local', null); + checkPublicSuffix('example.local', null); + checkPublicSuffix('b.example.local', null); + checkPublicSuffix('a.b.example.local', null); + // TLD with only 1 rule. + checkPublicSuffix('biz', null); + checkPublicSuffix('domain.biz', 'domain.biz'); + checkPublicSuffix('b.domain.biz', 'domain.biz'); + checkPublicSuffix('a.b.domain.biz', 'domain.biz'); + // TLD with some 2-level rules. + checkPublicSuffix('com', null); + checkPublicSuffix('example.com', 'example.com'); + checkPublicSuffix('b.example.com', 'example.com'); + checkPublicSuffix('a.b.example.com', 'example.com'); + checkPublicSuffix('uk.com', null); + checkPublicSuffix('example.uk.com', 'example.uk.com'); + checkPublicSuffix('b.example.uk.com', 'example.uk.com'); + checkPublicSuffix('a.b.example.uk.com', 'example.uk.com'); + checkPublicSuffix('test.ac', 'test.ac'); + // TLD with only 1 (wildcard) rule. + checkPublicSuffix('cy', null); + checkPublicSuffix('c.cy', null); + checkPublicSuffix('b.c.cy', 'b.c.cy'); + checkPublicSuffix('a.b.c.cy', 'b.c.cy'); + // More complex TLD. + checkPublicSuffix('jp', null); + checkPublicSuffix('test.jp', 'test.jp'); + checkPublicSuffix('www.test.jp', 'test.jp'); + checkPublicSuffix('ac.jp', null); + checkPublicSuffix('test.ac.jp', 'test.ac.jp'); + checkPublicSuffix('www.test.ac.jp', 'test.ac.jp'); + checkPublicSuffix('kyoto.jp', null); + checkPublicSuffix('c.kyoto.jp', null); + checkPublicSuffix('b.c.kyoto.jp', 'b.c.kyoto.jp'); + checkPublicSuffix('a.b.c.kyoto.jp', 'b.c.kyoto.jp'); + checkPublicSuffix('pref.kyoto.jp', 'pref.kyoto.jp'); // Exception rule. + checkPublicSuffix('www.pref.kyoto.jp', 'pref.kyoto.jp'); // Exception rule. + checkPublicSuffix('city.kyoto.jp', 'city.kyoto.jp'); // Exception rule. + checkPublicSuffix('www.city.kyoto.jp', 'city.kyoto.jp'); // Exception rule. + // TLD with a wildcard rule and exceptions. + checkPublicSuffix('om', null); + checkPublicSuffix('test.om', null); + checkPublicSuffix('b.test.om', 'b.test.om'); + checkPublicSuffix('a.b.test.om', 'b.test.om'); + checkPublicSuffix('songfest.om', 'songfest.om'); + checkPublicSuffix('www.songfest.om', 'songfest.om'); + // US K12. + checkPublicSuffix('us', null); + checkPublicSuffix('test.us', 'test.us'); + checkPublicSuffix('www.test.us', 'test.us'); + checkPublicSuffix('ak.us', null); + checkPublicSuffix('test.ak.us', 'test.ak.us'); + checkPublicSuffix('www.test.ak.us', 'test.ak.us'); + checkPublicSuffix('k12.ak.us', null); + checkPublicSuffix('test.k12.ak.us', 'test.k12.ak.us'); + checkPublicSuffix('www.test.k12.ak.us', 'test.k12.ak.us'); + + +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/cookie.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/cookie.js new file mode 100644 index 000000000..c93e927ae --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/cookie.js @@ -0,0 +1,1107 @@ +/* + * Copyright GoInstant, Inc. and other contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +'use strict'; +var net = require('net'); +var urlParse = require('url').parse; +var pubsuffix = require('./pubsuffix'); +var Store = require('./store').Store; + +var punycode; +try { + punycode = require('punycode'); +} catch(e) { + console.warn("cookie: can't load punycode; won't use punycode for domain normalization"); +} + +var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +// From RFC2616 S2.2: +var TOKEN = /[\x21\x23-\x26\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/; + +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +var COOKIE_OCTET = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/; +var COOKIE_OCTETS = new RegExp('^'+COOKIE_OCTET.source+'$'); + +// The name/key cannot be empty but the value can (S5.2): +var COOKIE_PAIR_STRICT = new RegExp('^('+TOKEN.source+'+)=("?)('+COOKIE_OCTET.source+'*)\\2$'); +var COOKIE_PAIR = /^([^=\s]+)\s*=\s*("?)\s*(.*)\s*\2\s*$/; + +// RFC6265 S4.1.1 defines extension-av as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +var NON_CTL_SEMICOLON = /[\x20-\x3A\x3C-\x7E]+/; +var EXTENSION_AV = NON_CTL_SEMICOLON; +var PATH_VALUE = NON_CTL_SEMICOLON; + +// Used for checking whether or not there is a trailing semi-colon +var TRAILING_SEMICOLON = /;+$/; + +/* RFC6265 S5.1.1.5: + * [fail if] the day-of-month-value is less than 1 or greater than 31 + */ +var DAY_OF_MONTH = /^(0?[1-9]|[12][0-9]|3[01])$/; + +/* RFC6265 S5.1.1.5: + * [fail if] + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + */ +var TIME = /(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/; +var STRICT_TIME = /^(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/; + +var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/i; +var MONTH_TO_NUM = { + jan:0, feb:1, mar:2, apr:3, may:4, jun:5, + jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 +}; +var NUM_TO_MONTH = [ + 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' +]; +var NUM_TO_DAY = [ + 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' +]; + +var YEAR = /^([1-9][0-9]{1,3})$/; // 2 to 4 digits + +var MAX_TIME = 2147483647000; // 31-bit max +var MIN_TIME = 0; // 31-bit min + + +// RFC6265 S5.1.1 date parser: +function parseDate(str,strict) { + if (!str) { + return; + } + var found_time, found_dom, found_month, found_year; + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + var tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + var date = new Date(); + date.setMilliseconds(0); + + for (var i=0; i= 10 ? d : '0'+d; + var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; + var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; + var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; + return NUM_TO_DAY[date.getUTCDay()] + ', ' + + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ + h+':'+m+':'+s+' GMT'; +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * "The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ + + /* "* The string is a host name (i.e., not an IP address)." */ + if (net.isIP(str)) { + return false; + } + + /* "* The domain string is a suffix of the string" */ + var idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // e.g "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { // it's not a suffix + return false; + } + + /* "* The last character of the string that is not included in the domain + * string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; + } + + return true; +} + + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0,1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + var rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch(reqPath,cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + var idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length,1) === "/") { + return true; + } + } + + return false; +} + +function parse(str, strict) { + str = str.trim(); + + // S4.1.1 Trailing semi-colons are not part of the specification. + // If we are not in strict mode we remove the trailing semi-colons. + var semiColonCheck = TRAILING_SEMICOLON.exec(str); + if (semiColonCheck) { + if (strict) { + return; + } + str = str.slice(0, semiColonCheck.index); + } + + // We use a regex to parse the "name-value-pair" part of S5.2 + var firstSemi = str.indexOf(';'); // S5.2 step 1 + var pairRx = strict ? COOKIE_PAIR_STRICT : COOKIE_PAIR; + var result = pairRx.exec(firstSemi === -1 ? str : str.substr(0,firstSemi)); + + // Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")" + // constraints as well as trimming any whitespace. + if (!result) { + return; + } + + var c = new Cookie(); + c.key = result[1]; // the regexp should trim() already + c.value = result[3]; // [2] is quotes or empty-string + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + var unparsed = str.slice(firstSemi).replace(/^\s*;\s*/,'').trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + var cookie_avs = unparsed.split(/\s*;\s*/); + while (cookie_avs.length) { + var av = cookie_avs.shift(); + + if (strict && !EXTENSION_AV.test(av)) { + return; + } + + var av_sep = av.indexOf('='); + var av_key, av_value; + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0,av_sep); + av_value = av.substr(av_sep+1); + } + + av_key = av_key.trim().toLowerCase(); + if (av_value) { + av_value = av_value.trim(); + } + + switch(av_key) { + case 'expires': // S5.2.1 + if (!av_value) {if(strict){return;}else{break;} } + var exp = parseDate(av_value,strict); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp == null) { if(strict){return;}else{break;} } + c.expires = exp; + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + break; + + case 'max-age': // S5.2.2 + if (!av_value) { if(strict){return;}else{break;} } + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (!/^-?[0-9]+$/.test(av_value)) { if(strict){return;}else{break;} } + var delta = parseInt(av_value,10); + if (strict && delta <= 0) { + return; // S4.1.1 + } + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + break; + + case 'domain': // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (!av_value) { if(strict){return;}else{break;} } + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + var domain = av_value.trim().replace(/^\./,''); + if (!domain) { if(strict){return;}else{break;} } // see "is empty" above + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + break; + + case 'path': // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + if (!av_value || av_value.substr(0,1) != "/") { + if(strict){return;}else{break;} + } + c.path = av_value; + break; + + case 'secure': // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + if (av_value != null) { if(strict){return;} } + c.secure = true; + break; + + case 'httponly': // S5.2.6 -- effectively the same as 'secure' + if (av_value != null) { if(strict){return;} } + c.httpOnly = true; + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + // ensure a default date for sorting: + c.creation = new Date(); + return c; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + var obj; + try { + obj = JSON.parse(str); + } catch (e) { + return null; + } + + var c = new Cookie(); + for (var i=0; i 1) { + var lindex = path.lastIndexOf('/'); + if (lindex === 0) { + break; + } + path = path.substr(0,lindex); + permutations.push(path); + } + permutations.push('/'); + return permutations; +} + + +function Cookie (opts) { + if (typeof opts !== "object") { + return; + } + Object.keys(opts).forEach(function (key) { + if (Cookie.prototype.hasOwnProperty(key)) { + this[key] = opts[key] || Cookie.prototype[key]; + } + }.bind(this)); +} + +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; + +Cookie.prototype.key = ""; +Cookie.prototype.value = ""; + +// the order in which the RFC has them: +Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity +Cookie.prototype.maxAge = null; // takes precedence over expires for TTL +Cookie.prototype.domain = null; +Cookie.prototype.path = null; +Cookie.prototype.secure = false; +Cookie.prototype.httpOnly = false; +Cookie.prototype.extensions = null; + +// set by the CookieJar: +Cookie.prototype.hostOnly = null; // boolean when set +Cookie.prototype.pathIsDefault = null; // boolean when set +Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse +Cookie.prototype.lastAccessed = null; // Date when set + +var cookieProperties = Object.freeze(Object.keys(Cookie.prototype).map(function(p) { + if (p instanceof Function) { + return; + } + return p; +})); +var numCookieProperties = cookieProperties.length; + +Cookie.prototype.inspect = function inspect() { + var now = Date.now(); + return 'Cookie="'+this.toString() + + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + + '"'; +}; + +Cookie.prototype.validate = function validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires,true)) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + var cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this + } + var suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { // it's a public suffix + return false; + } + } + return true; +}; + +Cookie.prototype.setExpires = function setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } +}; + +Cookie.prototype.setMaxAge = function setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } +}; + +// gives Cookie header format +Cookie.prototype.cookieString = function cookieString() { + var val = this.value; + if (val == null) { + val = ''; + } + return this.key+'='+val; +}; + +// gives Set-Cookie header format +Cookie.prototype.toString = function toString() { + var str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += '; Expires='+formatDate(this.expires); + } else { + str += '; Expires='+this.expires; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += '; Max-Age='+this.maxAge; + } + + if (this.domain && !this.hostOnly) { + str += '; Domain='+this.domain; + } + if (this.path) { + str += '; Path='+this.path; + } + + if (this.secure) { + str += '; Secure'; + } + if (this.httpOnly) { + str += '; HttpOnly'; + } + if (this.extensions) { + this.extensions.forEach(function(ext) { + str += '; '+ext; + }); + } + + return str; +}; + +// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +// S5.3 says to give the "latest representable date" for which we use Infinity +// For "expired" we use 0 +Cookie.prototype.TTL = function TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge<=0 ? 0 : this.maxAge*1000; + } + + var expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; + } + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; +}; + +// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +Cookie.prototype.expiryTime = function expiryTime(now) { + if (this.maxAge != null) { + var relativeTo = this.creation || now || new Date(); + var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); +}; + +// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere), except it returns a Date +Cookie.prototype.expiryDate = function expiryDate(now) { + var millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } +}; + +// This replaces the "persistent-flag" parts of S5.3 step 3 +Cookie.prototype.isPersistent = function isPersistent() { + return (this.maxAge != null || this.expires != Infinity); +}; + +// Mostly S5.1.2 and S5.2.3: +Cookie.prototype.cdomain = +Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); +}; + + +var memstore; +function CookieJar(store, rejectPublicSuffixes) { + if (rejectPublicSuffixes != null) { + this.rejectPublicSuffixes = rejectPublicSuffixes; + } + + if (!store) { + memstore = memstore || require('./memstore'); + store = new memstore.MemoryCookieStore(); + } + this.store = store; +} +CookieJar.prototype.store = null; +CookieJar.prototype.rejectPublicSuffixes = true; +var CAN_BE_SYNC = []; + +CAN_BE_SYNC.push('setCookie'); +CookieJar.prototype.setCookie = function(cookie, url, options, cb) { + var err; + var context = (url instanceof Object) ? url : urlParse(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + + // S5.3 step 1 + if (!(cookie instanceof Cookie)) { + cookie = Cookie.parse(cookie, options.strict === true); + } + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + var now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + var suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { // don't reset if already set + cookie.hostOnly = false; + } + + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + // S5.3 step 7: "Otherwise, set the cookie's path to the default-path of the + // request-uri" + if (!cookie.path) { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } else { + if (cookie.path.length > 1 && cookie.path.substr(-1) == '/') { + cookie.path = cookie.path.slice(0,-1); + } + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + var store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + var next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); +}; + +// RFC6365 S5.4 +CAN_BE_SYNC.push('getCookies'); +CookieJar.prototype.getCookies = function(url, options, cb) { + var context = (url instanceof Object) ? url : urlParse(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + var path = context.pathname || '/'; + + var secure = options.secure; + if (secure == null && context.protocol && + (context.protocol == 'https:' || context.protocol == 'wss:')) + { + secure = true; + } + + var http = options.http; + if (http == null) { + http = true; + } + + var now = options.now || Date.now(); + var expireCheck = options.expire !== false; + var allPaths = !!options.allPaths; + var store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } + } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored + return false; + } + + return true; + } + + store.findCookies(host, allPaths ? null : path, function(err,cookies) { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + var now = new Date(); + cookies.forEach(function(c) { + c.lastAccessed = now; + }); + // TODO persist lastAccessed + + cb(null,cookies); + }); +}; + +CAN_BE_SYNC.push('getCookieString'); +CookieJar.prototype.getCookieString = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies.map(function(c){ + return c.cookieString(); + }).join('; ')); + } + }; + args.push(next); + this.getCookies.apply(this,args); +}; + +CAN_BE_SYNC.push('getSetCookieStrings'); +CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies.map(function(c){ + return c.toString(); + })); + } + }; + args.push(next); + this.getCookies.apply(this,args); +}; + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function() { + if (!this.store.synchronous) { + throw new Error('CookieJar store is not synchronous; use async API instead.'); + } + + var args = Array.prototype.slice.call(arguments); + var syncErr, syncResult; + args.push(function syncCb(err, result) { + syncErr = err; + syncResult = result; + }); + this[method].apply(this, args); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +// wrap all declared CAN_BE_SYNC methods in the sync wrapper +CAN_BE_SYNC.forEach(function(method) { + CookieJar.prototype[method+'Sync'] = syncWrap(method); +}); + +module.exports = { + CookieJar: CookieJar, + Cookie: Cookie, + Store: Store, + parseDate: parseDate, + formatDate: formatDate, + parse: parse, + fromJSON: fromJSON, + domainMatch: domainMatch, + defaultPath: defaultPath, + pathMatch: pathMatch, + getPublicSuffix: pubsuffix.getPublicSuffix, + cookieCompare: cookieCompare, + permuteDomain: permuteDomain, + permutePath: permutePath, + canonicalDomain: canonicalDomain, +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/memstore.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/memstore.js new file mode 100644 index 000000000..fc5774c8a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/memstore.js @@ -0,0 +1,123 @@ +'use strict'; +var tough = require('./cookie'); +var Store = require('./store').Store; +var permuteDomain = tough.permuteDomain; +var permutePath = tough.permutePath; +var util = require('util'); + +function MemoryCookieStore() { + Store.call(this); + this.idx = {}; +} +util.inherits(MemoryCookieStore, Store); +exports.MemoryCookieStore = MemoryCookieStore; +MemoryCookieStore.prototype.idx = null; +MemoryCookieStore.prototype.synchronous = true; + +// force a default depth: +MemoryCookieStore.prototype.inspect = function() { + return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; +}; + +MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null,undefined); + } + if (!this.idx[domain][path]) { + return cb(null,undefined); + } + return cb(null,this.idx[domain][path][key]||null); +}; + +MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { + var results = []; + if (!domain) { + return cb(null,[]); + } + + var pathMatcher; + if (!path) { + // null or '/' means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (var curPath in domainIndex) { + var pathIndex = domainIndex[curPath]; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + + } else if (path === '/') { + pathMatcher = function matchSlash(domainIndex) { + var pathIndex = domainIndex['/']; + if (!pathIndex) { + return; + } + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + }; + + } else { + var paths = permutePath(path) || [path]; + pathMatcher = function matchRFC(domainIndex) { + paths.forEach(function(curPath) { + var pathIndex = domainIndex[curPath]; + if (!pathIndex) { + return; + } + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + }); + }; + } + + var domains = permuteDomain(domain) || [domain]; + var idx = this.idx; + domains.forEach(function(curDomain) { + var domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null,results); +}; + +MemoryCookieStore.prototype.putCookie = function(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); +}; + +MemoryCookieStore.prototype.updateCookie = function updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie,cb); +}; + +MemoryCookieStore.prototype.removeCookie = function removeCookie(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); +}; + +MemoryCookieStore.prototype.removeCookies = function removeCookies(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js new file mode 100644 index 000000000..a7031473b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js @@ -0,0 +1,69 @@ +/**************************************************** + * AUTOMATICALLY GENERATED by generate-pubsuffix.js * + * DO NOT EDIT! * + ****************************************************/ + +module.exports.getPublicSuffix = function getPublicSuffix(domain) { + /* + * Copyright GoInstant, Inc. and other contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + if (!domain) return null; + if (domain.match(/^\./)) return null; + + domain = domain.toLowerCase(); + var parts = domain.split('.').reverse(); + + var suffix = ''; + var suffixLen = 0; + for (var i=0; i suffixLen) { + return parts.slice(0,suffixLen+1).reverse().join('.'); + } + + return null; +}; + +// The following generated structure is used under the MPL version 1.1 +// See public-suffix.txt for more information + +var index = module.exports.index = Object.freeze( +{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"*.ar":true,"congresodelalengua3.ar":false,"educ.ar":false,"gobiernoelectronico.ar":false,"mecon.ar":false,"nacion.ar":false,"nic.ar":false,"promocion.ar":false,"retina.ar":false,"uba.ar":false,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"csiro.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"act.gov.au":true,"nt.gov.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"can.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mus.br":true,"net.br":true,"nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"gov.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cx":true,"gov.cx":true,"*.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"*.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"org.gg":true,"net.gg":true,"sch.gg":true,"gov.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"gm":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"*.gt":true,"www.gt":false,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"co.id":true,"go.id":true,"mil.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"*.il":true,"im":true,"co.im":true,"ltd.co.im":true,"plc.co.im":true,"net.im":true,"gov.im":true,"org.im":true,"nic.im":true,"ac.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"agrigento.it":true,"ag.it":true,"alessandria.it":true,"al.it":true,"ancona.it":true,"an.it":true,"aosta.it":true,"aoste.it":true,"ao.it":true,"arezzo.it":true,"ar.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"ap.it":true,"asti.it":true,"at.it":true,"avellino.it":true,"av.it":true,"bari.it":true,"ba.it":true,"andria-barletta-trani.it":true,"andriabarlettatrani.it":true,"trani-barletta-andria.it":true,"tranibarlettaandria.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"andria-trani-barletta.it":true,"andriatranibarletta.it":true,"trani-andria-barletta.it":true,"traniandriabarletta.it":true,"bt.it":true,"belluno.it":true,"bl.it":true,"benevento.it":true,"bn.it":true,"bergamo.it":true,"bg.it":true,"biella.it":true,"bi.it":true,"bologna.it":true,"bo.it":true,"bolzano.it":true,"bozen.it":true,"balsan.it":true,"alto-adige.it":true,"altoadige.it":true,"suedtirol.it":true,"bz.it":true,"brescia.it":true,"bs.it":true,"brindisi.it":true,"br.it":true,"cagliari.it":true,"ca.it":true,"caltanissetta.it":true,"cl.it":true,"campobasso.it":true,"cb.it":true,"carboniaiglesias.it":true,"carbonia-iglesias.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"ci.it":true,"caserta.it":true,"ce.it":true,"catania.it":true,"ct.it":true,"catanzaro.it":true,"cz.it":true,"chieti.it":true,"ch.it":true,"como.it":true,"co.it":true,"cosenza.it":true,"cs.it":true,"cremona.it":true,"cr.it":true,"crotone.it":true,"kr.it":true,"cuneo.it":true,"cn.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"ogliastra.it":true,"og.it":true,"enna.it":true,"en.it":true,"ferrara.it":true,"fe.it":true,"fermo.it":true,"fm.it":true,"firenze.it":true,"florence.it":true,"fi.it":true,"foggia.it":true,"fg.it":true,"forli-cesena.it":true,"forlicesena.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"fc.it":true,"frosinone.it":true,"fr.it":true,"genova.it":true,"genoa.it":true,"ge.it":true,"gorizia.it":true,"go.it":true,"grosseto.it":true,"gr.it":true,"imperia.it":true,"im.it":true,"isernia.it":true,"is.it":true,"laquila.it":true,"aquila.it":true,"aq.it":true,"la-spezia.it":true,"laspezia.it":true,"sp.it":true,"latina.it":true,"lt.it":true,"lecce.it":true,"le.it":true,"lecco.it":true,"lc.it":true,"livorno.it":true,"li.it":true,"lodi.it":true,"lo.it":true,"lucca.it":true,"lu.it":true,"macerata.it":true,"mc.it":true,"mantova.it":true,"mn.it":true,"massa-carrara.it":true,"massacarrara.it":true,"carrara-massa.it":true,"carraramassa.it":true,"ms.it":true,"matera.it":true,"mt.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"vs.it":true,"messina.it":true,"me.it":true,"milano.it":true,"milan.it":true,"mi.it":true,"modena.it":true,"mo.it":true,"monza.it":true,"monza-brianza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"monza-e-della-brianza.it":true,"mb.it":true,"napoli.it":true,"naples.it":true,"na.it":true,"novara.it":true,"no.it":true,"nuoro.it":true,"nu.it":true,"oristano.it":true,"or.it":true,"padova.it":true,"padua.it":true,"pd.it":true,"palermo.it":true,"pa.it":true,"parma.it":true,"pr.it":true,"pavia.it":true,"pv.it":true,"perugia.it":true,"pg.it":true,"pescara.it":true,"pe.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"pu.it":true,"piacenza.it":true,"pc.it":true,"pisa.it":true,"pi.it":true,"pistoia.it":true,"pt.it":true,"pordenone.it":true,"pn.it":true,"potenza.it":true,"pz.it":true,"prato.it":true,"po.it":true,"ragusa.it":true,"rg.it":true,"ravenna.it":true,"ra.it":true,"reggio-calabria.it":true,"reggiocalabria.it":true,"rc.it":true,"reggio-emilia.it":true,"reggioemilia.it":true,"re.it":true,"rieti.it":true,"ri.it":true,"rimini.it":true,"rn.it":true,"roma.it":true,"rome.it":true,"rm.it":true,"rovigo.it":true,"ro.it":true,"salerno.it":true,"sa.it":true,"sassari.it":true,"ss.it":true,"savona.it":true,"sv.it":true,"siena.it":true,"si.it":true,"siracusa.it":true,"sr.it":true,"sondrio.it":true,"so.it":true,"taranto.it":true,"ta.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"ot.it":true,"teramo.it":true,"te.it":true,"terni.it":true,"tr.it":true,"torino.it":true,"turin.it":true,"to.it":true,"trapani.it":true,"tp.it":true,"trento.it":true,"trentino.it":true,"tn.it":true,"treviso.it":true,"tv.it":true,"trieste.it":true,"ts.it":true,"udine.it":true,"ud.it":true,"varese.it":true,"va.it":true,"venezia.it":true,"venice.it":true,"ve.it":true,"verbania.it":true,"vb.it":true,"vercelli.it":true,"vc.it":true,"verona.it":true,"vr.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vv.it":true,"vicenza.it":true,"vi.it":true,"viterbo.it":true,"vt.it":true,"je":true,"co.je":true,"org.je":true,"net.je":true,"sch.je":true,"gov.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"*.aichi.jp":true,"*.akita.jp":true,"*.aomori.jp":true,"*.chiba.jp":true,"*.ehime.jp":true,"*.fukui.jp":true,"*.fukuoka.jp":true,"*.fukushima.jp":true,"*.gifu.jp":true,"*.gunma.jp":true,"*.hiroshima.jp":true,"*.hokkaido.jp":true,"*.hyogo.jp":true,"*.ibaraki.jp":true,"*.ishikawa.jp":true,"*.iwate.jp":true,"*.kagawa.jp":true,"*.kagoshima.jp":true,"*.kanagawa.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.kochi.jp":true,"*.kumamoto.jp":true,"*.kyoto.jp":true,"*.mie.jp":true,"*.miyagi.jp":true,"*.miyazaki.jp":true,"*.nagano.jp":true,"*.nagasaki.jp":true,"*.nagoya.jp":true,"*.nara.jp":true,"*.niigata.jp":true,"*.oita.jp":true,"*.okayama.jp":true,"*.okinawa.jp":true,"*.osaka.jp":true,"*.saga.jp":true,"*.saitama.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.shiga.jp":true,"*.shimane.jp":true,"*.shizuoka.jp":true,"*.tochigi.jp":true,"*.tokushima.jp":true,"*.tokyo.jp":true,"*.tottori.jp":true,"*.toyama.jp":true,"*.wakayama.jp":true,"*.yamagata.jp":true,"*.yamaguchi.jp":true,"*.yamanashi.jp":true,"*.yokohama.jp":true,"metro.tokyo.jp":false,"pref.aichi.jp":false,"pref.akita.jp":false,"pref.aomori.jp":false,"pref.chiba.jp":false,"pref.ehime.jp":false,"pref.fukui.jp":false,"pref.fukuoka.jp":false,"pref.fukushima.jp":false,"pref.gifu.jp":false,"pref.gunma.jp":false,"pref.hiroshima.jp":false,"pref.hokkaido.jp":false,"pref.hyogo.jp":false,"pref.ibaraki.jp":false,"pref.ishikawa.jp":false,"pref.iwate.jp":false,"pref.kagawa.jp":false,"pref.kagoshima.jp":false,"pref.kanagawa.jp":false,"pref.kochi.jp":false,"pref.kumamoto.jp":false,"pref.kyoto.jp":false,"pref.mie.jp":false,"pref.miyagi.jp":false,"pref.miyazaki.jp":false,"pref.nagano.jp":false,"pref.nagasaki.jp":false,"pref.nara.jp":false,"pref.niigata.jp":false,"pref.oita.jp":false,"pref.okayama.jp":false,"pref.okinawa.jp":false,"pref.osaka.jp":false,"pref.saga.jp":false,"pref.saitama.jp":false,"pref.shiga.jp":false,"pref.shimane.jp":false,"pref.shizuoka.jp":false,"pref.tochigi.jp":false,"pref.tokushima.jp":false,"pref.tottori.jp":false,"pref.toyama.jp":false,"pref.wakayama.jp":false,"pref.yamagata.jp":false,"pref.yamaguchi.jp":false,"pref.yamanashi.jp":false,"city.chiba.jp":false,"city.fukuoka.jp":false,"city.hiroshima.jp":false,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.kyoto.jp":false,"city.nagoya.jp":false,"city.niigata.jp":false,"city.okayama.jp":false,"city.osaka.jp":false,"city.saitama.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.shizuoka.jp":false,"city.yokohama.jp":false,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"*.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ac.ng":true,"com.ng":true,"edu.ng":true,"gov.ng":true,"net.ng":true,"org.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"*.nz":true,"*.om":true,"mediaphone.om":false,"nawrastelecom.om":false,"nawras.om":false,"omanmobile.om":false,"omanpost.om":false,"omantel.om":false,"rakpetroleum.om":false,"siemens.om":false,"songfest.om":false,"statecouncil.om":false,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"com.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"info.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"net.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"org.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"6bone.pl":true,"art.pl":true,"mbone.pl":true,"gov.pl":true,"uw.gov.pl":true,"um.gov.pl":true,"ug.gov.pl":true,"upow.gov.pl":true,"starostwo.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"po.gov.pl":true,"pa.gov.pl":true,"ngo.pl":true,"irc.pl":true,"usenet.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"siedlce.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"waw.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"*.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"mosreg.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"pskov.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"sshn.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"si":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"*.sv":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"*.tr":true,"nic.tr":false,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"ac.tz":true,"co.tz":true,"go.tz":true,"mil.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"chernigov.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"ks.ua":true,"kv.ua":true,"lg.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lviv.ua":true,"mk.ua":true,"nikolaev.ua":true,"od.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rovno.ua":true,"rv.ua":true,"sebastopol.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vn.ua":true,"zaporizhzhe.ua":true,"zp.ua":true,"zhitomir.ua":true,"zt.ua":true,"co.ua":true,"pp.ua":true,"ug":true,"co.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"or.ug":true,"*.uk":true,"*.sch.uk":true,"bl.uk":false,"british-library.uk":false,"icnet.uk":false,"jet.uk":false,"mod.uk":false,"nel.uk":false,"nhs.uk":false,"nic.uk":false,"nls.uk":false,"national-library-scotland.uk":false,"parliament.uk":false,"police.uk":false,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.nd.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.sd.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wv.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wv.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"*.uy":true,"uz":true,"com.uz":true,"co.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"*.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--54b7fta0cc":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--mgb9awbf":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"*.za":true,"*.zm":true,"*.zw":true,"biz.at":true,"info.at":true,"priv.at":true,"co.ca":true,"ar.com":true,"br.com":true,"cn.com":true,"de.com":true,"eu.com":true,"gb.com":true,"gr.com":true,"hu.com":true,"jpn.com":true,"kr.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"uk.com":true,"us.com":true,"uy.com":true,"za.com":true,"gb.net":true,"jp.net":true,"se.net":true,"uk.net":true,"ae.org":true,"us.org":true,"com.de":true,"operaunite.com":true,"appspot.com":true,"iki.fi":true,"c.la":true,"za.net":true,"za.org":true,"co.nl":true,"co.no":true,"co.pl":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true}); + +// END of automatically generated file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/store.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/store.js new file mode 100644 index 000000000..f8433dfcb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/lib/store.js @@ -0,0 +1,37 @@ +'use strict'; +/*jshint unused:false */ + +function Store() { +} +exports.Store = Store; + +// Stores may be synchronous, but are still required to use a +// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" +// API that converts from synchronous-callbacks to imperative style. +Store.prototype.synchronous = false; + +Store.prototype.findCookie = function(domain, path, key, cb) { + throw new Error('findCookie is not implemented'); +}; + +Store.prototype.findCookies = function(domain, path, cb) { + throw new Error('findCookies is not implemented'); +}; + +Store.prototype.putCookie = function(cookie, cb) { + throw new Error('putCookie is not implemented'); +}; + +Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error('updateCookie is not implemented'); +}; + +Store.prototype.removeCookie = function(domain, path, key, cb) { + throw new Error('removeCookie is not implemented'); +}; + +Store.prototype.removeCookies = function removeCookies(domain, path, cb) { + throw new Error('removeCookies is not implemented'); +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/LICENSE-MIT.txt b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 000000000..97067e546 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +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/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/README.md new file mode 100644 index 000000000..577f2c7a1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/README.md @@ -0,0 +1,176 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +A robust Punycode converter that fully complies to [RFC 3492](http://tools.ietf.org/html/rfc3492) and [RFC 5891](http://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](http://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc). + +## Installation + +Via [npm](http://npmjs.org/) (only required for Node.js releases older than v0.6.2): + +```bash +npm install punycode +``` + +Via [Bower](http://bower.io/): + +```bash +bower install punycode +``` + +Via [Component](https://github.com/component/component): + +```bash +component install bestiejs/punycode.js +``` + +In a browser: + +```html + +``` + +In [Narwhal](http://narwhaljs.org/), [Node.js](http://nodejs.org/), and [RingoJS](http://ringojs.org/): + +```js +var punycode = require('punycode'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('punycode.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'punycode': 'path/to/punycode' + } + }, + ['punycode'], + function(punycode) { + console.log(punycode); + } +); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that's already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](http://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Unit tests & code coverage + +After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. + +To generate the code coverage report, use `grunt cover`. + +Feel free to fork if you see possible improvements! + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](http://mathiasbynens.be/) | + +## Contributors + +| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | +|---| +| [John-David Dalton](http://allyoucanleet.com/) | + +## License + +Punycode.js is available under the [MIT](http://mths.be/mit) license. diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/package.json new file mode 100644 index 000000000..311294252 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/package.json @@ -0,0 +1,69 @@ +{ + "name": "punycode", + "version": "1.3.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "http://mths.be/punycode", + "main": "punycode.js", + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "licenses": [ + { + "type": "MIT", + "url": "http://mths.be/mit" + } + ], + "author": { + "name": "Mathias Bynens", + "url": "http://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "http://mathiasbynens.be/" + }, + { + "name": "John-David Dalton", + "url": "http://allyoucanleet.com/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/bestiejs/punycode.js.git" + }, + "bugs": { + "url": "https://github.com/bestiejs/punycode.js/issues" + }, + "files": [ + "LICENSE-MIT.txt", + "punycode.js" + ], + "directories": { + "test": "tests" + }, + "scripts": { + "test": "node tests/tests.js" + }, + "devDependencies": { + "coveralls": "^2.10.1", + "grunt": "^0.4.5", + "grunt-contrib-uglify": "^0.5.0", + "grunt-shell": "^0.7.0", + "istanbul": "^0.2.13", + "qunit-extras": "^1.2.0", + "qunitjs": "~1.11.0", + "requirejs": "^2.1.14" + }, + "readme": "# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js)\n\nA robust Punycode converter that fully complies to [RFC 3492](http://tools.ietf.org/html/rfc3492) and [RFC 5891](http://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms.\n\nThis JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:\n\n* [The C example code from RFC 3492](http://tools.ietf.org/html/rfc3492#appendix-C)\n* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)\n* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)\n* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)\n* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))\n\nThis project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc).\n\n## Installation\n\nVia [npm](http://npmjs.org/) (only required for Node.js releases older than v0.6.2):\n\n```bash\nnpm install punycode\n```\n\nVia [Bower](http://bower.io/):\n\n```bash\nbower install punycode\n```\n\nVia [Component](https://github.com/component/component):\n\n```bash\ncomponent install bestiejs/punycode.js\n```\n\nIn a browser:\n\n```html\n\n```\n\nIn [Narwhal](http://narwhaljs.org/), [Node.js](http://nodejs.org/), and [RingoJS](http://ringojs.org/):\n\n```js\nvar punycode = require('punycode');\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('punycode.js');\n```\n\nUsing an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire(\n {\n 'paths': {\n 'punycode': 'path/to/punycode'\n }\n },\n ['punycode'],\n function(punycode) {\n console.log(punycode);\n }\n);\n```\n\n## API\n\n### `punycode.decode(string)`\n\nConverts a Punycode string of ASCII symbols to a string of Unicode symbols.\n\n```js\n// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n```\n\n### `punycode.encode(string)`\n\nConverts a string of Unicode symbols to a Punycode string of ASCII symbols.\n\n```js\n// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n```\n\n### `punycode.toUnicode(input)`\n\nConverts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.\n\n```js\n// decode domain names\npunycode.toUnicode('xn--maana-pta.com');\n// → 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com');\n// → '☃-⌘.com'\n\n// decode email addresses\npunycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');\n// → 'джумла@джpумлатест.bрфa'\n```\n\n### `punycode.toASCII(input)`\n\nConverts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that's already in ASCII.\n\n```js\n// encode domain names\npunycode.toASCII('mañana.com');\n// → 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com');\n// → 'xn----dqo34k.com'\n\n// encode email addresses\npunycode.toASCII('джумла@джpумлатест.bрфa');\n// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'\n```\n\n### `punycode.ucs2`\n\n#### `punycode.ucs2.decode(string)`\n\nCreates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](http://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.\n\n```js\npunycode.ucs2.decode('abc');\n// → [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:\npunycode.ucs2.decode('\\uD834\\uDF06');\n// → [0x1D306]\n```\n\n#### `punycode.ucs2.encode(codePoints)`\n\nCreates a string based on an array of numeric code point values.\n\n```js\npunycode.ucs2.encode([0x61, 0x62, 0x63]);\n// → 'abc'\npunycode.ucs2.encode([0x1D306]);\n// → '\\uD834\\uDF06'\n```\n\n### `punycode.version`\n\nA string representing the current Punycode.js version number.\n\n## Unit tests & code coverage\n\nAfter cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.\n\nOnce that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`.\n\nTo generate the code coverage report, use `grunt cover`.\n\nFeel free to fork if you see possible improvements!\n\n## Author\n\n| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias \"Follow @mathias on Twitter\") |\n|---|\n| [Mathias Bynens](http://mathiasbynens.be/) |\n\n## Contributors\n\n| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton \"Follow @jdalton on Twitter\") |\n|---|\n| [John-David Dalton](http://allyoucanleet.com/) |\n\n## License\n\nPunycode.js is available under the [MIT](http://mths.be/mit) license.\n", + "readmeFilename": "README.md", + "_id": "punycode@1.3.1", + "_shasum": "710afe5123c20a1530b712e3e682b9118fe8058e", + "_from": "punycode@>=0.2.0", + "_resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.1.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/punycode.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/punycode.js new file mode 100644 index 000000000..6ab1df3a0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/node_modules/punycode/punycode.js @@ -0,0 +1,528 @@ +/*! http://mths.be/punycode v1.3.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + var labels = string.split(regexSeparators); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/package.json new file mode 100644 index 000000000..037187169 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/package.json @@ -0,0 +1,47 @@ +{ + "author": { + "name": "GoInstant Inc., a salesforce.com company" + }, + "license": "MIT", + "name": "tough-cookie", + "description": "RFC6265 Cookies and Cookie Jar for node.js", + "keywords": [ + "HTTP", + "cookie", + "cookies", + "set-cookie", + "cookiejar", + "jar", + "RFC6265", + "RFC2965" + ], + "version": "0.12.1", + "homepage": "https://github.com/goinstant/tough-cookie", + "repository": { + "type": "git", + "url": "git://github.com/goinstant/tough-cookie.git" + }, + "bugs": { + "url": "https://github.com/goinstant/tough-cookie/issues" + }, + "main": "./lib/cookie", + "scripts": { + "test": "vows test.js" + }, + "engines": { + "node": ">=0.4.12" + }, + "dependencies": { + "punycode": ">=0.2.0" + }, + "devDependencies": { + "vows": "0.7.0", + "async": ">=0.1.12" + }, + "readme": "[RFC6265](http://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js\n\n![Tough Cookie](http://www.goinstant.com.s3.amazonaws.com/tough-cookie.jpg)\n\n[![Build Status](https://travis-ci.org/goinstant/node-cookie.png?branch=master)](https://travis-ci.org/goinstant/node-cookie)\n\n[![NPM Stats](https://nodei.co/npm/tough-cookie.png?downloads=true&stars=true)](https://npmjs.org/package/tough-cookie)\n![NPM Downloads](https://nodei.co/npm-dl/tough-cookie.png?months=9)\n\n# Synopsis\n\n``` javascript\nvar tough = require('tough-cookie'); // note: not 'cookie', 'cookies' or 'node-cookie'\nvar Cookie = tough.Cookie;\nvar cookie = Cookie.parse(header);\ncookie.value = 'somethingdifferent';\nheader = cookie.toString();\n\nvar cookiejar = new tough.CookieJar();\ncookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);\n// ...\ncookiejar.getCookies('http://example.com/otherpath',function(err,cookies) {\n res.headers['cookie'] = cookies.join('; ');\n});\n```\n\n# Installation\n\nIt's _so_ easy!\n\n`npm install tough-cookie`\n\nRequires `punycode`, which should get installed automatically for you. Note that node.js v0.6.2+ bundles punycode by default.\n\nWhy the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken.\n\n# API\n\ntough\n=====\n\nFunctions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be \"bound\".\n\nparseDate(string[,strict])\n-----------------\n\nParse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. If strict is set to true then leading/trailing non-seperator characters around the time part will cause the parsing to fail (e.g. \"Thu, 01 Jan 1970 00:00:010 GMT\" has an extra trailing zero but Chrome, an assumedly RFC-compliant browser, treats this as valid).\n\nformatDate(date)\n----------------\n\nFormat a Date into a RFC1123 string (the RFC6265-recommended format).\n\ncanonicalDomain(str)\n--------------------\n\nTransforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects).\n\ndomainMatch(str,domStr[,canonicalize=true])\n-------------------------------------------\n\nAnswers \"does this real domain match the domain in a cookie?\". The `str` is the \"current\" domain-name and the `domStr` is the \"cookie\" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a \"suffix match\".\n\nThe `canonicalize` parameter will run the other two paramters through `canonicalDomain` or not.\n\ndefaultPath(path)\n-----------------\n\nGiven a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the \"directory\" of a \"file\" in the path, but is specified by Section 5.1.4 of the RFC.\n\nThe `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output.\n\npathMatch(reqPath,cookiePath)\n-----------------------------\n\nAnswers \"does the request-path path-match a given cookie-path?\" as per RFC6265 Section 5.1.4. Returns a boolean.\n\nThis is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`.\n\nparse(header[,strict=false])\n----------------------------\n\nalias for `Cookie.parse(header[,strict])`\n\nfromJSON(string)\n----------------\n\nalias for `Cookie.fromJSON(string)`\n\ngetPublicSuffix(hostname)\n-------------------------\n\nReturns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it.\n\nFor example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`.\n\nFor further information, see http://publicsuffix.org/. This module derives its list from that site.\n\ncookieCompare(a,b)\n------------------\n\nFor use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). Longest `.path`s go first, then sorted oldest to youngest.\n\n``` javascript\nvar cookies = [ /* unsorted array of Cookie objects */ ];\ncookies = cookies.sort(cookieCompare);\n```\n\npermuteDomain(domain)\n---------------------\n\nGenerates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores.\n\n\npermutePath(path)\n-----------------\n\nGenerates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores.\n\nCookie\n======\n\nCookie.parse(header[,strict=false])\n-----------------------------------\n\nParses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. If in strict mode, returns `undefined` if the cookie doesn't follow the guidelines in section 4 of RFC6265. Generally speaking, strict mode can be used to validate your own generated Set-Cookie headers, but acting as a client you want to be lenient and leave strict mode off.\n\nHere's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response:\n\n``` javascript\nif (res.headers['set-cookie'] instanceof Array)\n cookies = res.headers['set-cookie'].map(function (c) { return (Cookie.parse(c)); });\nelse\n cookies = [Cookie.parse(res.headers['set-cookie'])];\n```\n\nCookie.fromJSON(string)\n-----------------------\n\nConvert a JSON string to a `Cookie` object. Does a `JSON.parse()` and converts the `.created`, `.lastAccessed` and `.expires` properties into `Date` objects.\n\nProperties\n==========\n\n * _key_ - string - the name or key of the cookie (default \"\")\n * _value_ - string - the value of the cookie (default \"\")\n * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `\"Infinity\"`). See `setExpires()`\n * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `\"Infinity\"` and `\"-Infinity\"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()`\n * _domain_ - string - the `Domain=` attribute of the cookie\n * _path_ - string - the `Path=` of the cookie\n * _secure_ - boolean - the `Secure` cookie flag\n * _httpOnly_ - boolean - the `HttpOnly` cookie flag\n * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside)\n\nAfter a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes:\n\n * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied)\n * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one.\n * _created_ - `Date` - when this cookie was added to the jar\n * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute.\n\nConstruction([{options}])\n------------\n\nReceives an options object that can contain any Cookie properties, uses the default for unspecified properties.\n\n.toString()\n-----------\n\nencode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`.\n\n.cookieString()\n---------------\n\nencode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '=').\n\n.setExpires(String)\n-------------------\n\nsets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `\"Infinity\"` (a string) is set.\n\n.setMaxAge(number)\n-------------------\n\nsets the maxAge in seconds. Coerces `-Infinity` to `\"-Infinity\"` and `Infinity` to `\"Infinity\"` so it JSON serializes correctly.\n\n.expiryTime([now=Date.now()])\n-----------------------------\n\n.expiryDate([now=Date.now()])\n-----------------------------\n\nexpiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds.\n\nMax-Age takes precedence over Expires (as per the RFC). The `.created` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute.\n\nIf Expires (`.expires`) is set, that's returned.\n\nOtherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for \"Tue, 19 Jan 2038 03:14:07 GMT\" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents).\n\n.TTL([now=Date.now()])\n---------\n\ncompute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply.\n\nThe \"number\" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned.\n\n.canonicalizedDoman()\n---------------------\n\n.cdomain()\n----------\n\nreturn the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters.\n\n.validate()\n-----------\n\nStatus: *IN PROGRESS*. Works for a few things, but is by no means comprehensive.\n\nvalidates cookie attributes for semantic correctness. Useful for \"lint\" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct:\n\n``` javascript\nif (cookie.validate() === true) {\n // it's tasty\n} else {\n // yuck!\n}\n```\n\nCookieJar\n=========\n\nConstruction([store = new MemoryCookieStore()][, rejectPublicSuffixes])\n------------\n\nSimply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used.\n\n\nAttributes\n----------\n\n * _rejectPublicSuffixes_ - boolean - reject cookies with domains like \"com\" and \"co.uk\" (default: `true`)\n\nSince eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods.\n\n.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))\n-------------------------------------------------------------------\n\nAttempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.created`, `.lastAccessed` and `.hostOnly` properties.\n\nThe `options` object can be omitted and can have the following properties:\n\n * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.\n * _secure_ - boolean - autodetect from url - indicates if this is a \"Secure\" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`.\n * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies\n * _strict_ - boolean - default `false` - perform extra checks\n * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. CookieStore errors aren't ignored by this option.\n\nAs per the RFC, the `.hostOnly` property is set if there was no \"Domain=\" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual).\n\n.setCookieSync(cookieOrString, currentUrl, [{options}])\n-------------------------------------------------------\n\nSynchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).\n\n.storeCookie(cookie, [{options},] cb(err,cookie))\n-------------------------------------------------\n\n__REMOVED__ removed in lieu of the CookieStore API below\n\n.getCookies(currentUrl, [{options},] cb(err,cookies))\n-----------------------------------------------------\n\nRetrieve the list of cookies that can be sent in a Cookie header for the current url.\n\nIf an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given.\n\nThe `options` object can be omitted and can have the following properties:\n\n * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.\n * _secure_ - boolean - autodetect from url - indicates if this is a \"Secure\" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`.\n * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies\n * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially).\n * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the CookieStore `fetchCookies` function (the default MemoryCookieStore supports it).\n\nThe `.lastAccessed` property of the returned cookies will have been updated.\n\n.getCookiesSync(currentUrl, [{options}])\n----------------------------------------\n\nSynchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).\n\n.getCookieString(...)\n---------------------\n\nAccepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`.\n\n.getCookieStringSync(...)\n-------------------------\n\nSynchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).\n\n.getSetCookieStrings(...)\n-------------------------\n\nReturns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`.\n\n.getSetCookieStringsSync(...)\n-----------------------------\n\nSynchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).\n\nStore\n=====\n\nBase class for CookieJar stores.\n\n# CookieStore API\n\nThe storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores.\n\nStores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set, then the `*Sync` methods on the CookieJar can be used.\n\nAll `domain` parameters will have been normalized before calling.\n\nThe Cookie store must have all of the following methods.\n\nstore.findCookie(domain, path, key, cb(err,cookie))\n---------------------------------------------------\n\nRetrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned.\n\nCallback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error).\n\nstore.findCookies(domain, path, cb(err,cookies))\n------------------------------------------------\n\nLocates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above.\n\nIf no cookies are found, the callback MUST be passed an empty array.\n\nThe resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done.\n\nAs of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only).\n\nstore.putCookie(cookie, cb(err))\n--------------------------------\n\nAdds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur.\n\nThe `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties.\n\nPass an error if the cookie cannot be stored.\n\nstore.updateCookie(oldCookie, newCookie, cb(err))\n-------------------------------------------------\n\nUpdate an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store.\n\nThe `.lastAccessed` property will always be different between the two objects and `.created` will always be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are sorted (or selected for deletion).\n\nStores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object.\n\nThe `newCookie` and `oldCookie` objects MUST NOT be modified.\n\nPass an error if the newCookie cannot be stored.\n\nstore.removeCookie(domain, path, key, cb(err))\n----------------------------------------------\n\nRemove a cookie from the store (see notes on `findCookie` about the uniqueness constraint).\n\nThe implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie.\n\nstore.removeCookies(domain, path, cb(err))\n------------------------------------------\n\nRemoves matching cookies from the store. The `path` paramter is optional, and if missing means all paths in a domain should be removed.\n\nPass an error ONLY if removing any existing cookies failed.\n\n# TODO\n\n * _full_ RFC5890/RFC5891 canonicalization for domains in `cdomain()`\n * the optional `punycode` requirement implements RFC3492, but RFC6265 requires RFC5891\n * better tests for `validate()`?\n\n# Copyright and License\n\n(tl;dr: MIT with some MPL/1.1)\n\nCopyright 2012- GoInstant, Inc. and other contributors. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\nPortions may be licensed under different licenses (in particular public-suffix.txt is MPL/1.1); please read the LICENSE file for full details.\n", + "readmeFilename": "README.md", + "_id": "tough-cookie@0.12.1", + "_shasum": "8220c7e21abd5b13d96804254bd5a81ebf2c7d62", + "_from": "tough-cookie@>=0.12.0", + "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-0.12.1.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/public-suffix.txt b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/public-suffix.txt new file mode 100644 index 000000000..2c2013127 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/public-suffix.txt @@ -0,0 +1,5229 @@ +// ***** BEGIN LICENSE BLOCK ***** +// Version: MPL 1.1/GPL 2.0/LGPL 2.1 +// +// The contents of this file are subject to the Mozilla Public License Version +// 1.1 (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// http://www.mozilla.org/MPL/ +// +// Software distributed under the License is distributed on an "AS IS" basis, +// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +// for the specific language governing rights and limitations under the +// License. +// +// The Original Code is the Public Suffix List. +// +// The Initial Developer of the Original Code is +// Jo Hermans . +// Portions created by the Initial Developer are Copyright (C) 2007 +// the Initial Developer. All Rights Reserved. +// +// Contributor(s): +// Ruben Arakelyan +// Gervase Markham +// Pamela Greene +// David Triendl +// Jothan Frakes +// The kind representatives of many TLD registries +// +// Alternatively, the contents of this file may be used under the terms of +// either the GNU General Public License Version 2 or later (the "GPL"), or +// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +// in which case the provisions of the GPL or the LGPL are applicable instead +// of those above. If you wish to allow use of your version of this file only +// under the terms of either the GPL or the LGPL, and not to allow others to +// use your version of this file under the terms of the MPL, indicate your +// decision by deleting the provisions above and replace them with the notice +// and other provisions required by the GPL or the LGPL. If you do not delete +// the provisions above, a recipient may use your version of this file under +// the terms of any one of the MPL, the GPL or the LGPL. +// +// ***** END LICENSE BLOCK ***** + +// ===BEGIN ICANN DOMAINS=== + +// ac : http://en.wikipedia.org/wiki/.ac +ac +com.ac +edu.ac +gov.ac +net.ac +mil.ac +org.ac + +// ad : http://en.wikipedia.org/wiki/.ad +ad +nom.ad + +// ae : http://en.wikipedia.org/wiki/.ae +// see also: "Domain Name Eligibility Policy" at http://www.aeda.ae/eng/aepolicy.php +ae +co.ae +net.ae +org.ae +sch.ae +ac.ae +gov.ae +mil.ae + +// aero : see http://www.information.aero/index.php?id=66 +aero +accident-investigation.aero +accident-prevention.aero +aerobatic.aero +aeroclub.aero +aerodrome.aero +agents.aero +aircraft.aero +airline.aero +airport.aero +air-surveillance.aero +airtraffic.aero +air-traffic-control.aero +ambulance.aero +amusement.aero +association.aero +author.aero +ballooning.aero +broker.aero +caa.aero +cargo.aero +catering.aero +certification.aero +championship.aero +charter.aero +civilaviation.aero +club.aero +conference.aero +consultant.aero +consulting.aero +control.aero +council.aero +crew.aero +design.aero +dgca.aero +educator.aero +emergency.aero +engine.aero +engineer.aero +entertainment.aero +equipment.aero +exchange.aero +express.aero +federation.aero +flight.aero +freight.aero +fuel.aero +gliding.aero +government.aero +groundhandling.aero +group.aero +hanggliding.aero +homebuilt.aero +insurance.aero +journal.aero +journalist.aero +leasing.aero +logistics.aero +magazine.aero +maintenance.aero +marketplace.aero +media.aero +microlight.aero +modelling.aero +navigation.aero +parachuting.aero +paragliding.aero +passenger-association.aero +pilot.aero +press.aero +production.aero +recreation.aero +repbody.aero +res.aero +research.aero +rotorcraft.aero +safety.aero +scientist.aero +services.aero +show.aero +skydiving.aero +software.aero +student.aero +taxi.aero +trader.aero +trading.aero +trainer.aero +union.aero +workinggroup.aero +works.aero + +// af : http://www.nic.af/help.jsp +af +gov.af +com.af +org.af +net.af +edu.af + +// ag : http://www.nic.ag/prices.htm +ag +com.ag +org.ag +net.ag +co.ag +nom.ag + +// ai : http://nic.com.ai/ +ai +off.ai +com.ai +net.ai +org.ai + +// al : http://www.ert.gov.al/ert_alb/faq_det.html?Id=31 +al +com.al +edu.al +gov.al +mil.al +net.al +org.al + +// am : http://en.wikipedia.org/wiki/.am +am + +// an : http://www.una.an/an_domreg/default.asp +an +com.an +net.an +org.an +edu.an + +// ao : http://en.wikipedia.org/wiki/.ao +// http://www.dns.ao/REGISTR.DOC +ao +ed.ao +gv.ao +og.ao +co.ao +pb.ao +it.ao + +// aq : http://en.wikipedia.org/wiki/.aq +aq + +// ar : http://en.wikipedia.org/wiki/.ar +*.ar +!congresodelalengua3.ar +!educ.ar +!gobiernoelectronico.ar +!mecon.ar +!nacion.ar +!nic.ar +!promocion.ar +!retina.ar +!uba.ar + +// arpa : http://en.wikipedia.org/wiki/.arpa +// Confirmed by registry 2008-06-18 +e164.arpa +in-addr.arpa +ip6.arpa +iris.arpa +uri.arpa +urn.arpa + +// as : http://en.wikipedia.org/wiki/.as +as +gov.as + +// asia : http://en.wikipedia.org/wiki/.asia +asia + +// at : http://en.wikipedia.org/wiki/.at +// Confirmed by registry 2008-06-17 +at +ac.at +co.at +gv.at +or.at + +// au : http://en.wikipedia.org/wiki/.au +// http://www.auda.org.au/ +// 2LDs +com.au +net.au +org.au +edu.au +gov.au +csiro.au +asn.au +id.au +// Historic 2LDs (closed to new registration, but sites still exist) +info.au +conf.au +oz.au +// CGDNs - http://www.cgdn.org.au/ +act.au +nsw.au +nt.au +qld.au +sa.au +tas.au +vic.au +wa.au +// 3LDs +act.edu.au +nsw.edu.au +nt.edu.au +qld.edu.au +sa.edu.au +tas.edu.au +vic.edu.au +wa.edu.au +act.gov.au +// Removed at request of Shae.Donelan@services.nsw.gov.au, 2010-03-04 +// nsw.gov.au +nt.gov.au +qld.gov.au +sa.gov.au +tas.gov.au +vic.gov.au +wa.gov.au + +// aw : http://en.wikipedia.org/wiki/.aw +aw +com.aw + +// ax : http://en.wikipedia.org/wiki/.ax +ax + +// az : http://en.wikipedia.org/wiki/.az +az +com.az +net.az +int.az +gov.az +org.az +edu.az +info.az +pp.az +mil.az +name.az +pro.az +biz.az + +// ba : http://en.wikipedia.org/wiki/.ba +ba +org.ba +net.ba +edu.ba +gov.ba +mil.ba +unsa.ba +unbi.ba +co.ba +com.ba +rs.ba + +// bb : http://en.wikipedia.org/wiki/.bb +bb +biz.bb +com.bb +edu.bb +gov.bb +info.bb +net.bb +org.bb +store.bb + +// bd : http://en.wikipedia.org/wiki/.bd +*.bd + +// be : http://en.wikipedia.org/wiki/.be +// Confirmed by registry 2008-06-08 +be +ac.be + +// bf : http://en.wikipedia.org/wiki/.bf +bf +gov.bf + +// bg : http://en.wikipedia.org/wiki/.bg +// https://www.register.bg/user/static/rules/en/index.html +bg +a.bg +b.bg +c.bg +d.bg +e.bg +f.bg +g.bg +h.bg +i.bg +j.bg +k.bg +l.bg +m.bg +n.bg +o.bg +p.bg +q.bg +r.bg +s.bg +t.bg +u.bg +v.bg +w.bg +x.bg +y.bg +z.bg +0.bg +1.bg +2.bg +3.bg +4.bg +5.bg +6.bg +7.bg +8.bg +9.bg + +// bh : http://en.wikipedia.org/wiki/.bh +bh +com.bh +edu.bh +net.bh +org.bh +gov.bh + +// bi : http://en.wikipedia.org/wiki/.bi +// http://whois.nic.bi/ +bi +co.bi +com.bi +edu.bi +or.bi +org.bi + +// biz : http://en.wikipedia.org/wiki/.biz +biz + +// bj : http://en.wikipedia.org/wiki/.bj +bj +asso.bj +barreau.bj +gouv.bj + +// bm : http://www.bermudanic.bm/dnr-text.txt +bm +com.bm +edu.bm +gov.bm +net.bm +org.bm + +// bn : http://en.wikipedia.org/wiki/.bn +*.bn + +// bo : http://www.nic.bo/ +bo +com.bo +edu.bo +gov.bo +gob.bo +int.bo +org.bo +net.bo +mil.bo +tv.bo + +// br : http://registro.br/dominio/dpn.html +// Updated by registry 2011-03-01 +br +adm.br +adv.br +agr.br +am.br +arq.br +art.br +ato.br +b.br +bio.br +blog.br +bmd.br +can.br +cim.br +cng.br +cnt.br +com.br +coop.br +ecn.br +edu.br +emp.br +eng.br +esp.br +etc.br +eti.br +far.br +flog.br +fm.br +fnd.br +fot.br +fst.br +g12.br +ggf.br +gov.br +imb.br +ind.br +inf.br +jor.br +jus.br +lel.br +mat.br +med.br +mil.br +mus.br +net.br +nom.br +not.br +ntr.br +odo.br +org.br +ppg.br +pro.br +psc.br +psi.br +qsl.br +radio.br +rec.br +slg.br +srv.br +taxi.br +teo.br +tmp.br +trd.br +tur.br +tv.br +vet.br +vlog.br +wiki.br +zlg.br + +// bs : http://www.nic.bs/rules.html +bs +com.bs +net.bs +org.bs +edu.bs +gov.bs + +// bt : http://en.wikipedia.org/wiki/.bt +bt +com.bt +edu.bt +gov.bt +net.bt +org.bt + +// bv : No registrations at this time. +// Submitted by registry 2006-06-16 + +// bw : http://en.wikipedia.org/wiki/.bw +// http://www.gobin.info/domainname/bw.doc +// list of other 2nd level tlds ? +bw +co.bw +org.bw + +// by : http://en.wikipedia.org/wiki/.by +// http://tld.by/rules_2006_en.html +// list of other 2nd level tlds ? +by +gov.by +mil.by +// Official information does not indicate that com.by is a reserved +// second-level domain, but it's being used as one (see www.google.com.by and +// www.yahoo.com.by, for example), so we list it here for safety's sake. +com.by + +// http://hoster.by/ +of.by + +// bz : http://en.wikipedia.org/wiki/.bz +// http://www.belizenic.bz/ +bz +com.bz +net.bz +org.bz +edu.bz +gov.bz + +// ca : http://en.wikipedia.org/wiki/.ca +ca +// ca geographical names +ab.ca +bc.ca +mb.ca +nb.ca +nf.ca +nl.ca +ns.ca +nt.ca +nu.ca +on.ca +pe.ca +qc.ca +sk.ca +yk.ca +// gc.ca: http://en.wikipedia.org/wiki/.gc.ca +// see also: http://registry.gc.ca/en/SubdomainFAQ +gc.ca + +// cat : http://en.wikipedia.org/wiki/.cat +cat + +// cc : http://en.wikipedia.org/wiki/.cc +cc + +// cd : http://en.wikipedia.org/wiki/.cd +// see also: https://www.nic.cd/domain/insertDomain_2.jsp?act=1 +cd +gov.cd + +// cf : http://en.wikipedia.org/wiki/.cf +cf + +// cg : http://en.wikipedia.org/wiki/.cg +cg + +// ch : http://en.wikipedia.org/wiki/.ch +ch + +// ci : http://en.wikipedia.org/wiki/.ci +// http://www.nic.ci/index.php?page=charte +ci +org.ci +or.ci +com.ci +co.ci +edu.ci +ed.ci +ac.ci +net.ci +go.ci +asso.ci +aéroport.ci +int.ci +presse.ci +md.ci +gouv.ci + +// ck : http://en.wikipedia.org/wiki/.ck +*.ck +!www.ck + +// cl : http://en.wikipedia.org/wiki/.cl +cl +gov.cl +gob.cl +co.cl +mil.cl + +// cm : http://en.wikipedia.org/wiki/.cm +cm +gov.cm + +// cn : http://en.wikipedia.org/wiki/.cn +// Submitted by registry 2008-06-11 +cn +ac.cn +com.cn +edu.cn +gov.cn +net.cn +org.cn +mil.cn +公司.cn +网络.cn +網絡.cn +// cn geographic names +ah.cn +bj.cn +cq.cn +fj.cn +gd.cn +gs.cn +gz.cn +gx.cn +ha.cn +hb.cn +he.cn +hi.cn +hl.cn +hn.cn +jl.cn +js.cn +jx.cn +ln.cn +nm.cn +nx.cn +qh.cn +sc.cn +sd.cn +sh.cn +sn.cn +sx.cn +tj.cn +xj.cn +xz.cn +yn.cn +zj.cn +hk.cn +mo.cn +tw.cn + +// co : http://en.wikipedia.org/wiki/.co +// Submitted by registry 2008-06-11 +co +arts.co +com.co +edu.co +firm.co +gov.co +info.co +int.co +mil.co +net.co +nom.co +org.co +rec.co +web.co + +// com : http://en.wikipedia.org/wiki/.com +com + +// coop : http://en.wikipedia.org/wiki/.coop +coop + +// cr : http://www.nic.cr/niccr_publico/showRegistroDominiosScreen.do +cr +ac.cr +co.cr +ed.cr +fi.cr +go.cr +or.cr +sa.cr + +// cu : http://en.wikipedia.org/wiki/.cu +cu +com.cu +edu.cu +org.cu +net.cu +gov.cu +inf.cu + +// cv : http://en.wikipedia.org/wiki/.cv +cv + +// cx : http://en.wikipedia.org/wiki/.cx +// list of other 2nd level tlds ? +cx +gov.cx + +// cy : http://en.wikipedia.org/wiki/.cy +*.cy + +// cz : http://en.wikipedia.org/wiki/.cz +cz + +// de : http://en.wikipedia.org/wiki/.de +// Confirmed by registry (with technical +// reservations) 2008-07-01 +de + +// dj : http://en.wikipedia.org/wiki/.dj +dj + +// dk : http://en.wikipedia.org/wiki/.dk +// Confirmed by registry 2008-06-17 +dk + +// dm : http://en.wikipedia.org/wiki/.dm +dm +com.dm +net.dm +org.dm +edu.dm +gov.dm + +// do : http://en.wikipedia.org/wiki/.do +do +art.do +com.do +edu.do +gob.do +gov.do +mil.do +net.do +org.do +sld.do +web.do + +// dz : http://en.wikipedia.org/wiki/.dz +dz +com.dz +org.dz +net.dz +gov.dz +edu.dz +asso.dz +pol.dz +art.dz + +// ec : http://www.nic.ec/reg/paso1.asp +// Submitted by registry 2008-07-04 +ec +com.ec +info.ec +net.ec +fin.ec +k12.ec +med.ec +pro.ec +org.ec +edu.ec +gov.ec +gob.ec +mil.ec + +// edu : http://en.wikipedia.org/wiki/.edu +edu + +// ee : http://www.eenet.ee/EENet/dom_reeglid.html#lisa_B +ee +edu.ee +gov.ee +riik.ee +lib.ee +med.ee +com.ee +pri.ee +aip.ee +org.ee +fie.ee + +// eg : http://en.wikipedia.org/wiki/.eg +eg +com.eg +edu.eg +eun.eg +gov.eg +mil.eg +name.eg +net.eg +org.eg +sci.eg + +// er : http://en.wikipedia.org/wiki/.er +*.er + +// es : https://www.nic.es/site_ingles/ingles/dominios/index.html +es +com.es +nom.es +org.es +gob.es +edu.es + +// et : http://en.wikipedia.org/wiki/.et +*.et + +// eu : http://en.wikipedia.org/wiki/.eu +eu + +// fi : http://en.wikipedia.org/wiki/.fi +fi +// aland.fi : http://en.wikipedia.org/wiki/.ax +// This domain is being phased out in favor of .ax. As there are still many +// domains under aland.fi, we still keep it on the list until aland.fi is +// completely removed. +// TODO: Check for updates (expected to be phased out around Q1/2009) +aland.fi + +// fj : http://en.wikipedia.org/wiki/.fj +*.fj + +// fk : http://en.wikipedia.org/wiki/.fk +*.fk + +// fm : http://en.wikipedia.org/wiki/.fm +fm + +// fo : http://en.wikipedia.org/wiki/.fo +fo + +// fr : http://www.afnic.fr/ +// domaines descriptifs : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-descriptifs +fr +com.fr +asso.fr +nom.fr +prd.fr +presse.fr +tm.fr +// domaines sectoriels : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-sectoriels +aeroport.fr +assedic.fr +avocat.fr +avoues.fr +cci.fr +chambagri.fr +chirurgiens-dentistes.fr +experts-comptables.fr +geometre-expert.fr +gouv.fr +greta.fr +huissier-justice.fr +medecin.fr +notaires.fr +pharmacien.fr +port.fr +veterinaire.fr + +// ga : http://en.wikipedia.org/wiki/.ga +ga + +// gb : This registry is effectively dormant +// Submitted by registry 2008-06-12 + +// gd : http://en.wikipedia.org/wiki/.gd +gd + +// ge : http://www.nic.net.ge/policy_en.pdf +ge +com.ge +edu.ge +gov.ge +org.ge +mil.ge +net.ge +pvt.ge + +// gf : http://en.wikipedia.org/wiki/.gf +gf + +// gg : http://www.channelisles.net/applic/avextn.shtml +gg +co.gg +org.gg +net.gg +sch.gg +gov.gg + +// gh : http://en.wikipedia.org/wiki/.gh +// see also: http://www.nic.gh/reg_now.php +// Although domains directly at second level are not possible at the moment, +// they have been possible for some time and may come back. +gh +com.gh +edu.gh +gov.gh +org.gh +mil.gh + +// gi : http://www.nic.gi/rules.html +gi +com.gi +ltd.gi +gov.gi +mod.gi +edu.gi +org.gi + +// gl : http://en.wikipedia.org/wiki/.gl +// http://nic.gl +gl + +// gm : http://www.nic.gm/htmlpages%5Cgm-policy.htm +gm + +// gn : http://psg.com/dns/gn/gn.txt +// Submitted by registry 2008-06-17 +ac.gn +com.gn +edu.gn +gov.gn +org.gn +net.gn + +// gov : http://en.wikipedia.org/wiki/.gov +gov + +// gp : http://www.nic.gp/index.php?lang=en +gp +com.gp +net.gp +mobi.gp +edu.gp +org.gp +asso.gp + +// gq : http://en.wikipedia.org/wiki/.gq +gq + +// gr : https://grweb.ics.forth.gr/english/1617-B-2005.html +// Submitted by registry 2008-06-09 +gr +com.gr +edu.gr +net.gr +org.gr +gov.gr + +// gs : http://en.wikipedia.org/wiki/.gs +gs + +// gt : http://www.gt/politicas.html +*.gt +!www.gt + +// gu : http://gadao.gov.gu/registration.txt +*.gu + +// gw : http://en.wikipedia.org/wiki/.gw +gw + +// gy : http://en.wikipedia.org/wiki/.gy +// http://registry.gy/ +gy +co.gy +com.gy +net.gy + +// hk : https://www.hkdnr.hk +// Submitted by registry 2008-06-11 +hk +com.hk +edu.hk +gov.hk +idv.hk +net.hk +org.hk +公司.hk +教育.hk +敎育.hk +政府.hk +個人.hk +个人.hk +箇人.hk +網络.hk +网络.hk +组織.hk +網絡.hk +网絡.hk +组织.hk +組織.hk +組织.hk + +// hm : http://en.wikipedia.org/wiki/.hm +hm + +// hn : http://www.nic.hn/politicas/ps02,,05.html +hn +com.hn +edu.hn +org.hn +net.hn +mil.hn +gob.hn + +// hr : http://www.dns.hr/documents/pdf/HRTLD-regulations.pdf +hr +iz.hr +from.hr +name.hr +com.hr + +// ht : http://www.nic.ht/info/charte.cfm +ht +com.ht +shop.ht +firm.ht +info.ht +adult.ht +net.ht +pro.ht +org.ht +med.ht +art.ht +coop.ht +pol.ht +asso.ht +edu.ht +rel.ht +gouv.ht +perso.ht + +// hu : http://www.domain.hu/domain/English/sld.html +// Confirmed by registry 2008-06-12 +hu +co.hu +info.hu +org.hu +priv.hu +sport.hu +tm.hu +2000.hu +agrar.hu +bolt.hu +casino.hu +city.hu +erotica.hu +erotika.hu +film.hu +forum.hu +games.hu +hotel.hu +ingatlan.hu +jogasz.hu +konyvelo.hu +lakas.hu +media.hu +news.hu +reklam.hu +sex.hu +shop.hu +suli.hu +szex.hu +tozsde.hu +utazas.hu +video.hu + +// id : http://en.wikipedia.org/wiki/.id +// see also: https://register.pandi.or.id/ +id +ac.id +co.id +go.id +mil.id +net.id +or.id +sch.id +web.id + +// ie : http://en.wikipedia.org/wiki/.ie +ie +gov.ie + +// il : http://en.wikipedia.org/wiki/.il +*.il + +// im : https://www.nic.im/pdfs/imfaqs.pdf +im +co.im +ltd.co.im +plc.co.im +net.im +gov.im +org.im +nic.im +ac.im + +// in : http://en.wikipedia.org/wiki/.in +// see also: http://www.inregistry.in/policies/ +// Please note, that nic.in is not an offical eTLD, but used by most +// government institutions. +in +co.in +firm.in +net.in +org.in +gen.in +ind.in +nic.in +ac.in +edu.in +res.in +gov.in +mil.in + +// info : http://en.wikipedia.org/wiki/.info +info + +// int : http://en.wikipedia.org/wiki/.int +// Confirmed by registry 2008-06-18 +int +eu.int + +// io : http://www.nic.io/rules.html +// list of other 2nd level tlds ? +io +com.io + +// iq : http://www.cmc.iq/english/iq/iqregister1.htm +iq +gov.iq +edu.iq +mil.iq +com.iq +org.iq +net.iq + +// ir : http://www.nic.ir/Terms_and_Conditions_ir,_Appendix_1_Domain_Rules +// Also see http://www.nic.ir/Internationalized_Domain_Names +// Two .ir entries added at request of , 2010-04-16 +ir +ac.ir +co.ir +gov.ir +id.ir +net.ir +org.ir +sch.ir +// xn--mgba3a4f16a.ir (.ir, Persian YEH) +ایران.ir +// xn--mgba3a4fra.ir (.ir, Arabic YEH) +ايران.ir + +// is : http://www.isnic.is/domain/rules.php +// Confirmed by registry 2008-12-06 +is +net.is +com.is +edu.is +gov.is +org.is +int.is + +// it : http://en.wikipedia.org/wiki/.it +it +gov.it +edu.it +// list of reserved geo-names : +// http://www.nic.it/documenti/regolamenti-e-linee-guida/regolamento-assegnazione-versione-6.0.pdf +// (There is also a list of reserved geo-names corresponding to Italian +// municipalities : http://www.nic.it/documenti/appendice-c.pdf , but it is +// not included here.) +agrigento.it +ag.it +alessandria.it +al.it +ancona.it +an.it +aosta.it +aoste.it +ao.it +arezzo.it +ar.it +ascoli-piceno.it +ascolipiceno.it +ap.it +asti.it +at.it +avellino.it +av.it +bari.it +ba.it +andria-barletta-trani.it +andriabarlettatrani.it +trani-barletta-andria.it +tranibarlettaandria.it +barletta-trani-andria.it +barlettatraniandria.it +andria-trani-barletta.it +andriatranibarletta.it +trani-andria-barletta.it +traniandriabarletta.it +bt.it +belluno.it +bl.it +benevento.it +bn.it +bergamo.it +bg.it +biella.it +bi.it +bologna.it +bo.it +bolzano.it +bozen.it +balsan.it +alto-adige.it +altoadige.it +suedtirol.it +bz.it +brescia.it +bs.it +brindisi.it +br.it +cagliari.it +ca.it +caltanissetta.it +cl.it +campobasso.it +cb.it +carboniaiglesias.it +carbonia-iglesias.it +iglesias-carbonia.it +iglesiascarbonia.it +ci.it +caserta.it +ce.it +catania.it +ct.it +catanzaro.it +cz.it +chieti.it +ch.it +como.it +co.it +cosenza.it +cs.it +cremona.it +cr.it +crotone.it +kr.it +cuneo.it +cn.it +dell-ogliastra.it +dellogliastra.it +ogliastra.it +og.it +enna.it +en.it +ferrara.it +fe.it +fermo.it +fm.it +firenze.it +florence.it +fi.it +foggia.it +fg.it +forli-cesena.it +forlicesena.it +cesena-forli.it +cesenaforli.it +fc.it +frosinone.it +fr.it +genova.it +genoa.it +ge.it +gorizia.it +go.it +grosseto.it +gr.it +imperia.it +im.it +isernia.it +is.it +laquila.it +aquila.it +aq.it +la-spezia.it +laspezia.it +sp.it +latina.it +lt.it +lecce.it +le.it +lecco.it +lc.it +livorno.it +li.it +lodi.it +lo.it +lucca.it +lu.it +macerata.it +mc.it +mantova.it +mn.it +massa-carrara.it +massacarrara.it +carrara-massa.it +carraramassa.it +ms.it +matera.it +mt.it +medio-campidano.it +mediocampidano.it +campidano-medio.it +campidanomedio.it +vs.it +messina.it +me.it +milano.it +milan.it +mi.it +modena.it +mo.it +monza.it +monza-brianza.it +monzabrianza.it +monzaebrianza.it +monzaedellabrianza.it +monza-e-della-brianza.it +mb.it +napoli.it +naples.it +na.it +novara.it +no.it +nuoro.it +nu.it +oristano.it +or.it +padova.it +padua.it +pd.it +palermo.it +pa.it +parma.it +pr.it +pavia.it +pv.it +perugia.it +pg.it +pescara.it +pe.it +pesaro-urbino.it +pesarourbino.it +urbino-pesaro.it +urbinopesaro.it +pu.it +piacenza.it +pc.it +pisa.it +pi.it +pistoia.it +pt.it +pordenone.it +pn.it +potenza.it +pz.it +prato.it +po.it +ragusa.it +rg.it +ravenna.it +ra.it +reggio-calabria.it +reggiocalabria.it +rc.it +reggio-emilia.it +reggioemilia.it +re.it +rieti.it +ri.it +rimini.it +rn.it +roma.it +rome.it +rm.it +rovigo.it +ro.it +salerno.it +sa.it +sassari.it +ss.it +savona.it +sv.it +siena.it +si.it +siracusa.it +sr.it +sondrio.it +so.it +taranto.it +ta.it +tempio-olbia.it +tempioolbia.it +olbia-tempio.it +olbiatempio.it +ot.it +teramo.it +te.it +terni.it +tr.it +torino.it +turin.it +to.it +trapani.it +tp.it +trento.it +trentino.it +tn.it +treviso.it +tv.it +trieste.it +ts.it +udine.it +ud.it +varese.it +va.it +venezia.it +venice.it +ve.it +verbania.it +vb.it +vercelli.it +vc.it +verona.it +vr.it +vibo-valentia.it +vibovalentia.it +vv.it +vicenza.it +vi.it +viterbo.it +vt.it + +// je : http://www.channelisles.net/applic/avextn.shtml +je +co.je +org.je +net.je +sch.je +gov.je + +// jm : http://www.com.jm/register.html +*.jm + +// jo : http://www.dns.jo/Registration_policy.aspx +jo +com.jo +org.jo +net.jo +edu.jo +sch.jo +gov.jo +mil.jo +name.jo + +// jobs : http://en.wikipedia.org/wiki/.jobs +jobs + +// jp : http://en.wikipedia.org/wiki/.jp +// http://jprs.co.jp/en/jpdomain.html +// Submitted by registry 2008-06-11 +// Updated by registry 2008-12-04 +jp +// jp organizational type names +ac.jp +ad.jp +co.jp +ed.jp +go.jp +gr.jp +lg.jp +ne.jp +or.jp +// jp geographic type names +// http://jprs.jp/doc/rule/saisoku-1.html +*.aichi.jp +*.akita.jp +*.aomori.jp +*.chiba.jp +*.ehime.jp +*.fukui.jp +*.fukuoka.jp +*.fukushima.jp +*.gifu.jp +*.gunma.jp +*.hiroshima.jp +*.hokkaido.jp +*.hyogo.jp +*.ibaraki.jp +*.ishikawa.jp +*.iwate.jp +*.kagawa.jp +*.kagoshima.jp +*.kanagawa.jp +*.kawasaki.jp +*.kitakyushu.jp +*.kobe.jp +*.kochi.jp +*.kumamoto.jp +*.kyoto.jp +*.mie.jp +*.miyagi.jp +*.miyazaki.jp +*.nagano.jp +*.nagasaki.jp +*.nagoya.jp +*.nara.jp +*.niigata.jp +*.oita.jp +*.okayama.jp +*.okinawa.jp +*.osaka.jp +*.saga.jp +*.saitama.jp +*.sapporo.jp +*.sendai.jp +*.shiga.jp +*.shimane.jp +*.shizuoka.jp +*.tochigi.jp +*.tokushima.jp +*.tokyo.jp +*.tottori.jp +*.toyama.jp +*.wakayama.jp +*.yamagata.jp +*.yamaguchi.jp +*.yamanashi.jp +*.yokohama.jp +!metro.tokyo.jp +!pref.aichi.jp +!pref.akita.jp +!pref.aomori.jp +!pref.chiba.jp +!pref.ehime.jp +!pref.fukui.jp +!pref.fukuoka.jp +!pref.fukushima.jp +!pref.gifu.jp +!pref.gunma.jp +!pref.hiroshima.jp +!pref.hokkaido.jp +!pref.hyogo.jp +!pref.ibaraki.jp +!pref.ishikawa.jp +!pref.iwate.jp +!pref.kagawa.jp +!pref.kagoshima.jp +!pref.kanagawa.jp +!pref.kochi.jp +!pref.kumamoto.jp +!pref.kyoto.jp +!pref.mie.jp +!pref.miyagi.jp +!pref.miyazaki.jp +!pref.nagano.jp +!pref.nagasaki.jp +!pref.nara.jp +!pref.niigata.jp +!pref.oita.jp +!pref.okayama.jp +!pref.okinawa.jp +!pref.osaka.jp +!pref.saga.jp +!pref.saitama.jp +!pref.shiga.jp +!pref.shimane.jp +!pref.shizuoka.jp +!pref.tochigi.jp +!pref.tokushima.jp +!pref.tottori.jp +!pref.toyama.jp +!pref.wakayama.jp +!pref.yamagata.jp +!pref.yamaguchi.jp +!pref.yamanashi.jp +!city.chiba.jp +!city.fukuoka.jp +!city.hiroshima.jp +!city.kawasaki.jp +!city.kitakyushu.jp +!city.kobe.jp +!city.kyoto.jp +!city.nagoya.jp +!city.niigata.jp +!city.okayama.jp +!city.osaka.jp +!city.saitama.jp +!city.sapporo.jp +!city.sendai.jp +!city.shizuoka.jp +!city.yokohama.jp + +// ke : http://www.kenic.or.ke/index.php?option=com_content&task=view&id=117&Itemid=145 +*.ke + +// kg : http://www.domain.kg/dmn_n.html +kg +org.kg +net.kg +com.kg +edu.kg +gov.kg +mil.kg + +// kh : http://www.mptc.gov.kh/dns_registration.htm +*.kh + +// ki : http://www.ki/dns/index.html +ki +edu.ki +biz.ki +net.ki +org.ki +gov.ki +info.ki +com.ki + +// km : http://en.wikipedia.org/wiki/.km +// http://www.domaine.km/documents/charte.doc +km +org.km +nom.km +gov.km +prd.km +tm.km +edu.km +mil.km +ass.km +com.km +// These are only mentioned as proposed suggestions at domaine.km, but +// http://en.wikipedia.org/wiki/.km says they're available for registration: +coop.km +asso.km +presse.km +medecin.km +notaires.km +pharmaciens.km +veterinaire.km +gouv.km + +// kn : http://en.wikipedia.org/wiki/.kn +// http://www.dot.kn/domainRules.html +kn +net.kn +org.kn +edu.kn +gov.kn + +// kp : http://www.kcce.kp/en_index.php +com.kp +edu.kp +gov.kp +org.kp +rep.kp +tra.kp + +// kr : http://en.wikipedia.org/wiki/.kr +// see also: http://domain.nida.or.kr/eng/registration.jsp +kr +ac.kr +co.kr +es.kr +go.kr +hs.kr +kg.kr +mil.kr +ms.kr +ne.kr +or.kr +pe.kr +re.kr +sc.kr +// kr geographical names +busan.kr +chungbuk.kr +chungnam.kr +daegu.kr +daejeon.kr +gangwon.kr +gwangju.kr +gyeongbuk.kr +gyeonggi.kr +gyeongnam.kr +incheon.kr +jeju.kr +jeonbuk.kr +jeonnam.kr +seoul.kr +ulsan.kr + +// kw : http://en.wikipedia.org/wiki/.kw +*.kw + +// ky : http://www.icta.ky/da_ky_reg_dom.php +// Confirmed by registry 2008-06-17 +ky +edu.ky +gov.ky +com.ky +org.ky +net.ky + +// kz : http://en.wikipedia.org/wiki/.kz +// see also: http://www.nic.kz/rules/index.jsp +kz +org.kz +edu.kz +net.kz +gov.kz +mil.kz +com.kz + +// la : http://en.wikipedia.org/wiki/.la +// Submitted by registry 2008-06-10 +la +int.la +net.la +info.la +edu.la +gov.la +per.la +com.la +org.la + +// lb : http://en.wikipedia.org/wiki/.lb +// Submitted by registry 2008-06-17 +com.lb +edu.lb +gov.lb +net.lb +org.lb + +// lc : http://en.wikipedia.org/wiki/.lc +// see also: http://www.nic.lc/rules.htm +lc +com.lc +net.lc +co.lc +org.lc +edu.lc +gov.lc + +// li : http://en.wikipedia.org/wiki/.li +li + +// lk : http://www.nic.lk/seclevpr.html +lk +gov.lk +sch.lk +net.lk +int.lk +com.lk +org.lk +edu.lk +ngo.lk +soc.lk +web.lk +ltd.lk +assn.lk +grp.lk +hotel.lk + +// lr : http://psg.com/dns/lr/lr.txt +// Submitted by registry 2008-06-17 +com.lr +edu.lr +gov.lr +org.lr +net.lr + +// ls : http://en.wikipedia.org/wiki/.ls +ls +co.ls +org.ls + +// lt : http://en.wikipedia.org/wiki/.lt +lt +// gov.lt : http://www.gov.lt/index_en.php +gov.lt + +// lu : http://www.dns.lu/en/ +lu + +// lv : http://www.nic.lv/DNS/En/generic.php +lv +com.lv +edu.lv +gov.lv +org.lv +mil.lv +id.lv +net.lv +asn.lv +conf.lv + +// ly : http://www.nic.ly/regulations.php +ly +com.ly +net.ly +gov.ly +plc.ly +edu.ly +sch.ly +med.ly +org.ly +id.ly + +// ma : http://en.wikipedia.org/wiki/.ma +// http://www.anrt.ma/fr/admin/download/upload/file_fr782.pdf +ma +co.ma +net.ma +gov.ma +org.ma +ac.ma +press.ma + +// mc : http://www.nic.mc/ +mc +tm.mc +asso.mc + +// md : http://en.wikipedia.org/wiki/.md +md + +// me : http://en.wikipedia.org/wiki/.me +me +co.me +net.me +org.me +edu.me +ac.me +gov.me +its.me +priv.me + +// mg : http://www.nic.mg/tarif.htm +mg +org.mg +nom.mg +gov.mg +prd.mg +tm.mg +edu.mg +mil.mg +com.mg + +// mh : http://en.wikipedia.org/wiki/.mh +mh + +// mil : http://en.wikipedia.org/wiki/.mil +mil + +// mk : http://en.wikipedia.org/wiki/.mk +// see also: http://dns.marnet.net.mk/postapka.php +mk +com.mk +org.mk +net.mk +edu.mk +gov.mk +inf.mk +name.mk + +// ml : http://www.gobin.info/domainname/ml-template.doc +// see also: http://en.wikipedia.org/wiki/.ml +ml +com.ml +edu.ml +gouv.ml +gov.ml +net.ml +org.ml +presse.ml + +// mm : http://en.wikipedia.org/wiki/.mm +*.mm + +// mn : http://en.wikipedia.org/wiki/.mn +mn +gov.mn +edu.mn +org.mn + +// mo : http://www.monic.net.mo/ +mo +com.mo +net.mo +org.mo +edu.mo +gov.mo + +// mobi : http://en.wikipedia.org/wiki/.mobi +mobi + +// mp : http://www.dot.mp/ +// Confirmed by registry 2008-06-17 +mp + +// mq : http://en.wikipedia.org/wiki/.mq +mq + +// mr : http://en.wikipedia.org/wiki/.mr +mr +gov.mr + +// ms : http://en.wikipedia.org/wiki/.ms +ms + +// mt : https://www.nic.org.mt/dotmt/ +*.mt + +// mu : http://en.wikipedia.org/wiki/.mu +mu +com.mu +net.mu +org.mu +gov.mu +ac.mu +co.mu +or.mu + +// museum : http://about.museum/naming/ +// http://index.museum/ +museum +academy.museum +agriculture.museum +air.museum +airguard.museum +alabama.museum +alaska.museum +amber.museum +ambulance.museum +american.museum +americana.museum +americanantiques.museum +americanart.museum +amsterdam.museum +and.museum +annefrank.museum +anthro.museum +anthropology.museum +antiques.museum +aquarium.museum +arboretum.museum +archaeological.museum +archaeology.museum +architecture.museum +art.museum +artanddesign.museum +artcenter.museum +artdeco.museum +arteducation.museum +artgallery.museum +arts.museum +artsandcrafts.museum +asmatart.museum +assassination.museum +assisi.museum +association.museum +astronomy.museum +atlanta.museum +austin.museum +australia.museum +automotive.museum +aviation.museum +axis.museum +badajoz.museum +baghdad.museum +bahn.museum +bale.museum +baltimore.museum +barcelona.museum +baseball.museum +basel.museum +baths.museum +bauern.museum +beauxarts.museum +beeldengeluid.museum +bellevue.museum +bergbau.museum +berkeley.museum +berlin.museum +bern.museum +bible.museum +bilbao.museum +bill.museum +birdart.museum +birthplace.museum +bonn.museum +boston.museum +botanical.museum +botanicalgarden.museum +botanicgarden.museum +botany.museum +brandywinevalley.museum +brasil.museum +bristol.museum +british.museum +britishcolumbia.museum +broadcast.museum +brunel.museum +brussel.museum +brussels.museum +bruxelles.museum +building.museum +burghof.museum +bus.museum +bushey.museum +cadaques.museum +california.museum +cambridge.museum +can.museum +canada.museum +capebreton.museum +carrier.museum +cartoonart.museum +casadelamoneda.museum +castle.museum +castres.museum +celtic.museum +center.museum +chattanooga.museum +cheltenham.museum +chesapeakebay.museum +chicago.museum +children.museum +childrens.museum +childrensgarden.museum +chiropractic.museum +chocolate.museum +christiansburg.museum +cincinnati.museum +cinema.museum +circus.museum +civilisation.museum +civilization.museum +civilwar.museum +clinton.museum +clock.museum +coal.museum +coastaldefence.museum +cody.museum +coldwar.museum +collection.museum +colonialwilliamsburg.museum +coloradoplateau.museum +columbia.museum +columbus.museum +communication.museum +communications.museum +community.museum +computer.museum +computerhistory.museum +comunicações.museum +contemporary.museum +contemporaryart.museum +convent.museum +copenhagen.museum +corporation.museum +correios-e-telecomunicações.museum +corvette.museum +costume.museum +countryestate.museum +county.museum +crafts.museum +cranbrook.museum +creation.museum +cultural.museum +culturalcenter.museum +culture.museum +cyber.museum +cymru.museum +dali.museum +dallas.museum +database.museum +ddr.museum +decorativearts.museum +delaware.museum +delmenhorst.museum +denmark.museum +depot.museum +design.museum +detroit.museum +dinosaur.museum +discovery.museum +dolls.museum +donostia.museum +durham.museum +eastafrica.museum +eastcoast.museum +education.museum +educational.museum +egyptian.museum +eisenbahn.museum +elburg.museum +elvendrell.museum +embroidery.museum +encyclopedic.museum +england.museum +entomology.museum +environment.museum +environmentalconservation.museum +epilepsy.museum +essex.museum +estate.museum +ethnology.museum +exeter.museum +exhibition.museum +family.museum +farm.museum +farmequipment.museum +farmers.museum +farmstead.museum +field.museum +figueres.museum +filatelia.museum +film.museum +fineart.museum +finearts.museum +finland.museum +flanders.museum +florida.museum +force.museum +fortmissoula.museum +fortworth.museum +foundation.museum +francaise.museum +frankfurt.museum +franziskaner.museum +freemasonry.museum +freiburg.museum +fribourg.museum +frog.museum +fundacio.museum +furniture.museum +gallery.museum +garden.museum +gateway.museum +geelvinck.museum +gemological.museum +geology.museum +georgia.museum +giessen.museum +glas.museum +glass.museum +gorge.museum +grandrapids.museum +graz.museum +guernsey.museum +halloffame.museum +hamburg.museum +handson.museum +harvestcelebration.museum +hawaii.museum +health.museum +heimatunduhren.museum +hellas.museum +helsinki.museum +hembygdsforbund.museum +heritage.museum +histoire.museum +historical.museum +historicalsociety.museum +historichouses.museum +historisch.museum +historisches.museum +history.museum +historyofscience.museum +horology.museum +house.museum +humanities.museum +illustration.museum +imageandsound.museum +indian.museum +indiana.museum +indianapolis.museum +indianmarket.museum +intelligence.museum +interactive.museum +iraq.museum +iron.museum +isleofman.museum +jamison.museum +jefferson.museum +jerusalem.museum +jewelry.museum +jewish.museum +jewishart.museum +jfk.museum +journalism.museum +judaica.museum +judygarland.museum +juedisches.museum +juif.museum +karate.museum +karikatur.museum +kids.museum +koebenhavn.museum +koeln.museum +kunst.museum +kunstsammlung.museum +kunstunddesign.museum +labor.museum +labour.museum +lajolla.museum +lancashire.museum +landes.museum +lans.museum +läns.museum +larsson.museum +lewismiller.museum +lincoln.museum +linz.museum +living.museum +livinghistory.museum +localhistory.museum +london.museum +losangeles.museum +louvre.museum +loyalist.museum +lucerne.museum +luxembourg.museum +luzern.museum +mad.museum +madrid.museum +mallorca.museum +manchester.museum +mansion.museum +mansions.museum +manx.museum +marburg.museum +maritime.museum +maritimo.museum +maryland.museum +marylhurst.museum +media.museum +medical.museum +medizinhistorisches.museum +meeres.museum +memorial.museum +mesaverde.museum +michigan.museum +midatlantic.museum +military.museum +mill.museum +miners.museum +mining.museum +minnesota.museum +missile.museum +missoula.museum +modern.museum +moma.museum +money.museum +monmouth.museum +monticello.museum +montreal.museum +moscow.museum +motorcycle.museum +muenchen.museum +muenster.museum +mulhouse.museum +muncie.museum +museet.museum +museumcenter.museum +museumvereniging.museum +music.museum +national.museum +nationalfirearms.museum +nationalheritage.museum +nativeamerican.museum +naturalhistory.museum +naturalhistorymuseum.museum +naturalsciences.museum +nature.museum +naturhistorisches.museum +natuurwetenschappen.museum +naumburg.museum +naval.museum +nebraska.museum +neues.museum +newhampshire.museum +newjersey.museum +newmexico.museum +newport.museum +newspaper.museum +newyork.museum +niepce.museum +norfolk.museum +north.museum +nrw.museum +nuernberg.museum +nuremberg.museum +nyc.museum +nyny.museum +oceanographic.museum +oceanographique.museum +omaha.museum +online.museum +ontario.museum +openair.museum +oregon.museum +oregontrail.museum +otago.museum +oxford.museum +pacific.museum +paderborn.museum +palace.museum +paleo.museum +palmsprings.museum +panama.museum +paris.museum +pasadena.museum +pharmacy.museum +philadelphia.museum +philadelphiaarea.museum +philately.museum +phoenix.museum +photography.museum +pilots.museum +pittsburgh.museum +planetarium.museum +plantation.museum +plants.museum +plaza.museum +portal.museum +portland.museum +portlligat.museum +posts-and-telecommunications.museum +preservation.museum +presidio.museum +press.museum +project.museum +public.museum +pubol.museum +quebec.museum +railroad.museum +railway.museum +research.museum +resistance.museum +riodejaneiro.museum +rochester.museum +rockart.museum +roma.museum +russia.museum +saintlouis.museum +salem.museum +salvadordali.museum +salzburg.museum +sandiego.museum +sanfrancisco.museum +santabarbara.museum +santacruz.museum +santafe.museum +saskatchewan.museum +satx.museum +savannahga.museum +schlesisches.museum +schoenbrunn.museum +schokoladen.museum +school.museum +schweiz.museum +science.museum +scienceandhistory.museum +scienceandindustry.museum +sciencecenter.museum +sciencecenters.museum +science-fiction.museum +sciencehistory.museum +sciences.museum +sciencesnaturelles.museum +scotland.museum +seaport.museum +settlement.museum +settlers.museum +shell.museum +sherbrooke.museum +sibenik.museum +silk.museum +ski.museum +skole.museum +society.museum +sologne.museum +soundandvision.museum +southcarolina.museum +southwest.museum +space.museum +spy.museum +square.museum +stadt.museum +stalbans.museum +starnberg.museum +state.museum +stateofdelaware.museum +station.museum +steam.museum +steiermark.museum +stjohn.museum +stockholm.museum +stpetersburg.museum +stuttgart.museum +suisse.museum +surgeonshall.museum +surrey.museum +svizzera.museum +sweden.museum +sydney.museum +tank.museum +tcm.museum +technology.museum +telekommunikation.museum +television.museum +texas.museum +textile.museum +theater.museum +time.museum +timekeeping.museum +topology.museum +torino.museum +touch.museum +town.museum +transport.museum +tree.museum +trolley.museum +trust.museum +trustee.museum +uhren.museum +ulm.museum +undersea.museum +university.museum +usa.museum +usantiques.museum +usarts.museum +uscountryestate.museum +usculture.museum +usdecorativearts.museum +usgarden.museum +ushistory.museum +ushuaia.museum +uslivinghistory.museum +utah.museum +uvic.museum +valley.museum +vantaa.museum +versailles.museum +viking.museum +village.museum +virginia.museum +virtual.museum +virtuel.museum +vlaanderen.museum +volkenkunde.museum +wales.museum +wallonie.museum +war.museum +washingtondc.museum +watchandclock.museum +watch-and-clock.museum +western.museum +westfalen.museum +whaling.museum +wildlife.museum +williamsburg.museum +windmill.museum +workshop.museum +york.museum +yorkshire.museum +yosemite.museum +youth.museum +zoological.museum +zoology.museum +ירושלים.museum +иком.museum + +// mv : http://en.wikipedia.org/wiki/.mv +// "mv" included because, contra Wikipedia, google.mv exists. +mv +aero.mv +biz.mv +com.mv +coop.mv +edu.mv +gov.mv +info.mv +int.mv +mil.mv +museum.mv +name.mv +net.mv +org.mv +pro.mv + +// mw : http://www.registrar.mw/ +mw +ac.mw +biz.mw +co.mw +com.mw +coop.mw +edu.mw +gov.mw +int.mw +museum.mw +net.mw +org.mw + +// mx : http://www.nic.mx/ +// Submitted by registry 2008-06-19 +mx +com.mx +org.mx +gob.mx +edu.mx +net.mx + +// my : http://www.mynic.net.my/ +my +com.my +net.my +org.my +gov.my +edu.my +mil.my +name.my + +// mz : http://www.gobin.info/domainname/mz-template.doc +*.mz + +// na : http://www.na-nic.com.na/ +// http://www.info.na/domain/ +na +info.na +pro.na +name.na +school.na +or.na +dr.na +us.na +mx.na +ca.na +in.na +cc.na +tv.na +ws.na +mobi.na +co.na +com.na +org.na + +// name : has 2nd-level tlds, but there's no list of them +name + +// nc : http://www.cctld.nc/ +nc +asso.nc + +// ne : http://en.wikipedia.org/wiki/.ne +ne + +// net : http://en.wikipedia.org/wiki/.net +net + +// nf : http://en.wikipedia.org/wiki/.nf +nf +com.nf +net.nf +per.nf +rec.nf +web.nf +arts.nf +firm.nf +info.nf +other.nf +store.nf + +// ng : http://psg.com/dns/ng/ +// Submitted by registry 2008-06-17 +ac.ng +com.ng +edu.ng +gov.ng +net.ng +org.ng + +// ni : http://www.nic.ni/dominios.htm +*.ni + +// nl : http://www.domain-registry.nl/ace.php/c,728,122,,,,Home.html +// Confirmed by registry (with technical +// reservations) 2008-06-08 +nl + +// BV.nl will be a registry for dutch BV's (besloten vennootschap) +bv.nl + +// no : http://www.norid.no/regelverk/index.en.html +// The Norwegian registry has declined to notify us of updates. The web pages +// referenced below are the official source of the data. There is also an +// announce mailing list: +// https://postlister.uninett.no/sympa/info/norid-diskusjon +no +// Norid generic domains : http://www.norid.no/regelverk/vedlegg-c.en.html +fhs.no +vgs.no +fylkesbibl.no +folkebibl.no +museum.no +idrett.no +priv.no +// Non-Norid generic domains : http://www.norid.no/regelverk/vedlegg-d.en.html +mil.no +stat.no +dep.no +kommune.no +herad.no +// no geographical names : http://www.norid.no/regelverk/vedlegg-b.en.html +// counties +aa.no +ah.no +bu.no +fm.no +hl.no +hm.no +jan-mayen.no +mr.no +nl.no +nt.no +of.no +ol.no +oslo.no +rl.no +sf.no +st.no +svalbard.no +tm.no +tr.no +va.no +vf.no +// primary and lower secondary schools per county +gs.aa.no +gs.ah.no +gs.bu.no +gs.fm.no +gs.hl.no +gs.hm.no +gs.jan-mayen.no +gs.mr.no +gs.nl.no +gs.nt.no +gs.of.no +gs.ol.no +gs.oslo.no +gs.rl.no +gs.sf.no +gs.st.no +gs.svalbard.no +gs.tm.no +gs.tr.no +gs.va.no +gs.vf.no +// cities +akrehamn.no +åkrehamn.no +algard.no +ålgård.no +arna.no +brumunddal.no +bryne.no +bronnoysund.no +brønnøysund.no +drobak.no +drøbak.no +egersund.no +fetsund.no +floro.no +florø.no +fredrikstad.no +hokksund.no +honefoss.no +hønefoss.no +jessheim.no +jorpeland.no +jørpeland.no +kirkenes.no +kopervik.no +krokstadelva.no +langevag.no +langevåg.no +leirvik.no +mjondalen.no +mjøndalen.no +mo-i-rana.no +mosjoen.no +mosjøen.no +nesoddtangen.no +orkanger.no +osoyro.no +osøyro.no +raholt.no +råholt.no +sandnessjoen.no +sandnessjøen.no +skedsmokorset.no +slattum.no +spjelkavik.no +stathelle.no +stavern.no +stjordalshalsen.no +stjørdalshalsen.no +tananger.no +tranby.no +vossevangen.no +// communities +afjord.no +åfjord.no +agdenes.no +al.no +ål.no +alesund.no +ålesund.no +alstahaug.no +alta.no +áltá.no +alaheadju.no +álaheadju.no +alvdal.no +amli.no +åmli.no +amot.no +åmot.no +andebu.no +andoy.no +andøy.no +andasuolo.no +ardal.no +årdal.no +aremark.no +arendal.no +ås.no +aseral.no +åseral.no +asker.no +askim.no +askvoll.no +askoy.no +askøy.no +asnes.no +åsnes.no +audnedaln.no +aukra.no +aure.no +aurland.no +aurskog-holand.no +aurskog-høland.no +austevoll.no +austrheim.no +averoy.no +averøy.no +balestrand.no +ballangen.no +balat.no +bálát.no +balsfjord.no +bahccavuotna.no +báhccavuotna.no +bamble.no +bardu.no +beardu.no +beiarn.no +bajddar.no +bájddar.no +baidar.no +báidár.no +berg.no +bergen.no +berlevag.no +berlevåg.no +bearalvahki.no +bearalváhki.no +bindal.no +birkenes.no +bjarkoy.no +bjarkøy.no +bjerkreim.no +bjugn.no +bodo.no +bodø.no +badaddja.no +bådåddjå.no +budejju.no +bokn.no +bremanger.no +bronnoy.no +brønnøy.no +bygland.no +bykle.no +barum.no +bærum.no +bo.telemark.no +bø.telemark.no +bo.nordland.no +bø.nordland.no +bievat.no +bievát.no +bomlo.no +bømlo.no +batsfjord.no +båtsfjord.no +bahcavuotna.no +báhcavuotna.no +dovre.no +drammen.no +drangedal.no +dyroy.no +dyrøy.no +donna.no +dønna.no +eid.no +eidfjord.no +eidsberg.no +eidskog.no +eidsvoll.no +eigersund.no +elverum.no +enebakk.no +engerdal.no +etne.no +etnedal.no +evenes.no +evenassi.no +evenášši.no +evje-og-hornnes.no +farsund.no +fauske.no +fuossko.no +fuoisku.no +fedje.no +fet.no +finnoy.no +finnøy.no +fitjar.no +fjaler.no +fjell.no +flakstad.no +flatanger.no +flekkefjord.no +flesberg.no +flora.no +fla.no +flå.no +folldal.no +forsand.no +fosnes.no +frei.no +frogn.no +froland.no +frosta.no +frana.no +fræna.no +froya.no +frøya.no +fusa.no +fyresdal.no +forde.no +førde.no +gamvik.no +gangaviika.no +gáŋgaviika.no +gaular.no +gausdal.no +gildeskal.no +gildeskål.no +giske.no +gjemnes.no +gjerdrum.no +gjerstad.no +gjesdal.no +gjovik.no +gjøvik.no +gloppen.no +gol.no +gran.no +grane.no +granvin.no +gratangen.no +grimstad.no +grong.no +kraanghke.no +kråanghke.no +grue.no +gulen.no +hadsel.no +halden.no +halsa.no +hamar.no +hamaroy.no +habmer.no +hábmer.no +hapmir.no +hápmir.no +hammerfest.no +hammarfeasta.no +hámmárfeasta.no +haram.no +hareid.no +harstad.no +hasvik.no +aknoluokta.no +ákŋoluokta.no +hattfjelldal.no +aarborte.no +haugesund.no +hemne.no +hemnes.no +hemsedal.no +heroy.more-og-romsdal.no +herøy.møre-og-romsdal.no +heroy.nordland.no +herøy.nordland.no +hitra.no +hjartdal.no +hjelmeland.no +hobol.no +hobøl.no +hof.no +hol.no +hole.no +holmestrand.no +holtalen.no +holtålen.no +hornindal.no +horten.no +hurdal.no +hurum.no +hvaler.no +hyllestad.no +hagebostad.no +hægebostad.no +hoyanger.no +høyanger.no +hoylandet.no +høylandet.no +ha.no +hå.no +ibestad.no +inderoy.no +inderøy.no +iveland.no +jevnaker.no +jondal.no +jolster.no +jølster.no +karasjok.no +karasjohka.no +kárášjohka.no +karlsoy.no +galsa.no +gálsá.no +karmoy.no +karmøy.no +kautokeino.no +guovdageaidnu.no +klepp.no +klabu.no +klæbu.no +kongsberg.no +kongsvinger.no +kragero.no +kragerø.no +kristiansand.no +kristiansund.no +krodsherad.no +krødsherad.no +kvalsund.no +rahkkeravju.no +ráhkkerávju.no +kvam.no +kvinesdal.no +kvinnherad.no +kviteseid.no +kvitsoy.no +kvitsøy.no +kvafjord.no +kvæfjord.no +giehtavuoatna.no +kvanangen.no +kvænangen.no +navuotna.no +návuotna.no +kafjord.no +kåfjord.no +gaivuotna.no +gáivuotna.no +larvik.no +lavangen.no +lavagis.no +loabat.no +loabát.no +lebesby.no +davvesiida.no +leikanger.no +leirfjord.no +leka.no +leksvik.no +lenvik.no +leangaviika.no +leaŋgaviika.no +lesja.no +levanger.no +lier.no +lierne.no +lillehammer.no +lillesand.no +lindesnes.no +lindas.no +lindås.no +lom.no +loppa.no +lahppi.no +láhppi.no +lund.no +lunner.no +luroy.no +lurøy.no +luster.no +lyngdal.no +lyngen.no +ivgu.no +lardal.no +lerdal.no +lærdal.no +lodingen.no +lødingen.no +lorenskog.no +lørenskog.no +loten.no +løten.no +malvik.no +masoy.no +måsøy.no +muosat.no +muosát.no +mandal.no +marker.no +marnardal.no +masfjorden.no +meland.no +meldal.no +melhus.no +meloy.no +meløy.no +meraker.no +meråker.no +moareke.no +moåreke.no +midsund.no +midtre-gauldal.no +modalen.no +modum.no +molde.no +moskenes.no +moss.no +mosvik.no +malselv.no +målselv.no +malatvuopmi.no +málatvuopmi.no +namdalseid.no +aejrie.no +namsos.no +namsskogan.no +naamesjevuemie.no +nååmesjevuemie.no +laakesvuemie.no +nannestad.no +narvik.no +narviika.no +naustdal.no +nedre-eiker.no +nes.akershus.no +nes.buskerud.no +nesna.no +nesodden.no +nesseby.no +unjarga.no +unjárga.no +nesset.no +nissedal.no +nittedal.no +nord-aurdal.no +nord-fron.no +nord-odal.no +norddal.no +nordkapp.no +davvenjarga.no +davvenjárga.no +nordre-land.no +nordreisa.no +raisa.no +ráisa.no +nore-og-uvdal.no +notodden.no +naroy.no +nærøy.no +notteroy.no +nøtterøy.no +odda.no +oksnes.no +øksnes.no +oppdal.no +oppegard.no +oppegård.no +orkdal.no +orland.no +ørland.no +orskog.no +ørskog.no +orsta.no +ørsta.no +os.hedmark.no +os.hordaland.no +osen.no +osteroy.no +osterøy.no +ostre-toten.no +østre-toten.no +overhalla.no +ovre-eiker.no +øvre-eiker.no +oyer.no +øyer.no +oygarden.no +øygarden.no +oystre-slidre.no +øystre-slidre.no +porsanger.no +porsangu.no +porsáŋgu.no +porsgrunn.no +radoy.no +radøy.no +rakkestad.no +rana.no +ruovat.no +randaberg.no +rauma.no +rendalen.no +rennebu.no +rennesoy.no +rennesøy.no +rindal.no +ringebu.no +ringerike.no +ringsaker.no +rissa.no +risor.no +risør.no +roan.no +rollag.no +rygge.no +ralingen.no +rælingen.no +rodoy.no +rødøy.no +romskog.no +rømskog.no +roros.no +røros.no +rost.no +røst.no +royken.no +røyken.no +royrvik.no +røyrvik.no +rade.no +råde.no +salangen.no +siellak.no +saltdal.no +salat.no +sálát.no +sálat.no +samnanger.no +sande.more-og-romsdal.no +sande.møre-og-romsdal.no +sande.vestfold.no +sandefjord.no +sandnes.no +sandoy.no +sandøy.no +sarpsborg.no +sauda.no +sauherad.no +sel.no +selbu.no +selje.no +seljord.no +sigdal.no +siljan.no +sirdal.no +skaun.no +skedsmo.no +ski.no +skien.no +skiptvet.no +skjervoy.no +skjervøy.no +skierva.no +skiervá.no +skjak.no +skjåk.no +skodje.no +skanland.no +skånland.no +skanit.no +skánit.no +smola.no +smøla.no +snillfjord.no +snasa.no +snåsa.no +snoasa.no +snaase.no +snåase.no +sogndal.no +sokndal.no +sola.no +solund.no +songdalen.no +sortland.no +spydeberg.no +stange.no +stavanger.no +steigen.no +steinkjer.no +stjordal.no +stjørdal.no +stokke.no +stor-elvdal.no +stord.no +stordal.no +storfjord.no +omasvuotna.no +strand.no +stranda.no +stryn.no +sula.no +suldal.no +sund.no +sunndal.no +surnadal.no +sveio.no +svelvik.no +sykkylven.no +sogne.no +søgne.no +somna.no +sømna.no +sondre-land.no +søndre-land.no +sor-aurdal.no +sør-aurdal.no +sor-fron.no +sør-fron.no +sor-odal.no +sør-odal.no +sor-varanger.no +sør-varanger.no +matta-varjjat.no +mátta-várjjat.no +sorfold.no +sørfold.no +sorreisa.no +sørreisa.no +sorum.no +sørum.no +tana.no +deatnu.no +time.no +tingvoll.no +tinn.no +tjeldsund.no +dielddanuorri.no +tjome.no +tjøme.no +tokke.no +tolga.no +torsken.no +tranoy.no +tranøy.no +tromso.no +tromsø.no +tromsa.no +romsa.no +trondheim.no +troandin.no +trysil.no +trana.no +træna.no +trogstad.no +trøgstad.no +tvedestrand.no +tydal.no +tynset.no +tysfjord.no +divtasvuodna.no +divttasvuotna.no +tysnes.no +tysvar.no +tysvær.no +tonsberg.no +tønsberg.no +ullensaker.no +ullensvang.no +ulvik.no +utsira.no +vadso.no +vadsø.no +cahcesuolo.no +čáhcesuolo.no +vaksdal.no +valle.no +vang.no +vanylven.no +vardo.no +vardø.no +varggat.no +várggát.no +vefsn.no +vaapste.no +vega.no +vegarshei.no +vegårshei.no +vennesla.no +verdal.no +verran.no +vestby.no +vestnes.no +vestre-slidre.no +vestre-toten.no +vestvagoy.no +vestvågøy.no +vevelstad.no +vik.no +vikna.no +vindafjord.no +volda.no +voss.no +varoy.no +værøy.no +vagan.no +vågan.no +voagat.no +vagsoy.no +vågsøy.no +vaga.no +vågå.no +valer.ostfold.no +våler.østfold.no +valer.hedmark.no +våler.hedmark.no + +// np : http://www.mos.com.np/register.html +*.np + +// nr : http://cenpac.net.nr/dns/index.html +// Confirmed by registry 2008-06-17 +nr +biz.nr +info.nr +gov.nr +edu.nr +org.nr +net.nr +com.nr + +// nu : http://en.wikipedia.org/wiki/.nu +nu + +// nz : http://en.wikipedia.org/wiki/.nz +*.nz + +// om : http://en.wikipedia.org/wiki/.om +*.om +!mediaphone.om +!nawrastelecom.om +!nawras.om +!omanmobile.om +!omanpost.om +!omantel.om +!rakpetroleum.om +!siemens.om +!songfest.om +!statecouncil.om + +// org : http://en.wikipedia.org/wiki/.org +org + +// pa : http://www.nic.pa/ +// Some additional second level "domains" resolve directly as hostnames, such as +// pannet.pa, so we add a rule for "pa". +pa +ac.pa +gob.pa +com.pa +org.pa +sld.pa +edu.pa +net.pa +ing.pa +abo.pa +med.pa +nom.pa + +// pe : https://www.nic.pe/InformeFinalComision.pdf +pe +edu.pe +gob.pe +nom.pe +mil.pe +org.pe +com.pe +net.pe + +// pf : http://www.gobin.info/domainname/formulaire-pf.pdf +pf +com.pf +org.pf +edu.pf + +// pg : http://en.wikipedia.org/wiki/.pg +*.pg + +// ph : http://www.domains.ph/FAQ2.asp +// Submitted by registry 2008-06-13 +ph +com.ph +net.ph +org.ph +gov.ph +edu.ph +ngo.ph +mil.ph +i.ph + +// pk : http://pk5.pknic.net.pk/pk5/msgNamepk.PK +pk +com.pk +net.pk +edu.pk +org.pk +fam.pk +biz.pk +web.pk +gov.pk +gob.pk +gok.pk +gon.pk +gop.pk +gos.pk +info.pk + +// pl : http://www.dns.pl/english/ +pl +// NASK functional domains (nask.pl / dns.pl) : http://www.dns.pl/english/dns-funk.html +aid.pl +agro.pl +atm.pl +auto.pl +biz.pl +com.pl +edu.pl +gmina.pl +gsm.pl +info.pl +mail.pl +miasta.pl +media.pl +mil.pl +net.pl +nieruchomosci.pl +nom.pl +org.pl +pc.pl +powiat.pl +priv.pl +realestate.pl +rel.pl +sex.pl +shop.pl +sklep.pl +sos.pl +szkola.pl +targi.pl +tm.pl +tourism.pl +travel.pl +turystyka.pl +// ICM functional domains (icm.edu.pl) +6bone.pl +art.pl +mbone.pl +// Government domains (administred by ippt.gov.pl) +gov.pl +uw.gov.pl +um.gov.pl +ug.gov.pl +upow.gov.pl +starostwo.gov.pl +so.gov.pl +sr.gov.pl +po.gov.pl +pa.gov.pl +// other functional domains +ngo.pl +irc.pl +usenet.pl +// NASK geographical domains : http://www.dns.pl/english/dns-regiony.html +augustow.pl +babia-gora.pl +bedzin.pl +beskidy.pl +bialowieza.pl +bialystok.pl +bielawa.pl +bieszczady.pl +boleslawiec.pl +bydgoszcz.pl +bytom.pl +cieszyn.pl +czeladz.pl +czest.pl +dlugoleka.pl +elblag.pl +elk.pl +glogow.pl +gniezno.pl +gorlice.pl +grajewo.pl +ilawa.pl +jaworzno.pl +jelenia-gora.pl +jgora.pl +kalisz.pl +kazimierz-dolny.pl +karpacz.pl +kartuzy.pl +kaszuby.pl +katowice.pl +kepno.pl +ketrzyn.pl +klodzko.pl +kobierzyce.pl +kolobrzeg.pl +konin.pl +konskowola.pl +kutno.pl +lapy.pl +lebork.pl +legnica.pl +lezajsk.pl +limanowa.pl +lomza.pl +lowicz.pl +lubin.pl +lukow.pl +malbork.pl +malopolska.pl +mazowsze.pl +mazury.pl +mielec.pl +mielno.pl +mragowo.pl +naklo.pl +nowaruda.pl +nysa.pl +olawa.pl +olecko.pl +olkusz.pl +olsztyn.pl +opoczno.pl +opole.pl +ostroda.pl +ostroleka.pl +ostrowiec.pl +ostrowwlkp.pl +pila.pl +pisz.pl +podhale.pl +podlasie.pl +polkowice.pl +pomorze.pl +pomorskie.pl +prochowice.pl +pruszkow.pl +przeworsk.pl +pulawy.pl +radom.pl +rawa-maz.pl +rybnik.pl +rzeszow.pl +sanok.pl +sejny.pl +siedlce.pl +slask.pl +slupsk.pl +sosnowiec.pl +stalowa-wola.pl +skoczow.pl +starachowice.pl +stargard.pl +suwalki.pl +swidnica.pl +swiebodzin.pl +swinoujscie.pl +szczecin.pl +szczytno.pl +tarnobrzeg.pl +tgory.pl +turek.pl +tychy.pl +ustka.pl +walbrzych.pl +warmia.pl +warszawa.pl +waw.pl +wegrow.pl +wielun.pl +wlocl.pl +wloclawek.pl +wodzislaw.pl +wolomin.pl +wroclaw.pl +zachpomor.pl +zagan.pl +zarow.pl +zgora.pl +zgorzelec.pl +// TASK geographical domains (www.task.gda.pl/uslugi/dns) +gda.pl +gdansk.pl +gdynia.pl +med.pl +sopot.pl +// other geographical domains +gliwice.pl +krakow.pl +poznan.pl +wroc.pl +zakopane.pl + +// pm : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +pm + +// pn : http://www.government.pn/PnRegistry/policies.htm +pn +gov.pn +co.pn +org.pn +edu.pn +net.pn + +// pr : http://www.nic.pr/index.asp?f=1 +pr +com.pr +net.pr +org.pr +gov.pr +edu.pr +isla.pr +pro.pr +biz.pr +info.pr +name.pr +// these aren't mentioned on nic.pr, but on http://en.wikipedia.org/wiki/.pr +est.pr +prof.pr +ac.pr + +// pro : http://www.nic.pro/support_faq.htm +pro +aca.pro +bar.pro +cpa.pro +jur.pro +law.pro +med.pro +eng.pro + +// ps : http://en.wikipedia.org/wiki/.ps +// http://www.nic.ps/registration/policy.html#reg +ps +edu.ps +gov.ps +sec.ps +plo.ps +com.ps +org.ps +net.ps + +// pt : http://online.dns.pt/dns/start_dns +pt +net.pt +gov.pt +org.pt +edu.pt +int.pt +publ.pt +com.pt +nome.pt + +// pw : http://en.wikipedia.org/wiki/.pw +pw +co.pw +ne.pw +or.pw +ed.pw +go.pw +belau.pw + +// py : http://www.nic.py/faq_a.html#faq_b +*.py + +// qa : http://domains.qa/en/ +qa +com.qa +edu.qa +gov.qa +mil.qa +name.qa +net.qa +org.qa +sch.qa + +// re : http://www.afnic.re/obtenir/chartes/nommage-re/annexe-descriptifs +re +com.re +asso.re +nom.re + +// ro : http://www.rotld.ro/ +ro +com.ro +org.ro +tm.ro +nt.ro +nom.ro +info.ro +rec.ro +arts.ro +firm.ro +store.ro +www.ro + +// rs : http://en.wikipedia.org/wiki/.rs +rs +co.rs +org.rs +edu.rs +ac.rs +gov.rs +in.rs + +// ru : http://www.cctld.ru/ru/docs/aktiv_8.php +// Industry domains +ru +ac.ru +com.ru +edu.ru +int.ru +net.ru +org.ru +pp.ru +// Geographical domains +adygeya.ru +altai.ru +amur.ru +arkhangelsk.ru +astrakhan.ru +bashkiria.ru +belgorod.ru +bir.ru +bryansk.ru +buryatia.ru +cbg.ru +chel.ru +chelyabinsk.ru +chita.ru +chukotka.ru +chuvashia.ru +dagestan.ru +dudinka.ru +e-burg.ru +grozny.ru +irkutsk.ru +ivanovo.ru +izhevsk.ru +jar.ru +joshkar-ola.ru +kalmykia.ru +kaluga.ru +kamchatka.ru +karelia.ru +kazan.ru +kchr.ru +kemerovo.ru +khabarovsk.ru +khakassia.ru +khv.ru +kirov.ru +koenig.ru +komi.ru +kostroma.ru +krasnoyarsk.ru +kuban.ru +kurgan.ru +kursk.ru +lipetsk.ru +magadan.ru +mari.ru +mari-el.ru +marine.ru +mordovia.ru +mosreg.ru +msk.ru +murmansk.ru +nalchik.ru +nnov.ru +nov.ru +novosibirsk.ru +nsk.ru +omsk.ru +orenburg.ru +oryol.ru +palana.ru +penza.ru +perm.ru +pskov.ru +ptz.ru +rnd.ru +ryazan.ru +sakhalin.ru +samara.ru +saratov.ru +simbirsk.ru +smolensk.ru +spb.ru +stavropol.ru +stv.ru +surgut.ru +tambov.ru +tatarstan.ru +tom.ru +tomsk.ru +tsaritsyn.ru +tsk.ru +tula.ru +tuva.ru +tver.ru +tyumen.ru +udm.ru +udmurtia.ru +ulan-ude.ru +vladikavkaz.ru +vladimir.ru +vladivostok.ru +volgograd.ru +vologda.ru +voronezh.ru +vrn.ru +vyatka.ru +yakutia.ru +yamal.ru +yaroslavl.ru +yekaterinburg.ru +yuzhno-sakhalinsk.ru +// More geographical domains +amursk.ru +baikal.ru +cmw.ru +fareast.ru +jamal.ru +kms.ru +k-uralsk.ru +kustanai.ru +kuzbass.ru +magnitka.ru +mytis.ru +nakhodka.ru +nkz.ru +norilsk.ru +oskol.ru +pyatigorsk.ru +rubtsovsk.ru +snz.ru +syzran.ru +vdonsk.ru +zgrad.ru +// State domains +gov.ru +mil.ru +// Technical domains +test.ru + +// rw : http://www.nic.rw/cgi-bin/policy.pl +rw +gov.rw +net.rw +edu.rw +ac.rw +com.rw +co.rw +int.rw +mil.rw +gouv.rw + +// sa : http://www.nic.net.sa/ +sa +com.sa +net.sa +org.sa +gov.sa +med.sa +pub.sa +edu.sa +sch.sa + +// sb : http://www.sbnic.net.sb/ +// Submitted by registry 2008-06-08 +sb +com.sb +edu.sb +gov.sb +net.sb +org.sb + +// sc : http://www.nic.sc/ +sc +com.sc +gov.sc +net.sc +org.sc +edu.sc + +// sd : http://www.isoc.sd/sudanic.isoc.sd/billing_pricing.htm +// Submitted by registry 2008-06-17 +sd +com.sd +net.sd +org.sd +edu.sd +med.sd +gov.sd +info.sd + +// se : http://en.wikipedia.org/wiki/.se +// Submitted by registry 2008-06-24 +se +a.se +ac.se +b.se +bd.se +brand.se +c.se +d.se +e.se +f.se +fh.se +fhsk.se +fhv.se +g.se +h.se +i.se +k.se +komforb.se +kommunalforbund.se +komvux.se +l.se +lanbib.se +m.se +n.se +naturbruksgymn.se +o.se +org.se +p.se +parti.se +pp.se +press.se +r.se +s.se +sshn.se +t.se +tm.se +u.se +w.se +x.se +y.se +z.se + +// sg : http://www.nic.net.sg/sub_policies_agreement/2ld.html +sg +com.sg +net.sg +org.sg +gov.sg +edu.sg +per.sg + +// sh : http://www.nic.sh/rules.html +// list of 2nd level domains ? +sh + +// si : http://en.wikipedia.org/wiki/.si +si + +// sj : No registrations at this time. +// Submitted by registry 2008-06-16 + +// sk : http://en.wikipedia.org/wiki/.sk +// list of 2nd level domains ? +sk + +// sl : http://www.nic.sl +// Submitted by registry 2008-06-12 +sl +com.sl +net.sl +edu.sl +gov.sl +org.sl + +// sm : http://en.wikipedia.org/wiki/.sm +sm + +// sn : http://en.wikipedia.org/wiki/.sn +sn +art.sn +com.sn +edu.sn +gouv.sn +org.sn +perso.sn +univ.sn + +// so : http://www.soregistry.com/ +so +com.so +net.so +org.so + +// sr : http://en.wikipedia.org/wiki/.sr +sr + +// st : http://www.nic.st/html/policyrules/ +st +co.st +com.st +consulado.st +edu.st +embaixada.st +gov.st +mil.st +net.st +org.st +principe.st +saotome.st +store.st + +// su : http://en.wikipedia.org/wiki/.su +su + +// sv : http://www.svnet.org.sv/svpolicy.html +*.sv + +// sy : http://en.wikipedia.org/wiki/.sy +// see also: http://www.gobin.info/domainname/sy.doc +sy +edu.sy +gov.sy +net.sy +mil.sy +com.sy +org.sy + +// sz : http://en.wikipedia.org/wiki/.sz +// http://www.sispa.org.sz/ +sz +co.sz +ac.sz +org.sz + +// tc : http://en.wikipedia.org/wiki/.tc +tc + +// td : http://en.wikipedia.org/wiki/.td +td + +// tel: http://en.wikipedia.org/wiki/.tel +// http://www.telnic.org/ +tel + +// tf : http://en.wikipedia.org/wiki/.tf +tf + +// tg : http://en.wikipedia.org/wiki/.tg +// http://www.nic.tg/nictg/index.php implies no reserved 2nd-level domains, +// although this contradicts wikipedia. +tg + +// th : http://en.wikipedia.org/wiki/.th +// Submitted by registry 2008-06-17 +th +ac.th +co.th +go.th +in.th +mi.th +net.th +or.th + +// tj : http://www.nic.tj/policy.htm +tj +ac.tj +biz.tj +co.tj +com.tj +edu.tj +go.tj +gov.tj +int.tj +mil.tj +name.tj +net.tj +nic.tj +org.tj +test.tj +web.tj + +// tk : http://en.wikipedia.org/wiki/.tk +tk + +// tl : http://en.wikipedia.org/wiki/.tl +tl +gov.tl + +// tm : http://www.nic.tm/rules.html +// list of 2nd level tlds ? +tm + +// tn : http://en.wikipedia.org/wiki/.tn +// http://whois.ati.tn/ +tn +com.tn +ens.tn +fin.tn +gov.tn +ind.tn +intl.tn +nat.tn +net.tn +org.tn +info.tn +perso.tn +tourism.tn +edunet.tn +rnrt.tn +rns.tn +rnu.tn +mincom.tn +agrinet.tn +defense.tn +turen.tn + +// to : http://en.wikipedia.org/wiki/.to +// Submitted by registry 2008-06-17 +to +com.to +gov.to +net.to +org.to +edu.to +mil.to + +// tr : http://en.wikipedia.org/wiki/.tr +*.tr +!nic.tr +// Used by government in the TRNC +// http://en.wikipedia.org/wiki/.nc.tr +gov.nc.tr + +// travel : http://en.wikipedia.org/wiki/.travel +travel + +// tt : http://www.nic.tt/ +tt +co.tt +com.tt +org.tt +net.tt +biz.tt +info.tt +pro.tt +int.tt +coop.tt +jobs.tt +mobi.tt +travel.tt +museum.tt +aero.tt +name.tt +gov.tt +edu.tt + +// tv : http://en.wikipedia.org/wiki/.tv +// Not listing any 2LDs as reserved since none seem to exist in practice, +// Wikipedia notwithstanding. +tv + +// tw : http://en.wikipedia.org/wiki/.tw +tw +edu.tw +gov.tw +mil.tw +com.tw +net.tw +org.tw +idv.tw +game.tw +ebiz.tw +club.tw +網路.tw +組織.tw +商業.tw + +// tz : http://en.wikipedia.org/wiki/.tz +// Submitted by registry 2008-06-17 +// Updated from http://www.tznic.or.tz/index.php/domains.html 2010-10-25 +ac.tz +co.tz +go.tz +mil.tz +ne.tz +or.tz +sc.tz + +// ua : http://www.nic.net.ua/ +ua +com.ua +edu.ua +gov.ua +in.ua +net.ua +org.ua +// ua geo-names +cherkassy.ua +chernigov.ua +chernovtsy.ua +ck.ua +cn.ua +crimea.ua +cv.ua +dn.ua +dnepropetrovsk.ua +donetsk.ua +dp.ua +if.ua +ivano-frankivsk.ua +kh.ua +kharkov.ua +kherson.ua +khmelnitskiy.ua +kiev.ua +kirovograd.ua +km.ua +kr.ua +ks.ua +kv.ua +lg.ua +lugansk.ua +lutsk.ua +lviv.ua +mk.ua +nikolaev.ua +od.ua +odessa.ua +pl.ua +poltava.ua +rovno.ua +rv.ua +sebastopol.ua +sumy.ua +te.ua +ternopil.ua +uzhgorod.ua +vinnica.ua +vn.ua +zaporizhzhe.ua +zp.ua +zhitomir.ua +zt.ua + +// Private registries in .ua +co.ua +pp.ua + +// ug : http://www.registry.co.ug/ +ug +co.ug +ac.ug +sc.ug +go.ug +ne.ug +or.ug + +// uk : http://en.wikipedia.org/wiki/.uk +*.uk +*.sch.uk +!bl.uk +!british-library.uk +!icnet.uk +!jet.uk +!mod.uk +!nel.uk +!nhs.uk +!nic.uk +!nls.uk +!national-library-scotland.uk +!parliament.uk +!police.uk + +// us : http://en.wikipedia.org/wiki/.us +us +dni.us +fed.us +isa.us +kids.us +nsn.us +// us geographic names +ak.us +al.us +ar.us +as.us +az.us +ca.us +co.us +ct.us +dc.us +de.us +fl.us +ga.us +gu.us +hi.us +ia.us +id.us +il.us +in.us +ks.us +ky.us +la.us +ma.us +md.us +me.us +mi.us +mn.us +mo.us +ms.us +mt.us +nc.us +nd.us +ne.us +nh.us +nj.us +nm.us +nv.us +ny.us +oh.us +ok.us +or.us +pa.us +pr.us +ri.us +sc.us +sd.us +tn.us +tx.us +ut.us +vi.us +vt.us +va.us +wa.us +wi.us +wv.us +wy.us +// The registrar notes several more specific domains available in each state, +// such as state.*.us, dst.*.us, etc., but resolution of these is somewhat +// haphazard; in some states these domains resolve as addresses, while in others +// only subdomains are available, or even nothing at all. We include the +// most common ones where it's clear that different sites are different +// entities. +k12.ak.us +k12.al.us +k12.ar.us +k12.as.us +k12.az.us +k12.ca.us +k12.co.us +k12.ct.us +k12.dc.us +k12.de.us +k12.fl.us +k12.ga.us +k12.gu.us +// k12.hi.us Hawaii has a state-wide DOE login: bug 614565 +k12.ia.us +k12.id.us +k12.il.us +k12.in.us +k12.ks.us +k12.ky.us +k12.la.us +k12.ma.us +k12.md.us +k12.me.us +k12.mi.us +k12.mn.us +k12.mo.us +k12.ms.us +k12.mt.us +k12.nc.us +k12.nd.us +k12.ne.us +k12.nh.us +k12.nj.us +k12.nm.us +k12.nv.us +k12.ny.us +k12.oh.us +k12.ok.us +k12.or.us +k12.pa.us +k12.pr.us +k12.ri.us +k12.sc.us +k12.sd.us +k12.tn.us +k12.tx.us +k12.ut.us +k12.vi.us +k12.vt.us +k12.va.us +k12.wa.us +k12.wi.us +k12.wv.us +k12.wy.us + +cc.ak.us +cc.al.us +cc.ar.us +cc.as.us +cc.az.us +cc.ca.us +cc.co.us +cc.ct.us +cc.dc.us +cc.de.us +cc.fl.us +cc.ga.us +cc.gu.us +cc.hi.us +cc.ia.us +cc.id.us +cc.il.us +cc.in.us +cc.ks.us +cc.ky.us +cc.la.us +cc.ma.us +cc.md.us +cc.me.us +cc.mi.us +cc.mn.us +cc.mo.us +cc.ms.us +cc.mt.us +cc.nc.us +cc.nd.us +cc.ne.us +cc.nh.us +cc.nj.us +cc.nm.us +cc.nv.us +cc.ny.us +cc.oh.us +cc.ok.us +cc.or.us +cc.pa.us +cc.pr.us +cc.ri.us +cc.sc.us +cc.sd.us +cc.tn.us +cc.tx.us +cc.ut.us +cc.vi.us +cc.vt.us +cc.va.us +cc.wa.us +cc.wi.us +cc.wv.us +cc.wy.us + +lib.ak.us +lib.al.us +lib.ar.us +lib.as.us +lib.az.us +lib.ca.us +lib.co.us +lib.ct.us +lib.dc.us +lib.de.us +lib.fl.us +lib.ga.us +lib.gu.us +lib.hi.us +lib.ia.us +lib.id.us +lib.il.us +lib.in.us +lib.ks.us +lib.ky.us +lib.la.us +lib.ma.us +lib.md.us +lib.me.us +lib.mi.us +lib.mn.us +lib.mo.us +lib.ms.us +lib.mt.us +lib.nc.us +lib.nd.us +lib.ne.us +lib.nh.us +lib.nj.us +lib.nm.us +lib.nv.us +lib.ny.us +lib.oh.us +lib.ok.us +lib.or.us +lib.pa.us +lib.pr.us +lib.ri.us +lib.sc.us +lib.sd.us +lib.tn.us +lib.tx.us +lib.ut.us +lib.vi.us +lib.vt.us +lib.va.us +lib.wa.us +lib.wi.us +lib.wv.us +lib.wy.us + +// k12.ma.us contains school districts in Massachusetts. The 4LDs are +// managed indepedently except for private (PVT), charter (CHTR) and +// parochial (PAROCH) schools. Those are delegated dorectly to the +// 5LD operators. +pvt.k12.ma.us +chtr.k12.ma.us +paroch.k12.ma.us + +// uy : http://www.antel.com.uy/ +*.uy + +// uz : http://www.reg.uz/registerr.html +// are there other 2nd level tlds ? +uz +com.uz +co.uz + +// va : http://en.wikipedia.org/wiki/.va +va + +// vc : http://en.wikipedia.org/wiki/.vc +// Submitted by registry 2008-06-13 +vc +com.vc +net.vc +org.vc +gov.vc +mil.vc +edu.vc + +// ve : http://registro.nic.ve/nicve/registro/index.html +*.ve + +// vg : http://en.wikipedia.org/wiki/.vg +vg + +// vi : http://www.nic.vi/newdomainform.htm +// http://www.nic.vi/Domain_Rules/body_domain_rules.html indicates some other +// TLDs are "reserved", such as edu.vi and gov.vi, but doesn't actually say they +// are available for registration (which they do not seem to be). +vi +co.vi +com.vi +k12.vi +net.vi +org.vi + +// vn : https://www.dot.vn/vnnic/vnnic/domainregistration.jsp +vn +com.vn +net.vn +org.vn +edu.vn +gov.vn +int.vn +ac.vn +biz.vn +info.vn +name.vn +pro.vn +health.vn + +// vu : http://en.wikipedia.org/wiki/.vu +// list of 2nd level tlds ? +vu + +// wf : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +wf + +// ws : http://en.wikipedia.org/wiki/.ws +// http://samoanic.ws/index.dhtml +ws +com.ws +net.ws +org.ws +gov.ws +edu.ws + +// yt : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +yt + +// IDN ccTLDs +// Please sort by ISO 3166 ccTLD, then punicode string +// when submitting patches and follow this format: +// ("" ) : +// [optional sponsoring org] +// + +// xn--mgbaam7a8h ("Emerat" Arabic) : AE +//http://nic.ae/english/arabicdomain/rules.jsp +امارات + +// xn--54b7fta0cc ("Bangla" Bangla) : BD +বাংলা + +// xn--fiqs8s ("China" Chinese-Han-Simplified <.Zhonggou>) : CN +// CNNIC +// http://cnnic.cn/html/Dir/2005/10/11/3218.htm +中国 + +// xn--fiqz9s ("China" Chinese-Han-Traditional <.Zhonggou>) : CN +// CNNIC +// http://cnnic.cn/html/Dir/2005/10/11/3218.htm +中國 + +// xn--lgbbat1ad8j ("Algeria / Al Jazair" Arabic) : DZ +الجزائر + +// xn--wgbh1c ("Egypt" Arabic .masr) : EG +// http://www.dotmasr.eg/ +مصر + +// xn--node ("ge" Georgian (Mkhedruli)) : GE +გე + +// xn--j6w193g ("Hong Kong" Chinese-Han) : HK +// https://www2.hkirc.hk/register/rules.jsp +香港 + +// xn--h2brj9c ("Bharat" Devanagari) : IN +// India +भारत + +// xn--mgbbh1a71e ("Bharat" Arabic) : IN +// India +بھارت + +// xn--fpcrj9c3d ("Bharat" Telugu) : IN +// India +భారత్ + +// xn--gecrj9c ("Bharat" Gujarati) : IN +// India +ભારત + +// xn--s9brj9c ("Bharat" Gurmukhi) : IN +// India +ਭਾਰਤ + +// xn--45brj9c ("Bharat" Bengali) : IN +// India +ভারত + +// xn--xkc2dl3a5ee0h ("India" Tamil) : IN +// India +இந்தியா + +// xn--mgba3a4f16a ("Iran" Persian) : IR +ایران + +// xn--mgba3a4fra ("Iran" Arabic) : IR +ايران + +//xn--mgbayh7gpa ("al-Ordon" Arabic) JO +//National Information Technology Center (NITC) +//Royal Scientific Society, Al-Jubeiha +الاردن + +// xn--3e0b707e ("Republic of Korea" Hangul) : KR +한국 + +// xn--fzc2c9e2c ("Lanka" Sinhalese-Sinhala) : LK +// http://nic.lk +ලංකා + +// xn--xkc2al3hye2a ("Ilangai" Tamil) : LK +// http://nic.lk +இலங்கை + +// xn--mgbc0a9azcg ("Morocco / al-Maghrib" Arabic) : MA +المغرب + +// xn--mgb9awbf ("Oman" Arabic) : OM +عمان + +// xn--ygbi2ammx ("Falasteen" Arabic) : PS +// The Palestinian National Internet Naming Authority (PNINA) +// http://www.pnina.ps +فلسطين + +// xn--90a3ac ("srb" Cyrillic) : RS +срб + +// xn--p1ai ("rf" Russian-Cyrillic) : RU +// http://www.cctld.ru/en/docs/rulesrf.php +рф + +// xn--wgbl6a ("Qatar" Arabic) : QA +// http://www.ict.gov.qa/ +قطر + +// xn--mgberp4a5d4ar ("AlSaudiah" Arabic) : SA +// http://www.nic.net.sa/ +السعودية + +// xn--mgberp4a5d4a87g ("AlSaudiah" Arabic) variant : SA +السعودیة + +// xn--mgbqly7c0a67fbc ("AlSaudiah" Arabic) variant : SA +السعودیۃ + +// xn--mgbqly7cvafr ("AlSaudiah" Arabic) variant : SA +السعوديه + +// xn--ogbpf8fl ("Syria" Arabic) : SY +سورية + +// xn--mgbtf8fl ("Syria" Arabic) variant : SY +سوريا + +// xn--yfro4i67o Singapore ("Singapore" Chinese-Han) : SG +新加坡 + +// xn--clchc0ea0b2g2a9gcd ("Singapore" Tamil) : SG +சிங்கப்பூர் + +// xn--o3cw4h ("Thai" Thai) : TH +// http://www.thnic.co.th +ไทย + +// xn--pgbs0dh ("Tunis") : TN +// http://nic.tn +تونس + +// xn--kpry57d ("Taiwan" Chinese-Han-Traditional) : TW +// http://www.twnic.net/english/dn/dn_07a.htm +台灣 + +// xn--kprw13d ("Taiwan" Chinese-Han-Simplified) : TW +// http://www.twnic.net/english/dn/dn_07a.htm +台湾 + +// xn--nnx388a ("Taiwan") variant : TW +臺灣 + +// xn--j1amh ("ukr" Cyrillic) : UA +укр + +// xn--mgb2ddes ("AlYemen" Arabic) : YE +اليمن + +// xxx : http://icmregistry.com +xxx + +// ye : http://www.y.net.ye/services/domain_name.htm +*.ye + +// za : http://www.zadna.org.za/slds.html +*.za + +// zm : http://en.wikipedia.org/wiki/.zm +*.zm + +// zw : http://en.wikipedia.org/wiki/.zw +*.zw + +// ===END ICANN DOMAINS=== +// ===BEGIN PRIVATE DOMAINS=== + +// info.at : http://www.info.at/ +biz.at +info.at + +// priv.at : http://www.nic.priv.at/ +// Submitted by registry 2008-06-09 +priv.at + +// co.ca : http://registry.co.ca +co.ca + +// CentralNic : http://www.centralnic.com/names/domains +// Confirmed by registry 2008-06-09 +ar.com +br.com +cn.com +de.com +eu.com +gb.com +gr.com +hu.com +jpn.com +kr.com +no.com +qc.com +ru.com +sa.com +se.com +uk.com +us.com +uy.com +za.com +gb.net +jp.net +se.net +uk.net +ae.org +us.org +com.de + +// Opera Software, A.S.A. +// Requested by Yngve Pettersen 2009-11-26 +operaunite.com + +// Google, Inc. +// Requested by Eduardo Vela 2010-09-06 +appspot.com + +// iki.fi : Submitted by Hannu Aronsson 2009-11-05 +iki.fi + +// c.la : http://www.c.la/ +c.la + +// ZaNiC : http://www.za.net/ +// Confirmed by registry 2009-10-03 +za.net +za.org + +// CoDNS B.V. +// Added 2010-05-23. +co.nl +co.no + +// Mainseek Sp. z o.o. : http://www.co.pl/ +co.pl + +// DynDNS.com : http://www.dyndns.com/services/dns/dyndns/ +dyndns-at-home.com +dyndns-at-work.com +dyndns-blog.com +dyndns-free.com +dyndns-home.com +dyndns-ip.com +dyndns-mail.com +dyndns-office.com +dyndns-pics.com +dyndns-remote.com +dyndns-server.com +dyndns-web.com +dyndns-wiki.com +dyndns-work.com +dyndns.biz +dyndns.info +dyndns.org +dyndns.tv +at-band-camp.net +ath.cx +barrel-of-knowledge.info +barrell-of-knowledge.info +better-than.tv +blogdns.com +blogdns.net +blogdns.org +blogsite.org +boldlygoingnowhere.org +broke-it.net +buyshouses.net +cechire.com +dnsalias.com +dnsalias.net +dnsalias.org +dnsdojo.com +dnsdojo.net +dnsdojo.org +does-it.net +doesntexist.com +doesntexist.org +dontexist.com +dontexist.net +dontexist.org +doomdns.com +doomdns.org +dvrdns.org +dyn-o-saur.com +dynalias.com +dynalias.net +dynalias.org +dynathome.net +dyndns.ws +endofinternet.net +endofinternet.org +endoftheinternet.org +est-a-la-maison.com +est-a-la-masion.com +est-le-patron.com +est-mon-blogueur.com +for-better.biz +for-more.biz +for-our.info +for-some.biz +for-the.biz +forgot.her.name +forgot.his.name +from-ak.com +from-al.com +from-ar.com +from-az.net +from-ca.com +from-co.net +from-ct.com +from-dc.com +from-de.com +from-fl.com +from-ga.com +from-hi.com +from-ia.com +from-id.com +from-il.com +from-in.com +from-ks.com +from-ky.com +from-la.net +from-ma.com +from-md.com +from-me.org +from-mi.com +from-mn.com +from-mo.com +from-ms.com +from-mt.com +from-nc.com +from-nd.com +from-ne.com +from-nh.com +from-nj.com +from-nm.com +from-nv.com +from-ny.net +from-oh.com +from-ok.com +from-or.com +from-pa.com +from-pr.com +from-ri.com +from-sc.com +from-sd.com +from-tn.com +from-tx.com +from-ut.com +from-va.com +from-vt.com +from-wa.com +from-wi.com +from-wv.com +from-wy.com +ftpaccess.cc +fuettertdasnetz.de +game-host.org +game-server.cc +getmyip.com +gets-it.net +go.dyndns.org +gotdns.com +gotdns.org +groks-the.info +groks-this.info +ham-radio-op.net +here-for-more.info +hobby-site.com +hobby-site.org +home.dyndns.org +homedns.org +homeftp.net +homeftp.org +homeip.net +homelinux.com +homelinux.net +homelinux.org +homeunix.com +homeunix.net +homeunix.org +iamallama.com +in-the-band.net +is-a-anarchist.com +is-a-blogger.com +is-a-bookkeeper.com +is-a-bruinsfan.org +is-a-bulls-fan.com +is-a-candidate.org +is-a-caterer.com +is-a-celticsfan.org +is-a-chef.com +is-a-chef.net +is-a-chef.org +is-a-conservative.com +is-a-cpa.com +is-a-cubicle-slave.com +is-a-democrat.com +is-a-designer.com +is-a-doctor.com +is-a-financialadvisor.com +is-a-geek.com +is-a-geek.net +is-a-geek.org +is-a-green.com +is-a-guru.com +is-a-hard-worker.com +is-a-hunter.com +is-a-knight.org +is-a-landscaper.com +is-a-lawyer.com +is-a-liberal.com +is-a-libertarian.com +is-a-linux-user.org +is-a-llama.com +is-a-musician.com +is-a-nascarfan.com +is-a-nurse.com +is-a-painter.com +is-a-patsfan.org +is-a-personaltrainer.com +is-a-photographer.com +is-a-player.com +is-a-republican.com +is-a-rockstar.com +is-a-socialist.com +is-a-soxfan.org +is-a-student.com +is-a-teacher.com +is-a-techie.com +is-a-therapist.com +is-an-accountant.com +is-an-actor.com +is-an-actress.com +is-an-anarchist.com +is-an-artist.com +is-an-engineer.com +is-an-entertainer.com +is-by.us +is-certified.com +is-found.org +is-gone.com +is-into-anime.com +is-into-cars.com +is-into-cartoons.com +is-into-games.com +is-leet.com +is-lost.org +is-not-certified.com +is-saved.org +is-slick.com +is-uberleet.com +is-very-bad.org +is-very-evil.org +is-very-good.org +is-very-nice.org +is-very-sweet.org +is-with-theband.com +isa-geek.com +isa-geek.net +isa-geek.org +isa-hockeynut.com +issmarterthanyou.com +isteingeek.de +istmein.de +kicks-ass.net +kicks-ass.org +knowsitall.info +land-4-sale.us +lebtimnetz.de +leitungsen.de +likes-pie.com +likescandy.com +merseine.nu +mine.nu +misconfused.org +mypets.ws +myphotos.cc +neat-url.com +office-on-the.net +on-the-web.tv +podzone.net +podzone.org +readmyblog.org +saves-the-whales.com +scrapper-site.net +scrapping.cc +selfip.biz +selfip.com +selfip.info +selfip.net +selfip.org +sells-for-less.com +sells-for-u.com +sells-it.net +sellsyourhome.org +servebbs.com +servebbs.net +servebbs.org +serveftp.net +serveftp.org +servegame.org +shacknet.nu +simple-url.com +space-to-rent.com +stuff-4-sale.org +stuff-4-sale.us +teaches-yoga.com +thruhere.net +traeumtgerade.de +webhop.biz +webhop.info +webhop.net +webhop.org +worse-than.tv +writesthisblog.com + +// ===END PRIVATE DOMAINS=== diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/test.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/test.js new file mode 100644 index 000000000..5cbf536ca --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tough-cookie/test.js @@ -0,0 +1,1625 @@ +/* + * Copyright GoInstant, Inc. and other contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var async = require('async'); + +// NOTE use require("tough-cookie") in your own code: +var tough = require('./lib/cookie'); +var Cookie = tough.Cookie; +var CookieJar = tough.CookieJar; + + +function dateVows(table) { + var theVows = { }; + Object.keys(table).forEach(function(date) { + var expect = table[date]; + theVows[date] = function() { + var got = tough.parseDate(date) ? 'valid' : 'invalid'; + assert.equal(got, expect ? 'valid' : 'invalid'); + }; + }); + return { "date parsing": theVows }; +} + +function matchVows(func,table) { + var theVows = {}; + table.forEach(function(item) { + var str = item[0]; + var dom = item[1]; + var expect = item[2]; + var label = str+(expect?" matches ":" doesn't match ")+dom; + theVows[label] = function() { + assert.equal(func(str,dom),expect); + }; + }); + return theVows; +} + +function defaultPathVows(table) { + var theVows = {}; + table.forEach(function(item) { + var str = item[0]; + var expect = item[1]; + var label = str+" gives "+expect; + theVows[label] = function() { + assert.equal(tough.defaultPath(str),expect); + }; + }); + return theVows; +} + +var atNow = Date.now(); +function at(offset) { return {now: new Date(atNow+offset)}; } + +vows.describe('Cookie Jar') +.addBatch({ + "all defined": function() { + assert.ok(Cookie); + assert.ok(CookieJar); + }, +}) +.addBatch( + dateVows({ + "Wed, 09 Jun 2021 10:18:14 GMT": true, + "Wed, 09 Jun 2021 22:18:14 GMT": true, + "Tue, 18 Oct 2011 07:42:42.123 GMT": true, + "18 Oct 2011 07:42:42 GMT": true, + "8 Oct 2011 7:42:42 GMT": true, + "8 Oct 2011 7:2:42 GMT": false, + "Oct 18 2011 07:42:42 GMT": true, + "Tue Oct 18 2011 07:05:03 GMT+0000 (GMT)": true, + "09 Jun 2021 10:18:14 GMT": true, + "99 Jix 3038 48:86:72 ZMT": false, + '01 Jan 1970 00:00:00 GMT': true, + '01 Jan 1600 00:00:00 GMT': false, // before 1601 + '01 Jan 1601 00:00:00 GMT': true, + '10 Feb 81 13:00:00 GMT': true, // implicit year + 'Thu, 01 Jan 1970 00:00:010 GMT': true, // strange time, non-strict OK + 'Thu, 17-Apr-2014 02:12:29 GMT': true, // dashes + 'Thu, 17-Apr-2014 02:12:29 UTC': true, // dashes and UTC + }) +) +.addBatch({ + "strict date parse of Thu, 01 Jan 1970 00:00:010 GMT": { + topic: function() { + return tough.parseDate('Thu, 01 Jan 1970 00:00:010 GMT', true) ? true : false; + }, + "invalid": function(date) { + assert.equal(date,false); + }, + } +}) +.addBatch({ + "formatting": { + "a simple cookie": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + return c; + }, + "validates": function(c) { + assert.ok(c.validate()); + }, + "to string": function(c) { + assert.equal(c.toString(), 'a=b'); + }, + }, + "a cookie with spaces in the value": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'beta gamma'; + return c; + }, + "doesn't validate": function(c) { + assert.ok(!c.validate()); + }, + "'garbage in, garbage out'": function(c) { + assert.equal(c.toString(), 'a=beta gamma'); + }, + }, + "with an empty value and HttpOnly": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.httpOnly = true; + return c; + }, + "to string": function(c) { + assert.equal(c.toString(), 'a=; HttpOnly'); + } + }, + "with an expiry": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + return c; + }, + "validates": function(c) { + assert.ok(c.validate()); + }, + "to string": function(c) { + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT'); + }, + "to short string": function(c) { + assert.equal(c.cookieString(), 'a=b'); + }, + }, + "with a max-age": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + c.maxAge = 12345; + return c; + }, + "validates": function(c) { + assert.ok(c.validate()); // mabe this one *shouldn't*? + }, + "to string": function(c) { + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Max-Age=12345'); + }, + }, + "with a bunch of things": function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + c.maxAge = 12345; + c.domain = 'example.com'; + c.path = '/foo'; + c.secure = true; + c.httpOnly = true; + c.extensions = ['MyExtension']; + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Max-Age=12345; Domain=example.com; Path=/foo; Secure; HttpOnly; MyExtension'); + }, + "a host-only cookie": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.hostOnly = true; + c.domain = 'shouldnt-stringify.example.com'; + c.path = '/should-stringify'; + return c; + }, + "validates": function(c) { + assert.ok(c.validate()); + }, + "to string": function(c) { + assert.equal(c.toString(), 'a=b; Path=/should-stringify'); + }, + }, + "minutes are '10'": { + topic: function() { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.expires = new Date(1284113410000); + return c; + }, + "validates": function(c) { + assert.ok(c.validate()); + }, + "to string": function(c) { + var str = c.toString(); + assert.notEqual(str, 'a=b; Expires=Fri, 010 Sep 2010 010:010:010 GMT'); + assert.equal(str, 'a=b; Expires=Fri, 10 Sep 2010 10:10:10 GMT'); + }, + } + } +}) +.addBatch({ + "TTL with max-age": function() { + var c = new Cookie(); + c.maxAge = 123; + assert.equal(c.TTL(), 123000); + assert.equal(c.expiryTime(new Date(9000000)), 9123000); + }, + "TTL with zero max-age": function() { + var c = new Cookie(); + c.key = 'a'; c.value = 'b'; + c.maxAge = 0; // should be treated as "earliest representable" + assert.equal(c.TTL(), 0); + assert.equal(c.expiryTime(new Date(9000000)), -Infinity); + assert.ok(!c.validate()); // not valid, really: non-zero-digit *DIGIT + }, + "TTL with negative max-age": function() { + var c = new Cookie(); + c.key = 'a'; c.value = 'b'; + c.maxAge = -1; // should be treated as "earliest representable" + assert.equal(c.TTL(), 0); + assert.equal(c.expiryTime(new Date(9000000)), -Infinity); + assert.ok(!c.validate()); // not valid, really: non-zero-digit *DIGIT + }, + "TTL with max-age and expires": function() { + var c = new Cookie(); + c.maxAge = 123; + c.expires = new Date(Date.now()+9000); + assert.equal(c.TTL(), 123000); + assert.ok(c.isPersistent()); + }, + "TTL with expires": function() { + var c = new Cookie(); + var now = Date.now(); + c.expires = new Date(now+9000); + assert.equal(c.TTL(now), 9000); + assert.equal(c.expiryTime(), c.expires.getTime()); + }, + "TTL with old expires": function() { + var c = new Cookie(); + c.setExpires('17 Oct 2010 00:00:00 GMT'); + assert.ok(c.TTL() < 0); + assert.ok(c.isPersistent()); + }, + "default TTL": { + topic: function() { return new Cookie(); }, + "is Infinite-future": function(c) { assert.equal(c.TTL(), Infinity) }, + "is a 'session' cookie": function(c) { assert.ok(!c.isPersistent()) }, + }, +}).addBatch({ + "Parsing": { + "simple": { + topic: function() { + return Cookie.parse('a=bcd',true) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'bcd') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) }, + }, + "with expiry": { + topic: function() { + return Cookie.parse('a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT',true) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'bcd') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + }, + }, + "with expiry and path": { + topic: function() { + return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc',true) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'abc') }, + "value": function(c) { assert.equal(c.value, 'xyzzy!') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + }, + "has path": function(c) { assert.equal(c.path, '/aBc'); }, + "no httponly or secure": function(c) { + assert.ok(!c.httpOnly); + assert.ok(!c.secure); + }, + }, + "with everything": { + topic: function() { + return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc; Domain=example.com; Secure; HTTPOnly; Max-Age=1234; Foo=Bar; Baz', true) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'abc') }, + "value": function(c) { assert.equal(c.value, 'xyzzy!') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + }, + "has path": function(c) { assert.equal(c.path, '/aBc'); }, + "has domain": function(c) { assert.equal(c.domain, 'example.com'); }, + "has httponly": function(c) { assert.equal(c.httpOnly, true); }, + "has secure": function(c) { assert.equal(c.secure, true); }, + "has max-age": function(c) { assert.equal(c.maxAge, 1234); }, + "has extensions": function(c) { + assert.ok(c.extensions); + assert.equal(c.extensions[0], 'Foo=Bar'); + assert.equal(c.extensions[1], 'Baz'); + }, + }, + "invalid expires": { + "strict": function() { assert.ok(!Cookie.parse("a=b; Expires=xyzzy", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; Expires=xyzzy"); + assert.ok(c); + assert.equal(c.expires, Infinity); + }, + }, + "zero max-age": { + "strict": function() { assert.ok(!Cookie.parse("a=b; Max-Age=0", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; Max-Age=0"); + assert.ok(c); + assert.equal(c.maxAge, 0); + }, + }, + "negative max-age": { + "strict": function() { assert.ok(!Cookie.parse("a=b; Max-Age=-1", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; Max-Age=-1"); + assert.ok(c); + assert.equal(c.maxAge, -1); + }, + }, + "empty domain": { + "strict": function() { assert.ok(!Cookie.parse("a=b; domain=", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; domain="); + assert.ok(c); + assert.equal(c.domain, null); + }, + }, + "dot domain": { + "strict": function() { assert.ok(!Cookie.parse("a=b; domain=.", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; domain=."); + assert.ok(c); + assert.equal(c.domain, null); + }, + }, + "uppercase domain": { + "strict lowercases": function() { + var c = Cookie.parse("a=b; domain=EXAMPLE.COM"); + assert.ok(c); + assert.equal(c.domain, 'example.com'); + }, + "non-strict lowercases": function() { + var c = Cookie.parse("a=b; domain=EXAMPLE.COM"); + assert.ok(c); + assert.equal(c.domain, 'example.com'); + }, + }, + "trailing dot in domain": { + topic: function() { + return Cookie.parse("a=b; Domain=example.com.", true) || null; + }, + "has the domain": function(c) { assert.equal(c.domain,"example.com.") }, + "but doesn't validate": function(c) { assert.equal(c.validate(),false) }, + }, + "empty path": { + "strict": function() { assert.ok(!Cookie.parse("a=b; path=", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; path="); + assert.ok(c); + assert.equal(c.path, null); + }, + }, + "no-slash path": { + "strict": function() { assert.ok(!Cookie.parse("a=b; path=xyzzy", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; path=xyzzy"); + assert.ok(c); + assert.equal(c.path, null); + }, + }, + "trailing semi-colons after path": { + topic: function () { + return [ + "a=b; path=/;", + "c=d;;;;" + ]; + }, + "strict": function (t) { + assert.ok(!Cookie.parse(t[0], true)); + assert.ok(!Cookie.parse(t[1], true)); + }, + "non-strict": function (t) { + var c1 = Cookie.parse(t[0]); + var c2 = Cookie.parse(t[1]); + assert.ok(c1); + assert.ok(c2); + assert.equal(c1.path, '/'); + } + }, + "secure-with-value": { + "strict": function() { assert.ok(!Cookie.parse("a=b; Secure=xyzzy", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; Secure=xyzzy"); + assert.ok(c); + assert.equal(c.secure, true); + }, + }, + "httponly-with-value": { + "strict": function() { assert.ok(!Cookie.parse("a=b; HttpOnly=xyzzy", true)) }, + "non-strict": function() { + var c = Cookie.parse("a=b; HttpOnly=xyzzy"); + assert.ok(c); + assert.equal(c.httpOnly, true); + }, + }, + "garbage": { + topic: function() { + return Cookie.parse("\x08", true) || null; + }, + "doesn't parse": function(c) { assert.equal(c,null) }, + }, + "public suffix domain": { + topic: function() { + return Cookie.parse("a=b; domain=kyoto.jp", true) || null; + }, + "parses fine": function(c) { + assert.ok(c); + assert.equal(c.domain, 'kyoto.jp'); + }, + "but fails validation": function(c) { + assert.ok(c); + assert.ok(!c.validate()); + }, + }, + "Ironically, Google 'GAPS' cookie has very little whitespace": { + topic: function() { + return Cookie.parse("GAPS=1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-;Path=/;Expires=Thu, 17-Apr-2014 02:12:29 GMT;Secure;HttpOnly"); + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'GAPS') }, + "value": function(c) { assert.equal(c.value, '1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-') }, + "path": function(c) { + assert.notEqual(c.path, '/;Expires'); // BUG + assert.equal(c.path, '/'); + }, + "expires": function(c) { + assert.notEqual(c.expires, Infinity); + assert.equal(c.expires.getTime(), 1397700749000); + }, + "secure": function(c) { assert.ok(c.secure) }, + "httponly": function(c) { assert.ok(c.httpOnly) }, + }, + "lots of equal signs": { + topic: function() { + return Cookie.parse("queryPref=b=c&d=e; Path=/f=g; Expires=Thu, 17 Apr 2014 02:12:29 GMT; HttpOnly"); + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'queryPref') }, + "value": function(c) { assert.equal(c.value, 'b=c&d=e') }, + "path": function(c) { + assert.equal(c.path, '/f=g'); + }, + "expires": function(c) { + assert.notEqual(c.expires, Infinity); + assert.equal(c.expires.getTime(), 1397700749000); + }, + "httponly": function(c) { assert.ok(c.httpOnly) }, + }, + "spaces in value": { + "strict": { + topic: function() { + return Cookie.parse('a=one two three',true) || null; + }, + "did not parse": function(c) { assert.isNull(c) }, + }, + "non-strict": { + topic: function() { + return Cookie.parse('a=one two three',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'one two three') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) }, + }, + }, + "quoted spaces in value": { + "strict": { + topic: function() { + return Cookie.parse('a="one two three"',true) || null; + }, + "did not parse": function(c) { assert.isNull(c) }, + }, + "non-strict": { + topic: function() { + return Cookie.parse('a="one two three"',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'one two three') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) }, + } + }, + "non-ASCII in value": { + "strict": { + topic: function() { + return Cookie.parse('farbe=weiß',true) || null; + }, + "did not parse": function(c) { assert.isNull(c) }, + }, + "non-strict": { + topic: function() { + return Cookie.parse('farbe=weiß',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'farbe') }, + "value": function(c) { assert.equal(c.value, 'weiß') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) }, + }, + }, + } +}) +.addBatch({ + "domain normalization": { + "simple": function() { + var c = new Cookie(); + c.domain = "EXAMPLE.com"; + assert.equal(c.canonicalizedDomain(), "example.com"); + }, + "extra dots": function() { + var c = new Cookie(); + c.domain = ".EXAMPLE.com"; + assert.equal(c.cdomain(), "example.com"); + }, + "weird trailing dot": function() { + var c = new Cookie(); + c.domain = "EXAMPLE.ca."; + assert.equal(c.canonicalizedDomain(), "example.ca."); + }, + "weird internal dots": function() { + var c = new Cookie(); + c.domain = "EXAMPLE...ca."; + assert.equal(c.canonicalizedDomain(), "example...ca."); + }, + "IDN": function() { + var c = new Cookie(); + c.domain = "δοκιμή.δοκιμή"; // "test.test" in greek + assert.equal(c.canonicalizedDomain(), "xn--jxalpdlp.xn--jxalpdlp"); + } + } +}) +.addBatch({ + "Domain Match":matchVows(tough.domainMatch, [ + // str, dom, expect + ["example.com", "example.com", true], + ["eXaMpLe.cOm", "ExAmPlE.CoM", true], + ["no.ca", "yes.ca", false], + ["wwwexample.com", "example.com", false], + ["www.example.com", "example.com", true], + ["example.com", "www.example.com", false], + ["www.subdom.example.com", "example.com", true], + ["www.subdom.example.com", "subdom.example.com", true], + ["example.com", "example.com.", false], // RFC6265 S4.1.2.3 + ["192.168.0.1", "168.0.1", false], // S5.1.3 "The string is a host name" + [null, "example.com", null], + ["example.com", null, null], + [null, null, null], + [undefined, undefined, null], + ]) +}) +.addBatch({ + "default-path": defaultPathVows([ + [null,"/"], + ["/","/"], + ["/file","/"], + ["/dir/file","/dir"], + ["noslash","/"], + ]) +}) +.addBatch({ + "Path-Match": matchVows(tough.pathMatch, [ + // request, cookie, match + ["/","/",true], + ["/dir","/",true], + ["/","/dir",false], + ["/dir/","/dir/", true], + ["/dir/file","/dir/",true], + ["/dir/file","/dir",true], + ["/directory","/dir",false], + ]) +}) +.addBatch({ + "Cookie Sorting": { + topic: function() { + var cookies = []; + var now = Date.now(); + cookies.push(Cookie.parse("a=0; Domain=example.com")); + cookies.push(Cookie.parse("b=1; Domain=www.example.com")); + cookies.push(Cookie.parse("c=2; Domain=example.com; Path=/pathA")); + cookies.push(Cookie.parse("d=3; Domain=www.example.com; Path=/pathA")); + cookies.push(Cookie.parse("e=4; Domain=example.com; Path=/pathA/pathB")); + cookies.push(Cookie.parse("f=5; Domain=www.example.com; Path=/pathA/pathB")); + + // force a stable creation time consistent with the order above since + // some may have been created at now + 1ms. + var i = cookies.length; + cookies.forEach(function(cookie) { + cookie.creation = new Date(now - 100*(i--)); + }); + + // weak shuffle: + cookies = cookies.sort(function(){return Math.random()-0.5}); + + cookies = cookies.sort(tough.cookieCompare); + return cookies; + }, + "got": function(cookies) { + assert.lengthOf(cookies, 6); + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['e','f','c','d','a','b']); + }, + } +}) +.addBatch({ + "CookieJar": { + "Setting a basic cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now()-10000); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "works": function(c) { assert.instanceOf(c,Cookie) }, // C is for Cookie, good enough for me + "gets timestamped": function(c) { + assert.ok(c.creation); + assert.ok(Date.now() - c.creation.getTime() < 5000); // recently stamped + assert.ok(c.lastAccessed); + assert.equal(c.creation, c.lastAccessed); + assert.equal(c.TTL(), Infinity); + assert.ok(!c.isPersistent()); + }, + }, + "Setting a no-path cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now()-10000); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "domain": function(c) { assert.equal(c.domain, 'example.com') }, + "path is /": function(c) { assert.equal(c.path, '/') }, + "path was derived": function(c) { assert.strictEqual(c.pathIsDefault, true) }, + }, + "Setting a cookie already marked as host-only": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now()-10000); + c.hostOnly = true; + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "domain": function(c) { assert.equal(c.domain, 'example.com') }, + "still hostOnly": function(c) { assert.strictEqual(c.hostOnly, true) }, + }, + "Setting a session cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b"); + assert.strictEqual(c.path, null); + cj.setCookie(c, 'http://www.example.com/dir/index.html', this.callback); + }, + "works": function(c) { assert.instanceOf(c,Cookie) }, + "gets the domain": function(c) { assert.equal(c.domain, 'www.example.com') }, + "gets the default path": function(c) { assert.equal(c.path, '/dir') }, + "is 'hostOnly'": function(c) { assert.ok(c.hostOnly) }, + }, + "Setting wrong domain cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=fooxample.com; Path=/"); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "fails": function(err,c) { + assert.ok(err.message.match(/domain/i)); + assert.ok(!c); + }, + }, + "Setting sub-domain cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=www.example.com; Path=/"); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "fails": function(err,c) { + assert.ok(err.message.match(/domain/i)); + assert.ok(!c); + }, + }, + "Setting super-domain cookie": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/"); + cj.setCookie(c, 'http://www.app.example.com/index.html', this.callback); + }, + "success": function(err,c) { + assert.ok(!err); + assert.equal(c.domain, 'example.com'); + }, + }, + "Setting a sub-path cookie on a super-domain": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/subpath"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now()-10000); + cj.setCookie(c, 'http://www.example.com/index.html', this.callback); + }, + "domain is super-domain": function(c) { assert.equal(c.domain, 'example.com') }, + "path is /subpath": function(c) { assert.equal(c.path, '/subpath') }, + "path was NOT derived": function(c) { assert.strictEqual(c.pathIsDefault, null) }, + }, + "Setting HttpOnly cookie over non-HTTP API": { + topic: function() { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/; HttpOnly"); + cj.setCookie(c, 'http://example.com/index.html', {http:false}, this.callback); + }, + "fails": function(err,c) { + assert.match(err.message, /HttpOnly/i); + assert.ok(!c); + }, + }, + }, + "Cookie Jar store eight cookies": { + topic: function() { + var cj = new CookieJar(); + var ex = 'http://example.com/index.html'; + var tasks = []; + tasks.push(function(next) { + cj.setCookie('a=1; Domain=example.com; Path=/',ex,at(0),next); + }); + tasks.push(function(next) { + cj.setCookie('b=2; Domain=example.com; Path=/; HttpOnly',ex,at(1000),next); + }); + tasks.push(function(next) { + cj.setCookie('c=3; Domain=example.com; Path=/; Secure',ex,at(2000),next); + }); + tasks.push(function(next) { // path + cj.setCookie('d=4; Domain=example.com; Path=/foo',ex,at(3000),next); + }); + tasks.push(function(next) { // host only + cj.setCookie('e=5',ex,at(4000),next); + }); + tasks.push(function(next) { // other domain + cj.setCookie('f=6; Domain=nodejs.org; Path=/','http://nodejs.org',at(5000),next); + }); + tasks.push(function(next) { // expired + cj.setCookie('g=7; Domain=example.com; Path=/; Expires=Tue, 18 Oct 2011 00:00:00 GMT',ex,at(6000),next); + }); + tasks.push(function(next) { // expired via Max-Age + cj.setCookie('h=8; Domain=example.com; Path=/; Max-Age=1',ex,next); + }); + var cb = this.callback; + async.parallel(tasks, function(err,results){ + setTimeout(function() { + cb(err,cj,results); + }, 2000); // so that 'h=8' expires + }); + }, + "setup ok": function(err,cj,results) { + assert.ok(!err); + assert.ok(cj); + assert.ok(results); + }, + "then retrieving for http://nodejs.org": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://nodejs.org',this.callback); + }, + "get a nodejs cookie": function(cookies) { + assert.lengthOf(cookies, 1); + var cookie = cookies[0]; + assert.equal(cookie.domain, 'nodejs.org'); + }, + }, + "then retrieving for https://example.com": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('https://example.com',{secure:true},this.callback); + }, + "get a secure example cookie with others": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['a','b','c','e']); + }, + }, + "then retrieving for https://example.com (missing options)": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('https://example.com',this.callback); + }, + "get a secure example cookie with others": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['a','b','c','e']); + }, + }, + "then retrieving for http://example.com": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com',this.callback); + }, + "get a bunch of cookies": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['a','b','e']); + }, + }, + "then retrieving for http://EXAMPlE.com": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://EXAMPlE.com',this.callback); + }, + "get a bunch of cookies": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['a','b','e']); + }, + }, + "then retrieving for http://example.com, non-HTTP": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com',{http:false},this.callback); + }, + "get a bunch of cookies": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['a','e']); + }, + }, + "then retrieving for http://example.com/foo/bar": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com/foo/bar',this.callback); + }, + "get a bunch of cookies": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['d','a','b','e']); + }, + }, + "then retrieving for http://example.com as a string": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookieString('http://example.com',this.callback); + }, + "get a single string": function(cookieHeader) { + assert.equal(cookieHeader, "a=1; b=2; e=5"); + }, + }, + "then retrieving for http://example.com as a set-cookie header": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getSetCookieStrings('http://example.com',this.callback); + }, + "get a single string": function(cookieHeaders) { + assert.lengthOf(cookieHeaders, 3); + assert.equal(cookieHeaders[0], "a=1; Domain=example.com; Path=/"); + assert.equal(cookieHeaders[1], "b=2; Domain=example.com; Path=/; HttpOnly"); + assert.equal(cookieHeaders[2], "e=5; Path=/"); + }, + }, + "then retrieving for http://www.example.com/": { + topic: function(cj,oldResults) { + assert.ok(oldResults); + cj.getCookies('http://www.example.com/foo/bar',this.callback); + }, + "get a bunch of cookies": function(cookies) { + var names = cookies.map(function(c) {return c.key}); + assert.deepEqual(names, ['d','a','b']); // note lack of 'e' + }, + }, + }, + "Repeated names": { + topic: function() { + var cb = this.callback; + var cj = new CookieJar(); + var ex = 'http://www.example.com/'; + var sc = cj.setCookie; + var tasks = []; + var now = Date.now(); + tasks.push(sc.bind(cj,'aaaa=xxxx',ex,at(0))); + tasks.push(sc.bind(cj,'aaaa=1111; Domain=www.example.com',ex,at(1000))); + tasks.push(sc.bind(cj,'aaaa=2222; Domain=example.com',ex,at(2000))); + tasks.push(sc.bind(cj,'aaaa=3333; Domain=www.example.com; Path=/pathA',ex,at(3000))); + async.series(tasks,function(err,results) { + results = results.filter(function(e) {return e !== undefined}); + cb(err,{cj:cj, cookies:results, now:now}); + }); + }, + "all got set": function(err,t) { + assert.lengthOf(t.cookies,4); + }, + "then getting 'em back": { + topic: function(t) { + var cj = t.cj; + cj.getCookies('http://www.example.com/pathA',this.callback); + }, + "there's just three": function (err,cookies) { + var vals = cookies.map(function(c) {return c.value}); + // may break with sorting; sorting should put 3333 first due to longest path: + assert.deepEqual(vals, ['3333','1111','2222']); + } + }, + }, + "CookieJar setCookie errors": { + "public-suffix domain": { + topic: function() { + var cj = new CookieJar(); + cj.setCookie('i=9; Domain=kyoto.jp; Path=/','kyoto.jp',this.callback); + }, + "errors": function(err,cookie) { + assert.ok(err); + assert.ok(!cookie); + assert.match(err.message, /public suffix/i); + }, + }, + "wrong domain": { + topic: function() { + var cj = new CookieJar(); + cj.setCookie('j=10; Domain=google.com; Path=/','google.ca',this.callback); + }, + "errors": function(err,cookie) { + assert.ok(err); + assert.ok(!cookie); + assert.match(err.message, /not in this host's domain/i); + }, + }, + "old cookie is HttpOnly": { + topic: function() { + var cb = this.callback; + var next = function (err,c) { + c = null; + return cb(err,cj); + }; + var cj = new CookieJar(); + cj.setCookie('k=11; Domain=example.ca; Path=/; HttpOnly','http://example.ca',{http:true},next); + }, + "initial cookie is set": function(err,cj) { + assert.ok(!err); + assert.ok(cj); + }, + "but when trying to overwrite": { + topic: function(cj) { + var cb = this.callback; + var next = function(err,c) { + c = null; + cb(null,err); + }; + cj.setCookie('k=12; Domain=example.ca; Path=/','http://example.ca',{http:false},next); + }, + "it's an error": function(err) { + assert.ok(err); + }, + "then, checking the original": { + topic: function(ignored,cj) { + assert.ok(cj instanceof CookieJar); + cj.getCookies('http://example.ca',{http:true},this.callback); + }, + "cookie has original value": function(err,cookies) { + assert.equal(err,null); + assert.lengthOf(cookies, 1); + assert.equal(cookies[0].value,11); + }, + }, + }, + }, + }, +}) +.addBatch({ + "JSON": { + "serialization": { + topic: function() { + var c = Cookie.parse('alpha=beta; Domain=example.com; Path=/foo; Expires=Tue, 19 Jan 2038 03:14:07 GMT; HttpOnly'); + return JSON.stringify(c); + }, + "gives a string": function(str) { + assert.equal(typeof str, "string"); + }, + "date is in ISO format": function(str) { + assert.match(str, /"expires":"2038-01-19T03:14:07\.000Z"/, 'expires is in ISO format'); + }, + }, + "deserialization": { + topic: function() { + var json = '{"key":"alpha","value":"beta","domain":"example.com","path":"/foo","expires":"2038-01-19T03:14:07.000Z","httpOnly":true,"lastAccessed":2000000000123}'; + return Cookie.fromJSON(json); + }, + "works": function(c) { + assert.ok(c); + }, + "key": function(c) { assert.equal(c.key, "alpha") }, + "value": function(c) { assert.equal(c.value, "beta") }, + "domain": function(c) { assert.equal(c.domain, "example.com") }, + "path": function(c) { assert.equal(c.path, "/foo") }, + "httpOnly": function(c) { assert.strictEqual(c.httpOnly, true) }, + "secure": function(c) { assert.strictEqual(c.secure, false) }, + "hostOnly": function(c) { assert.strictEqual(c.hostOnly, null) }, + "expires is a date object": function(c) { + assert.equal(c.expires.getTime(), 2147483647000); + }, + "lastAccessed is a date object": function(c) { + assert.equal(c.lastAccessed.getTime(), 2000000000123); + }, + "creation defaulted": function(c) { + assert.ok(c.creation.getTime()); + } + }, + "null deserialization": { + topic: function() { + return Cookie.fromJSON(null); + }, + "is null": function(cookie) { + assert.equal(cookie,null); + }, + }, + }, + "expiry deserialization": { + "Infinity": { + topic: Cookie.fromJSON.bind(null, '{"expires":"Infinity"}'), + "is infinite": function(c) { + assert.strictEqual(c.expires, "Infinity"); + assert.equal(c.expires, Infinity); + }, + }, + }, + "maxAge serialization": { + topic: function() { + return function(toSet) { + var c = new Cookie(); + c.key = 'foo'; c.value = 'bar'; + c.setMaxAge(toSet); + return JSON.stringify(c); + }; + }, + "zero": { + topic: function(f) { return f(0) }, + "looks good": function(str) { + assert.match(str, /"maxAge":0/); + }, + }, + "Infinity": { + topic: function(f) { return f(Infinity) }, + "looks good": function(str) { + assert.match(str, /"maxAge":"Infinity"/); + }, + }, + "-Infinity": { + topic: function(f) { return f(-Infinity) }, + "looks good": function(str) { + assert.match(str, /"maxAge":"-Infinity"/); + }, + }, + "null": { + topic: function(f) { return f(null) }, + "looks good": function(str) { + assert.match(str, /"maxAge":null/); + }, + }, + }, + "maxAge deserialization": { + "number": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":123}'), + "is the number": function(c) { + assert.strictEqual(c.maxAge, 123); + }, + }, + "null": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":null}'), + "is null": function(c) { + assert.strictEqual(c.maxAge, null); + }, + }, + "less than zero": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":-123}'), + "is -123": function(c) { + assert.strictEqual(c.maxAge, -123); + }, + }, + "Infinity": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":"Infinity"}'), + "is inf-as-string": function(c) { + assert.strictEqual(c.maxAge, "Infinity"); + }, + }, + "-Infinity": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":"-Infinity"}'), + "is inf-as-string": function(c) { + assert.strictEqual(c.maxAge, "-Infinity"); + }, + }, + } +}) +.addBatch({ + "permuteDomain": { + "base case": { + topic: tough.permuteDomain.bind(null,'example.com'), + "got the domain": function(list) { + assert.deepEqual(list, ['example.com']); + }, + }, + "two levels": { + topic: tough.permuteDomain.bind(null,'foo.bar.example.com'), + "got three things": function(list) { + assert.deepEqual(list, ['example.com','bar.example.com','foo.bar.example.com']); + }, + }, + "invalid domain": { + topic: tough.permuteDomain.bind(null,'foo.bar.example.localduhmain'), + "got three things": function(list) { + assert.equal(list, null); + }, + }, + }, + "permutePath": { + "base case": { + topic: tough.permutePath.bind(null,'/'), + "just slash": function(list) { + assert.deepEqual(list,['/']); + }, + }, + "single case": { + topic: tough.permutePath.bind(null,'/foo'), + "two things": function(list) { + assert.deepEqual(list,['/foo','/']); + }, + "path matching": function(list) { + list.forEach(function(e) { + assert.ok(tough.pathMatch('/foo',e)); + }); + }, + }, + "double case": { + topic: tough.permutePath.bind(null,'/foo/bar'), + "four things": function(list) { + assert.deepEqual(list,['/foo/bar','/foo','/']); + }, + "path matching": function(list) { + list.forEach(function(e) { + assert.ok(tough.pathMatch('/foo/bar',e)); + }); + }, + }, + "trailing slash": { + topic: tough.permutePath.bind(null,'/foo/bar/'), + "three things": function(list) { + assert.deepEqual(list,['/foo/bar','/foo','/']); + }, + "path matching": function(list) { + list.forEach(function(e) { + assert.ok(tough.pathMatch('/foo/bar/',e)); + }); + }, + }, + } +}) +.addBatch({ + "Issue 1": { + topic: function() { + var cj = new CookieJar(); + cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function(err,cookie) { + this.callback(err,{cj:cj, cookie:cookie}); + }.bind(this)); + }, + "stored a cookie": function(t) { + assert.ok(t.cookie); + }, + "cookie's path was modified to remove unnecessary slash": function(t) { + assert.equal(t.cookie.path, '/some/path'); + }, + "getting it back": { + topic: function(t) { + t.cj.getCookies('http://domain/some/path/file', function(err,cookies) { + this.callback(err, {cj:t.cj, cookies:cookies||[]}); + }.bind(this)); + }, + "got one cookie": function(t) { + assert.lengthOf(t.cookies, 1); + }, + "it's the right one": function(t) { + var c = t.cookies[0]; + assert.equal(c.key, 'hello'); + assert.equal(c.value, 'world'); + }, + } + } +}) +.addBatch({ + "expiry option": { + topic: function() { + var cb = this.callback; + var cj = new CookieJar(); + cj.setCookie('near=expiry; Domain=example.com; Path=/; Max-Age=1','http://www.example.com',at(-1), function(err,cookie) { + + cb(err, {cj:cj, cookie:cookie}); + }); + }, + "set the cookie": function(t) { + assert.ok(t.cookie, "didn't set?!"); + assert.equal(t.cookie.key, 'near'); + }, + "then, retrieving": { + topic: function(t) { + var cb = this.callback; + setTimeout(function() { + t.cj.getCookies('http://www.example.com', {http:true, expire:false}, function(err,cookies) { + t.cookies = cookies; + cb(err,t); + }); + },2000); + }, + "got the cookie": function(t) { + assert.lengthOf(t.cookies, 1); + assert.equal(t.cookies[0].key, 'near'); + }, + } + } +}) +.addBatch({ + "trailing semi-colon set into cj": { + topic: function () { + var cb = this.callback; + var cj = new CookieJar(); + var ex = 'http://www.example.com'; + var tasks = []; + tasks.push(function(next) { + cj.setCookie('broken_path=testme; path=/;',ex,at(-1),next); + }); + tasks.push(function(next) { + cj.setCookie('b=2; Path=/;;;;',ex,at(-1),next); + }); + async.parallel(tasks, function (err, cookies) { + cb(null, { + cj: cj, + cookies: cookies + }); + }); + }, + "check number of cookies": function (t) { + assert.lengthOf(t.cookies, 2, "didn't set"); + }, + "check *broken_path* was set properly": function (t) { + assert.equal(t.cookies[0].key, "broken_path"); + assert.equal(t.cookies[0].value, "testme"); + assert.equal(t.cookies[0].path, "/"); + }, + "check *b* was set properly": function (t) { + assert.equal(t.cookies[1].key, "b"); + assert.equal(t.cookies[1].value, "2"); + assert.equal(t.cookies[1].path, "/"); + }, + "retrieve the cookie": { + topic: function (t) { + var cb = this.callback; + t.cj.getCookies('http://www.example.com', {}, function (err, cookies) { + t.cookies = cookies; + cb(err, t); + }); + }, + "get the cookie": function(t) { + assert.lengthOf(t.cookies, 2); + assert.equal(t.cookies[0].key, 'broken_path'); + assert.equal(t.cookies[0].value, 'testme'); + assert.equal(t.cookies[1].key, "b"); + assert.equal(t.cookies[1].value, "2"); + assert.equal(t.cookies[1].path, "/"); + }, + }, + } +}) +.addBatch({ + "Constructor":{ + topic: function () { + return new Cookie({ + key: 'test', + value: 'b', + maxAge: 60 + }); + }, + 'check for key property': function (c) { + assert.ok(c); + assert.equal(c.key, 'test'); + }, + 'check for value property': function (c) { + assert.equal(c.value, 'b'); + }, + 'check for maxAge': function (c) { + assert.equal(c.maxAge, 60); + }, + 'check for default values for unspecified properties': function (c) { + assert.equal(c.expires, "Infinity"); + assert.equal(c.secure, false); + assert.equal(c.httpOnly, false); + } + } +}) +.addBatch({ + "allPaths option": { + topic: function() { + var cj = new CookieJar(); + var tasks = []; + tasks.push(cj.setCookie.bind(cj, 'nopath_dom=qq; Path=/; Domain=example.com', 'http://example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'path_dom=qq; Path=/foo; Domain=example.com', 'http://example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'nopath_host=qq; Path=/', 'http://www.example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'path_host=qq; Path=/foo', 'http://www.example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'other=qq; Path=/', 'http://other.example.com/', {})); + tasks.push(cj.setCookie.bind(cj, 'other2=qq; Path=/foo', 'http://other.example.com/foo', {})); + var cb = this.callback; + async.parallel(tasks, function(err,results) { + cb(err, {cj:cj, cookies: results}); + }); + }, + "all set": function(t) { + assert.equal(t.cookies.length, 6); + assert.ok(t.cookies.every(function(c) { return !!c })); + }, + "getting without allPaths": { + topic: function(t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/', {}, function(err,cookies) { + cb(err, {cj:cj, cookies:cookies}); + }); + }, + "found just two cookies": function(t) { + assert.equal(t.cookies.length, 2); + }, + "all are path=/": function(t) { + assert.ok(t.cookies.every(function(c) { return c.path === '/' })); + }, + "no 'other' cookies": function(t) { + assert.ok(!t.cookies.some(function(c) { return (/^other/).test(c.name) })); + }, + }, + "getting without allPaths for /foo": { + topic: function(t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/foo', {}, function(err,cookies) { + cb(err, {cj:cj, cookies:cookies}); + }); + }, + "found four cookies": function(t) { + assert.equal(t.cookies.length, 4); + }, + "no 'other' cookies": function(t) { + assert.ok(!t.cookies.some(function(c) { return (/^other/).test(c.name) })); + }, + }, + "getting with allPaths:true": { + topic: function(t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/', {allPaths:true}, function(err,cookies) { + cb(err, {cj:cj, cookies:cookies}); + }); + }, + "found four cookies": function(t) { + assert.equal(t.cookies.length, 4); + }, + "no 'other' cookies": function(t) { + assert.ok(!t.cookies.some(function(c) { return (/^other/).test(c.name) })); + }, + }, + } +}) +.addBatch({ + "remove cookies": { + topic: function() { + var jar = new CookieJar(); + var cookie = Cookie.parse("a=b; Domain=example.com; Path=/"); + var cookie2 = Cookie.parse("a=b; Domain=foo.com; Path=/"); + var cookie3 = Cookie.parse("foo=bar; Domain=foo.com; Path=/"); + jar.setCookie(cookie, 'http://example.com/index.html', function(){}); + jar.setCookie(cookie2, 'http://foo.com/index.html', function(){}); + jar.setCookie(cookie3, 'http://foo.com/index.html', function(){}); + return jar; + }, + "all from matching domain": function(jar){ + jar.store.removeCookies('example.com',null, function(err) { + assert(err == null); + + jar.store.findCookies('example.com', null, function(err, cookies){ + assert(err == null); + assert(cookies != null); + assert(cookies.length === 0, 'cookie was not removed'); + }); + + jar.store.findCookies('foo.com', null, function(err, cookies){ + assert(err == null); + assert(cookies != null); + assert(cookies.length === 2, 'cookies should not have been removed'); + }); + }); + }, + "from cookie store matching domain and key": function(jar){ + jar.store.removeCookie('foo.com', '/', 'foo', function(err) { + assert(err == null); + + jar.store.findCookies('foo.com', null, function(err, cookies){ + assert(err == null); + assert(cookies != null); + assert(cookies.length === 1, 'cookie was not removed correctly'); + assert(cookies[0].key === 'a', 'wrong cookie was removed'); + }); + }); + } + } +}) +.addBatch({ + "Synchronous CookieJar": { + "setCookieSync": { + topic: function() { + var jar = new CookieJar(); + var cookie = Cookie.parse("a=b; Domain=example.com; Path=/"); + cookie = jar.setCookieSync(cookie, 'http://example.com/index.html'); + return cookie; + }, + "returns a copy of the cookie": function(cookie) { + assert.instanceOf(cookie, Cookie); + } + }, + + "setCookieSync strict parse error": { + topic: function() { + var jar = new CookieJar(); + var opts = { strict: true }; + try { + jar.setCookieSync("farbe=weiß", 'http://example.com/index.html', opts); + return false; + } catch (e) { + return e; + } + }, + "throws the error": function(err) { + assert.instanceOf(err, Error); + assert.equal(err.message, "Cookie failed to parse"); + } + }, + + "getCookiesSync": { + topic: function() { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getCookiesSync(url); + }, + "returns the cookie array": function(err, cookies) { + assert.ok(!err); + assert.ok(Array.isArray(cookies)); + assert.lengthOf(cookies, 2); + cookies.forEach(function(cookie) { + assert.instanceOf(cookie, Cookie); + }); + } + }, + + "getCookieStringSync": { + topic: function() { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getCookieStringSync(url); + }, + "returns the cookie header string": function(err, str) { + assert.ok(!err); + assert.typeOf(str, 'string'); + } + }, + + "getSetCookieStringsSync": { + topic: function() { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getSetCookieStringsSync(url); + }, + "returns the cookie header string": function(err, headers) { + assert.ok(!err); + assert.ok(Array.isArray(headers)); + assert.lengthOf(headers, 2); + headers.forEach(function(header) { + assert.typeOf(header, 'string'); + }); + } + }, + } +}) +.addBatch({ + "Synchronous API on async CookieJar": { + topic: function() { + return new tough.Store(); + }, + "setCookieSync": { + topic: function(store) { + var jar = new CookieJar(store); + try { + jar.setCookieSync("a=b", 'http://example.com/index.html'); + return false; + } catch(e) { + return e; + } + }, + "fails": function(err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getCookiesSync": { + topic: function(store) { + var jar = new CookieJar(store); + try { + jar.getCookiesSync('http://example.com/index.html'); + return false; + } catch(e) { + return e; + } + }, + "fails": function(err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getCookieStringSync": { + topic: function(store) { + var jar = new CookieJar(store); + try { + jar.getCookieStringSync('http://example.com/index.html'); + return false; + } catch(e) { + return e; + } + }, + "fails": function(err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getSetCookieStringsSync": { + topic: function(store) { + var jar = new CookieJar(store); + try { + jar.getSetCookieStringsSync('http://example.com/index.html'); + return false; + } catch(e) { + return e; + } + }, + "fails": function(err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + } +}) +.export(module); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/.jshintrc b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/.jshintrc new file mode 100644 index 000000000..4c1c8d497 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/.jshintrc @@ -0,0 +1,5 @@ +{ + "node": true, + "asi": true, + "laxcomma": true +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/LICENSE b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/LICENSE new file mode 100644 index 000000000..a4a9aee0c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/README.md b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/README.md new file mode 100644 index 000000000..bb533d56b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/README.md @@ -0,0 +1,4 @@ +tunnel-agent +============ + +HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/index.js b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/index.js new file mode 100644 index 000000000..13c04272d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/index.js @@ -0,0 +1,236 @@ +'use strict' + +var net = require('net') + , tls = require('tls') + , http = require('http') + , https = require('https') + , events = require('events') + , assert = require('assert') + , util = require('util') + ; + +exports.httpOverHttp = httpOverHttp +exports.httpsOverHttp = httpsOverHttp +exports.httpOverHttps = httpOverHttps +exports.httpsOverHttps = httpsOverHttps + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + return agent +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + agent.createSocket = createSecureSocket + return agent +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + return agent +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + agent.createSocket = createSecureSocket + return agent +} + + +function TunnelingAgent(options) { + var self = this + self.options = options || {} + self.proxyOptions = self.options.proxy || {} + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets + self.requests = [] + self.sockets = [] + + self.on('free', function onFree(socket, host, port) { + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i] + if (pending.host === host && pending.port === port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1) + pending.request.onSocket(socket) + return + } + } + socket.destroy() + self.removeSocket(socket) + }) +} +util.inherits(TunnelingAgent, events.EventEmitter) + +TunnelingAgent.prototype.addRequest = function addRequest(req, options) { + var self = this + + // Legacy API: addRequest(req, host, port, path) + if (typeof options === 'string') { + options = { + host: options, + port: arguments[2], + path: arguments[3] + }; + } + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push({host: host, port: port, request: req}) + return + } + + // If we are under maxSockets create a new one. + self.createSocket({host: options.host, port: options.port, request: req}, function(socket) { + socket.on('free', onFree) + socket.on('close', onCloseOrRemove) + socket.on('agentRemove', onCloseOrRemove) + req.onSocket(socket) + + function onFree() { + self.emit('free', socket, options.host, options.port) + } + + function onCloseOrRemove(err) { + self.removeSocket() + socket.removeListener('free', onFree) + socket.removeListener('close', onCloseOrRemove) + socket.removeListener('agentRemove', onCloseOrRemove) + } + }) +} + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this + var placeholder = {} + self.sockets.push(placeholder) + + var connectOptions = mergeOptions({}, self.proxyOptions, + { method: 'CONNECT' + , path: options.host + ':' + options.port + , agent: false + } + ) + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {} + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64') + } + + debug('making CONNECT request') + var connectReq = self.request(connectOptions) + connectReq.useChunkedEncodingByDefault = false // for v0.6 + connectReq.once('response', onResponse) // for v0.6 + connectReq.once('upgrade', onUpgrade) // for v0.6 + connectReq.once('connect', onConnect) // for v0.7 or later + connectReq.once('error', onError) + connectReq.end() + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head) + }) + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners() + socket.removeAllListeners() + + if (res.statusCode === 200) { + assert.equal(head.length, 0) + debug('tunneling connection has established') + self.sockets[self.sockets.indexOf(placeholder)] = socket + cb(socket) + } else { + debug('tunneling socket could not be established, statusCode=%d', res.statusCode) + var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } + } + + function onError(cause) { + connectReq.removeAllListeners() + + debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack) + var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } +} + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) return + + this.sockets.splice(pos, 1) + + var pending = this.requests.shift() + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket) + }) + } +} + +function createSecureSocket(options, cb) { + var self = this + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, mergeOptions({}, self.options, + { servername: options.host + , socket: socket + } + )) + cb(secureSocket) + }) +} + + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i] + if (typeof overrides === 'object') { + var keys = Object.keys(overrides) + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j] + if (overrides[k] !== undefined) { + target[k] = overrides[k] + } + } + } + } + return target +} + + +var debug +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments) + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0] + } else { + args.unshift('TUNNEL:') + } + console.error.apply(console, args) + } +} else { + debug = function() {} +} +exports.debug = debug // for test diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/package.json new file mode 100644 index 000000000..90c2a3422 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/node_modules/tunnel-agent/package.json @@ -0,0 +1,30 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "tunnel-agent", + "description": "HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.", + "version": "0.4.0", + "repository": { + "url": "https://github.com/mikeal/tunnel-agent" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "tunnel-agent\n============\n\nHTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mikeal/tunnel-agent/issues" + }, + "homepage": "https://github.com/mikeal/tunnel-agent", + "_id": "tunnel-agent@0.4.0", + "_shasum": "b1184e312ffbcf70b3b4c78e8c219de7ebb1c550", + "_from": "tunnel-agent@~0.4.0", + "_resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.4.0.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/package.json b/node_modules/less-middleware/node_modules/less/node_modules/request/package.json new file mode 100644 index 000000000..c6e617279 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/package.json @@ -0,0 +1,62 @@ +{ + "name": "request", + "description": "Simplified HTTP request client.", + "tags": [ + "http", + "simple", + "util", + "utility" + ], + "version": "2.40.0", + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com" + }, + "repository": { + "type": "git", + "url": "https://github.com/mikeal/request.git" + }, + "bugs": { + "url": "http://github.com/mikeal/request/issues" + }, + "license": "Apache-2.0", + "engines": [ + "node >= 0.8.0" + ], + "main": "index.js", + "dependencies": { + "qs": "~1.0.0", + "json-stringify-safe": "~5.0.0", + "mime-types": "~1.0.1", + "forever-agent": "~0.5.0", + "node-uuid": "~1.4.0", + "tough-cookie": ">=0.12.0", + "form-data": "~0.1.0", + "tunnel-agent": "~0.4.0", + "http-signature": "~0.10.0", + "oauth-sign": "~0.3.0", + "hawk": "1.1.1", + "aws-sign2": "~0.5.0", + "stringstream": "~0.0.4" + }, + "optionalDependencies": { + "tough-cookie": ">=0.12.0", + "form-data": "~0.1.0", + "tunnel-agent": "~0.4.0", + "http-signature": "~0.10.0", + "oauth-sign": "~0.3.0", + "hawk": "1.1.1", + "aws-sign2": "~0.5.0", + "stringstream": "~0.0.4" + }, + "scripts": { + "test": "node tests/run.js" + }, + "readme": "# Request — Simplified HTTP client\n\n[![NPM](https://nodei.co/npm/request.png)](https://nodei.co/npm/request/)\n\n## Super simple to use\n\nRequest is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.\n\n```javascript\nvar request = require('request');\nrequest('http://www.google.com', function (error, response, body) {\n if (!error && response.statusCode == 200) {\n console.log(body) // Print the google web page.\n }\n})\n```\n\n## Streaming\n\nYou can stream any response to a file stream.\n\n```javascript\nrequest('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))\n```\n\nYou can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one).\n\n```javascript\nfs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))\n```\n\nRequest can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.\n\n```javascript\nrequest.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))\n```\n\nNow let’s get fancy.\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n if (req.method === 'PUT') {\n req.pipe(request.put('http://mysite.com/doodle.png'))\n } else if (req.method === 'GET' || req.method === 'HEAD') {\n request.get('http://mysite.com/doodle.png').pipe(resp)\n }\n }\n})\n```\n\nYou can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n var x = request('http://mysite.com/doodle.png')\n req.pipe(x)\n x.pipe(resp)\n }\n})\n```\n\nAnd since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)\n\n```javascript\nreq.pipe(request('http://mysite.com/doodle.png')).pipe(resp)\n```\n\nAlso, none of this new functionality conflicts with requests previous features, it just expands them.\n\n```javascript\nvar r = request.defaults({'proxy':'http://localproxy.com'})\n\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n r.get('http://google.com/doodle.png').pipe(resp)\n }\n})\n```\n\nYou can still use intermediate proxies, the requests will still follow HTTP forwards, etc.\n\n## UNIX Socket \n\n`request` supports the `unix://` protocol for all requests. The path is assumed to be absolute to the root of the host file system. \n\nHTTP paths are extracted from the supplied URL by testing each level of the full URL against net.connect for a socket response.\n\nThus the following request will GET `/httppath` from the HTTP server listening on `/tmp/unix.socket`\n\n```javascript\nrequest.get('unix://tmp/unix.socket/httppath')\n```\n\n## Forms\n\n`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.\n\nURL-encoded forms are simple.\n\n```javascript\nrequest.post('http://service.com/upload', {form:{key:'value'}})\n// or\nrequest.post('http://service.com/upload').form({key:'value'})\n```\n\nFor `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). You don’t need to worry about piping the form object or setting the headers, `request` will handle that for you.\n\n```javascript\nvar r = request.post('http://service.com/upload', function optionalCallback (err, httpResponse, body) {\n if (err) {\n return console.error('upload failed:', err);\n }\n console.log('Upload successful! Server responded with:', body);\n})\nvar form = r.form()\nform.append('my_field', 'my_value')\nform.append('my_buffer', new Buffer([1, 2, 3]))\nform.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png')))\nform.append('remote_file', request('http://google.com/doodle.png'))\n\n// Just like always, `r` is a writable stream, and can be used as such (you have until nextTick to pipe it, etc.)\n// Alternatively, you can provide a callback (that's what this example does — see `optionalCallback` above).\n```\n\n## HTTP Authentication\n\n```javascript\nrequest.get('http://some.server.com/').auth('username', 'password', false);\n// or\nrequest.get('http://some.server.com/', {\n 'auth': {\n 'user': 'username',\n 'pass': 'password',\n 'sendImmediately': false\n }\n});\n// or\nrequest.get('http://some.server.com/').auth(null, null, true, 'bearerToken');\n// or\nrequest.get('http://some.server.com/', {\n 'auth': {\n 'bearer': 'bearerToken'\n }\n});\n```\n\nIf passed as an option, `auth` should be a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). The method form takes parameters `auth(username, password, sendImmediately)`.\n\n`sendImmediately` defaults to `true`, which causes a basic authentication header to be sent. If `sendImmediately` is `false`, then `request` will retry with a proper authentication header after receiving a `401` response from the server (which must contain a `WWW-Authenticate` header indicating the required authentication method).\n\nNote that you can also use for basic authentication a trick using the URL itself, as specified in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). \nSimply pass the `user:password` before the host with an `@` sign.\n\n```javascript\nvar username = 'username',\n password = 'password',\n url = 'http://' + username + ':' + password + '@some.server.com';\n\nrequest({url: url}, function (error, response, body) {\n // Do more stuff with 'body' here\n});\n```\n\nDigest authentication is supported, but it only works with `sendImmediately` set to `false`; otherwise `request` will send basic authentication on the initial request, which will probably cause the request to fail.\n\nBearer authentication is supported, and is activated when the `bearer` value is available. The value may be either a `String` or a `Function` returning a `String`. Using a function to supply the bearer token is particularly useful if used in conjuction with `defaults` to allow a single function to supply the last known token at the time or sending a request or to compute one on the fly.\n\n## OAuth Signing\n\n```javascript\n// Twitter OAuth\nvar qs = require('querystring')\n , oauth =\n { callback: 'http://mysite.com/callback/'\n , consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n }\n , url = 'https://api.twitter.com/oauth/request_token'\n ;\nrequest.post({url:url, oauth:oauth}, function (e, r, body) {\n // Ideally, you would take the body in the response\n // and construct a URL that a user clicks on (like a sign in button).\n // The verifier is only available in the response after a user has\n // verified with twitter that they are authorizing your app.\n var access_token = qs.parse(body)\n , oauth =\n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: access_token.oauth_token\n , verifier: access_token.oauth_verifier\n }\n , url = 'https://api.twitter.com/oauth/access_token'\n ;\n request.post({url:url, oauth:oauth}, function (e, r, body) {\n var perm_token = qs.parse(body)\n , oauth =\n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: perm_token.oauth_token\n , token_secret: perm_token.oauth_token_secret\n }\n , url = 'https://api.twitter.com/1.1/users/show.json?'\n , params =\n { screen_name: perm_token.screen_name\n , user_id: perm_token.user_id\n }\n ;\n url += qs.stringify(params)\n request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {\n console.log(user)\n })\n })\n})\n```\n\n### Custom HTTP Headers\n\nHTTP Headers, such as `User-Agent`, can be set in the `options` object.\nIn the example below, we call the github API to find out the number\nof stars and forks for the request repository. This requires a\ncustom `User-Agent` header as well as https.\n\n```javascript\nvar request = require('request');\n\nvar options = {\n\turl: 'https://api.github.com/repos/mikeal/request',\n\theaders: {\n\t\t'User-Agent': 'request'\n\t}\n};\n\nfunction callback(error, response, body) {\n\tif (!error && response.statusCode == 200) {\n\t\tvar info = JSON.parse(body);\n\t\tconsole.log(info.stargazers_count + \" Stars\");\n\t\tconsole.log(info.forks_count + \" Forks\");\n\t}\n}\n\nrequest(options, callback);\n```\n\n### request(options, callback)\n\nThe first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.\n\n* `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`\n* `qs` - object containing querystring values to be appended to the `uri`\n* `method` - http method (default: `\"GET\"`)\n* `headers` - http headers (default: `{}`)\n* `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer` or `String`.\n* `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. When passed no options, a `FormData` instance is returned (and is piped to request).\n* `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.\n* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.\n* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.\n* `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`)\n* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)\n* `maxRedirects` - the maximum number of redirects to follow (default: `10`)\n* `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`.\n* `pool` - A hash object containing the agents for these requests. If omitted, the request will use the global pool (which is set to node's default `maxSockets`)\n* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.\n* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request\n* `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)\n* `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.\n* `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).\n* `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.\n* `jar` - If `true` and `tough-cookie` is installed, remember cookies for future use (or define your custom cookie jar; see examples section)\n* `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services)\n* `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.\n* `localAddress` - Local interface to bind for network connections.\n* `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response.\n\n\nThe callback argument gets 3 arguments: \n\n1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)\n2. An [`http.IncomingMessage`](http://nodejs.org/api/http.html#http_http_incomingmessage) object\n3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)\n\n## Convenience methods\n\nThere are also shorthand methods for different HTTP METHODs and some other conveniences.\n\n### request.defaults(options)\n\nThis method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.\n\n### request.put\n\nSame as `request()`, but defaults to `method: \"PUT\"`.\n\n```javascript\nrequest.put(url)\n```\n\n### request.patch\n\nSame as `request()`, but defaults to `method: \"PATCH\"`.\n\n```javascript\nrequest.patch(url)\n```\n\n### request.post\n\nSame as `request()`, but defaults to `method: \"POST\"`.\n\n```javascript\nrequest.post(url)\n```\n\n### request.head\n\nSame as request() but defaults to `method: \"HEAD\"`.\n\n```javascript\nrequest.head(url)\n```\n\n### request.del\n\nSame as `request()`, but defaults to `method: \"DELETE\"`.\n\n```javascript\nrequest.del(url)\n```\n\n### request.get\n\nSame as `request()` (for uniformity).\n\n```javascript\nrequest.get(url)\n```\n### request.cookie\n\nFunction that creates a new cookie.\n\n```javascript\nrequest.cookie('cookie_string_here')\n```\n### request.jar\n\nFunction that creates a new cookie jar.\n\n```javascript\nrequest.jar()\n```\n\n\n## Examples:\n\n```javascript\n var request = require('request')\n , rand = Math.floor(Math.random()*100000000).toString()\n ;\n request(\n { method: 'PUT'\n , uri: 'http://mikeal.iriscouch.com/testjs/' + rand\n , multipart:\n [ { 'content-type': 'application/json'\n , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})\n }\n , { body: 'I am an attachment' }\n ]\n }\n , function (error, response, body) {\n if(response.statusCode == 201){\n console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)\n } else {\n console.log('error: '+ response.statusCode)\n console.log(body)\n }\n }\n )\n```\n\nCookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`) and install `tough-cookie`.\n\n```javascript\nvar request = request.defaults({jar: true})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\n\nTo use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`)\n\n```javascript\nvar j = request.jar()\nvar request = request.defaults({jar:j})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\n\nOR\n\n```javascript\n// `npm install --save tough-cookie` before this works\nvar j = request.jar()\nvar cookie = request.cookie('your_cookie_here')\nj.setCookie(cookie, uri);\nrequest({url: 'http://www.google.com', jar: j}, function () {\n request('http://images.google.com')\n})\n```\n\nTo inspect your cookie jar after a request\n\n```javascript\nvar j = request.jar() \nrequest({url: 'http://www.google.com', jar: j}, function () {\n var cookie_string = j.getCookieString(uri); // \"key1=value1; key2=value2; ...\"\n var cookies = j.getCookies(uri); \n // [{key: 'key1', value: 'value1', domain: \"www.google.com\", ...}, ...]\n})\n```\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/mikeal/request", + "_id": "request@2.40.0", + "_shasum": "4dd670f696f1e6e842e66b4b5e839301ab9beb67", + "_from": "request@~2.40.0", + "_resolved": "https://registry.npmjs.org/request/-/request-2.40.0.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/request/request.js b/node_modules/less-middleware/node_modules/less/node_modules/request/request.js new file mode 100644 index 000000000..38d60d570 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/request/request.js @@ -0,0 +1,1428 @@ +var optional = require('./lib/optional') + , http = require('http') + , https = optional('https') + , tls = optional('tls') + , url = require('url') + , util = require('util') + , stream = require('stream') + , qs = require('qs') + , querystring = require('querystring') + , crypto = require('crypto') + , zlib = require('zlib') + + , oauth = optional('oauth-sign') + , hawk = optional('hawk') + , aws = optional('aws-sign2') + , httpSignature = optional('http-signature') + , uuid = require('node-uuid') + , mime = require('mime-types') + , tunnel = optional('tunnel-agent') + , _safeStringify = require('json-stringify-safe') + , stringstream = optional('stringstream') + + , ForeverAgent = require('forever-agent') + , FormData = optional('form-data') + + , cookies = require('./lib/cookies') + , globalCookieJar = cookies.jar() + + , copy = require('./lib/copy') + , debug = require('./lib/debug') + , getSafe = require('./lib/getSafe') + , net = require('net') + ; + +function safeStringify (obj) { + var ret + try { ret = JSON.stringify(obj) } + catch (e) { ret = _safeStringify(obj) } + return ret +} + +var globalPool = {} +var isUrl = /^https?:|^unix:/ + + +// Hacky fix for pre-0.4.4 https +if (https && !https.Agent) { + https.Agent = function (options) { + http.Agent.call(this, options) + } + util.inherits(https.Agent, http.Agent) + https.Agent.prototype._getConnection = function (host, port, cb) { + var s = tls.connect(port, host, this.options, function () { + // do other checks here? + if (cb) cb() + }) + return s + } +} + +function isReadStream (rs) { + return rs.readable && rs.path && rs.mode; +} + +function toBase64 (str) { + return (new Buffer(str || "", "ascii")).toString("base64") +} + +function md5 (str) { + return crypto.createHash('md5').update(str).digest('hex') +} + +function Request (options) { + stream.Stream.call(this) + this.readable = true + this.writable = true + + if (typeof options === 'string') { + options = {uri:options} + } + + var reserved = Object.keys(Request.prototype) + for (var i in options) { + if (reserved.indexOf(i) === -1) { + this[i] = options[i] + } else { + if (typeof options[i] === 'function') { + delete options[i] + } + } + } + + if (options.method) { + this.explicitMethod = true + } + + this.canTunnel = options.tunnel !== false && tunnel; + + this.init(options) +} +util.inherits(Request, stream.Stream) +Request.prototype.init = function (options) { + // init() contains all the code to setup the request object. + // the actual outgoing request is not started until start() is called + // this function is called from both the constructor and on redirect. + var self = this + if (!options) options = {} + + if (!self.method) self.method = options.method || 'GET' + self.localAddress = options.localAddress + + debug(options) + if (!self.pool && self.pool !== false) self.pool = globalPool + self.dests = self.dests || [] + self.__isRequestRequest = true + + // Protect against double callback + if (!self._callback && self.callback) { + self._callback = self.callback + self.callback = function () { + if (self._callbackCalled) return // Print a warning maybe? + self._callbackCalled = true + self._callback.apply(self, arguments) + } + self.on('error', self.callback.bind()) + self.on('complete', self.callback.bind(self, null)) + } + + if (self.url && !self.uri) { + // People use this property instead all the time so why not just support it. + self.uri = self.url + delete self.url + } + + if (!self.uri) { + // this will throw if unhandled but is handleable when in a redirect + return self.emit('error', new Error("options.uri is a required argument")) + } else { + if (typeof self.uri == "string") self.uri = url.parse(self.uri) + } + + if (self.strictSSL === false) { + self.rejectUnauthorized = false + } + + if(!self.hasOwnProperty('proxy')) { + // check for HTTP(S)_PROXY environment variables + if(self.uri.protocol == "http:") { + self.proxy = process.env.HTTP_PROXY || process.env.http_proxy || null; + } else if(self.uri.protocol == "https:") { + self.proxy = process.env.HTTPS_PROXY || process.env.https_proxy || + process.env.HTTP_PROXY || process.env.http_proxy || null; + } + } + + if (self.proxy) { + if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy) + + // do the HTTP CONNECT dance using koichik/node-tunnel + if (http.globalAgent && self.uri.protocol === "https:" && self.canTunnel) { + var tunnelFn = self.proxy.protocol === "http:" + ? tunnel.httpsOverHttp : tunnel.httpsOverHttps + + var tunnelOptions = { proxy: { host: self.proxy.hostname + , port: +self.proxy.port + , proxyAuth: self.proxy.auth + , headers: { Host: self.uri.hostname + ':' + + (self.uri.port || self.uri.protocol === 'https:' ? 443 : 80) }} + , rejectUnauthorized: self.rejectUnauthorized + , ca: this.ca + , cert:this.cert + , key: this.key} + + self.agent = tunnelFn(tunnelOptions) + self.tunnel = true + } + } + + if (!self.uri.pathname) {self.uri.pathname = '/'} + + if (!self.uri.host && !self.protocol=='unix:') { + // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar + // Detect and reject it as soon as possible + var faultyUri = url.format(self.uri) + var message = 'Invalid URI "' + faultyUri + '"' + if (Object.keys(options).length === 0) { + // No option ? This can be the sign of a redirect + // As this is a case where the user cannot do anything (they didn't call request directly with this URL) + // they should be warned that it can be caused by a redirection (can save some hair) + message += '. This can be caused by a crappy redirection.' + } + self.emit('error', new Error(message)) + return // This error was fatal + } + + self._redirectsFollowed = self._redirectsFollowed || 0 + self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10 + self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true + self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false + if (self.followRedirect || self.followAllRedirects) + self.redirects = self.redirects || [] + + self.headers = self.headers ? copy(self.headers) : {} + + self.setHost = false + if (!self.hasHeader('host')) { + self.setHeader('host', self.uri.hostname) + if (self.uri.port) { + if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') && + !(self.uri.port === 443 && self.uri.protocol === 'https:') ) + self.setHeader('host', self.getHeader('host') + (':'+self.uri.port) ) + } + self.setHost = true + } + + self.jar(self._jar || options.jar) + + if (!self.uri.port) { + if (self.uri.protocol == 'http:') {self.uri.port = 80} + else if (self.uri.protocol == 'https:') {self.uri.port = 443} + } + + if (self.proxy && !self.tunnel) { + self.port = self.proxy.port + self.host = self.proxy.hostname + } else { + self.port = self.uri.port + self.host = self.uri.hostname + } + + self.clientErrorHandler = function (error) { + if (self._aborted) return + if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' + && self.agent.addRequestNoreuse) { + self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } + self.start() + self.req.end() + return + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + self.emit('error', error) + } + + self._parserErrorHandler = function (error) { + if (this.res) { + if (this.res.request) { + this.res.request.emit('error', error) + } else { + this.res.emit('error', error) + } + } else { + this._httpMessage.emit('error', error) + } + } + + self._buildRequest = function(){ + var self = this; + + if (options.form) { + self.form(options.form) + } + + if (options.qs) self.qs(options.qs) + + if (self.uri.path) { + self.path = self.uri.path + } else { + self.path = self.uri.pathname + (self.uri.search || "") + } + + if (self.path.length === 0) self.path = '/' + + + // Auth must happen last in case signing is dependent on other headers + if (options.oauth) { + self.oauth(options.oauth) + } + + if (options.aws) { + self.aws(options.aws) + } + + if (options.hawk) { + self.hawk(options.hawk) + } + + if (options.httpSignature) { + self.httpSignature(options.httpSignature) + } + + if (options.auth) { + if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) options.auth.user = options.auth.username + if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) options.auth.pass = options.auth.password + + self.auth( + options.auth.user, + options.auth.pass, + options.auth.sendImmediately, + options.auth.bearer + ) + } + + if (self.gzip && !self.hasHeader('accept-encoding')) { + self.setHeader('accept-encoding', 'gzip') + } + + if (self.uri.auth && !self.hasHeader('authorization')) { + var authPieces = self.uri.auth.split(':').map(function(item){ return querystring.unescape(item) }) + self.auth(authPieces[0], authPieces.slice(1).join(':'), true) + } + if (self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization') && !self.tunnel) { + self.setHeader('proxy-authorization', "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return querystring.unescape(item)}).join(':'))) + } + + + if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) + + if (options.json) { + self.json(options.json) + } else if (options.multipart) { + self.boundary = uuid() + self.multipart(options.multipart) + } + + if (self.body) { + var length = 0 + if (!Buffer.isBuffer(self.body)) { + if (Array.isArray(self.body)) { + for (var i = 0; i < self.body.length; i++) { + length += self.body[i].length + } + } else { + self.body = new Buffer(self.body) + length = self.body.length + } + } else { + length = self.body.length + } + if (length) { + if (!self.hasHeader('content-length')) self.setHeader('content-length', length) + } else { + throw new Error('Argument error, options.body.') + } + } + + var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol + , defaultModules = {'http:':http, 'https:':https, 'unix:':http} + , httpModules = self.httpModules || {} + ; + self.httpModule = httpModules[protocol] || defaultModules[protocol] + + if (!self.httpModule) return this.emit('error', new Error("Invalid protocol: " + protocol)) + + if (options.ca) self.ca = options.ca + + if (!self.agent) { + if (options.agentOptions) self.agentOptions = options.agentOptions + + if (options.agentClass) { + self.agentClass = options.agentClass + } else if (options.forever) { + self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL + } else { + self.agentClass = self.httpModule.Agent + } + } + + if (self.pool === false) { + self.agent = false + } else { + self.agent = self.agent || self.getAgent() + if (self.maxSockets) { + // Don't use our pooling if node has the refactored client + self.agent.maxSockets = self.maxSockets + } + if (self.pool.maxSockets) { + // Don't use our pooling if node has the refactored client + self.agent.maxSockets = self.pool.maxSockets + } + } + + self.on('pipe', function (src) { + if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.") + self.src = src + if (isReadStream(src)) { + if (!self.hasHeader('content-type')) self.setHeader('content-type', mime.lookup(src.path)) + } else { + if (src.headers) { + for (var i in src.headers) { + if (!self.hasHeader(i)) { + self.setHeader(i, src.headers[i]) + } + } + } + if (self._json && !self.hasHeader('content-type')) + self.setHeader('content-type', 'application/json') + if (src.method && !self.explicitMethod) { + self.method = src.method + } + } + + // self.on('pipe', function () { + // console.error("You have already piped to this stream. Pipeing twice is likely to break the request.") + // }) + }) + + process.nextTick(function () { + if (self._aborted) return + + var end = function () { + if (self._form) { + self._form.pipe(self) + } + if (self.body) { + if (Array.isArray(self.body)) { + self.body.forEach(function (part) { + self.write(part) + }) + } else { + self.write(self.body) + } + self.end() + } else if (self.requestBodyStream) { + console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.") + self.requestBodyStream.pipe(self) + } else if (!self.src) { + if (self.method !== 'GET' && typeof self.method !== 'undefined') { + self.setHeader('content-length', 0) + } + self.end() + } + } + + if (self._form && !self.hasHeader('content-length')) { + // Before ending the request, we had to compute the length of the whole form, asyncly + self.setHeaders(self._form.getHeaders()) + self._form.getLength(function (err, length) { + if (!err) { + self.setHeader('content-length', length) + } + end() + }) + } else { + end() + } + + self.ntick = true + }) + + } // End _buildRequest + + self._handleUnixSocketURI = function(self){ + // Parse URI and extract a socket path (tested as a valid socket using net.connect), and a http style path suffix + // Thus http requests can be made to a socket using the uri unix://tmp/my.socket/urlpath + // and a request for '/urlpath' will be sent to the unix socket at /tmp/my.socket + + self.unixsocket = true; + + var full_path = self.uri.href.replace(self.uri.protocol+'/', ''); + + var lookup = full_path.split('/'); + var error_connecting = true; + + var lookup_table = {}; + do { lookup_table[lookup.join('/')]={} } while(lookup.pop()) + for (r in lookup_table){ + try_next(r); + } + + function try_next(table_row){ + var client = net.connect( table_row ); + client.path = table_row + client.on('error', function(){ lookup_table[this.path].error_connecting=true; this.end(); }); + client.on('connect', function(){ lookup_table[this.path].error_connecting=false; this.end(); }); + table_row.client = client; + } + + wait_for_socket_response(); + + response_counter = 0; + + function wait_for_socket_response(){ + var detach; + if('undefined' == typeof setImmediate ) detach = process.nextTick + else detach = setImmediate; + detach(function(){ + // counter to prevent infinite blocking waiting for an open socket to be found. + response_counter++; + var trying = false; + for (r in lookup_table){ + //console.log(r, lookup_table[r], lookup_table[r].error_connecting) + if('undefined' == typeof lookup_table[r].error_connecting) + trying = true; + } + if(trying && response_counter<1000) + wait_for_socket_response() + else + set_socket_properties(); + }) + } + + function set_socket_properties(){ + var host; + for (r in lookup_table){ + if(lookup_table[r].error_connecting === false){ + host = r + } + } + if(!host){ + self.emit('error', new Error("Failed to connect to any socket in "+full_path)) + } + var path = full_path.replace(host, '') + + self.socketPath = host + self.uri.pathname = path + self.uri.href = path + self.uri.path = path + self.host = '' + self.hostname = '' + delete self.host + delete self.hostname + self._buildRequest(); + } + } + + // Intercept UNIX protocol requests to change properties to match socket + if(/^unix:/.test(self.uri.protocol)){ + self._handleUnixSocketURI(self); + } else { + self._buildRequest(); + } + +} + +// Must call this when following a redirect from https to http or vice versa +// Attempts to keep everything as identical as possible, but update the +// httpModule, Tunneling agent, and/or Forever Agent in use. +Request.prototype._updateProtocol = function () { + var self = this + var protocol = self.uri.protocol + + if (protocol === 'https:') { + // previously was doing http, now doing https + // if it's https, then we might need to tunnel now. + if (self.proxy && self.canTunnel) { + self.tunnel = true + var tunnelFn = self.proxy.protocol === 'http:' + ? tunnel.httpsOverHttp : tunnel.httpsOverHttps + var tunnelOptions = { proxy: { host: self.proxy.hostname + , port: +self.proxy.port + , proxyAuth: self.proxy.auth } + , rejectUnauthorized: self.rejectUnauthorized + , ca: self.ca } + self.agent = tunnelFn(tunnelOptions) + return + } + + self.httpModule = https + switch (self.agentClass) { + case ForeverAgent: + self.agentClass = ForeverAgent.SSL + break + case http.Agent: + self.agentClass = https.Agent + break + default: + // nothing we can do. Just hope for the best. + return + } + + // if there's an agent, we need to get a new one. + if (self.agent) self.agent = self.getAgent() + + } else { + // previously was doing https, now doing http + // stop any tunneling. + if (self.tunnel) self.tunnel = false + self.httpModule = http + switch (self.agentClass) { + case ForeverAgent.SSL: + self.agentClass = ForeverAgent + break + case https.Agent: + self.agentClass = http.Agent + break + default: + // nothing we can do. just hope for the best + return + } + + // if there's an agent, then get a new one. + if (self.agent) { + self.agent = null + self.agent = self.getAgent() + } + } +} + +Request.prototype.getAgent = function () { + var Agent = this.agentClass + var options = {} + if (this.agentOptions) { + for (var i in this.agentOptions) { + options[i] = this.agentOptions[i] + } + } + if (this.ca) options.ca = this.ca + if (this.ciphers) options.ciphers = this.ciphers + if (this.secureProtocol) options.secureProtocol = this.secureProtocol + if (this.secureOptions) options.secureOptions = this.secureOptions + if (typeof this.rejectUnauthorized !== 'undefined') options.rejectUnauthorized = this.rejectUnauthorized + + if (this.cert && this.key) { + options.key = this.key + options.cert = this.cert + } + + var poolKey = '' + + // different types of agents are in different pools + if (Agent !== this.httpModule.Agent) { + poolKey += Agent.name + } + + if (!this.httpModule.globalAgent) { + // node 0.4.x + options.host = this.host + options.port = this.port + if (poolKey) poolKey += ':' + poolKey += this.host + ':' + this.port + } + + // ca option is only relevant if proxy or destination are https + var proxy = this.proxy + if (typeof proxy === 'string') proxy = url.parse(proxy) + var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' + if (isHttps) { + if (options.ca) { + if (poolKey) poolKey += ':' + poolKey += options.ca + } + + if (typeof options.rejectUnauthorized !== 'undefined') { + if (poolKey) poolKey += ':' + poolKey += options.rejectUnauthorized + } + + if (options.cert) + poolKey += options.cert.toString('ascii') + options.key.toString('ascii') + + if (options.ciphers) { + if (poolKey) poolKey += ':' + poolKey += options.ciphers + } + + if (options.secureProtocol) { + if (poolKey) poolKey += ':' + poolKey += options.secureProtocol + } + + if (options.secureOptions) { + if (poolKey) poolKey += ':' + poolKey += options.secureOptions + } + } + + if (this.pool === globalPool && !poolKey && Object.keys(options).length === 0 && this.httpModule.globalAgent) { + // not doing anything special. Use the globalAgent + return this.httpModule.globalAgent + } + + // we're using a stored agent. Make sure it's protocol-specific + poolKey = this.uri.protocol + poolKey + + // already generated an agent for this setting + if (this.pool[poolKey]) return this.pool[poolKey] + + return this.pool[poolKey] = new Agent(options) +} + +Request.prototype.start = function () { + // start() is called once we are ready to send the outgoing HTTP request. + // this is usually called on the first write(), end() or on nextTick() + var self = this + + if (self._aborted) return + + self._started = true + self.method = self.method || 'GET' + self.href = self.uri.href + + if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { + self.setHeader('content-length', self.src.stat.size) + } + if (self._aws) { + self.aws(self._aws, true) + } + + // We have a method named auth, which is completely different from the http.request + // auth option. If we don't remove it, we're gonna have a bad time. + var reqOptions = copy(self) + delete reqOptions.auth + + debug('make request', self.uri.href) + self.req = self.httpModule.request(reqOptions, self.onResponse.bind(self)) + + if (self.timeout && !self.timeoutTimer) { + self.timeoutTimer = setTimeout(function () { + self.req.abort() + var e = new Error("ETIMEDOUT") + e.code = "ETIMEDOUT" + self.emit("error", e) + }, self.timeout) + + // Set additional timeout on socket - in case if remote + // server freeze after sending headers + if (self.req.setTimeout) { // only works on node 0.6+ + self.req.setTimeout(self.timeout, function () { + if (self.req) { + self.req.abort() + var e = new Error("ESOCKETTIMEDOUT") + e.code = "ESOCKETTIMEDOUT" + self.emit("error", e) + } + }) + } + } + + self.req.on('error', self.clientErrorHandler) + self.req.on('drain', function() { + self.emit('drain') + }) + self.on('end', function() { + if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler) + }) + self.emit('request', self.req) +} +Request.prototype.onResponse = function (response) { + var self = this + debug('onResponse', self.uri.href, response.statusCode, response.headers) + response.on('end', function() { + debug('response end', self.uri.href, response.statusCode, response.headers) + }); + + // The check on response.connection is a workaround for browserify. + if (response.connection && response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) { + response.connection.setMaxListeners(0) + response.connection.once('error', self._parserErrorHandler) + } + if (self._aborted) { + debug('aborted', self.uri.href) + response.resume() + return + } + if (self._paused) response.pause() + // Check that response.resume is defined. Workaround for browserify. + else response.resume && response.resume() + + self.response = response + response.request = self + response.toJSON = toJSON + + // XXX This is different on 0.10, because SSL is strict by default + if (self.httpModule === https && + self.strictSSL && + !response.client.authorized) { + debug('strict ssl error', self.uri.href) + var sslErr = response.client.authorizationError + self.emit('error', new Error('SSL Error: '+ sslErr)) + return + } + + if (self.setHost && self.hasHeader('host')) delete self.headers[self.hasHeader('host')] + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + + var targetCookieJar = (self._jar && self._jar.setCookie)?self._jar:globalCookieJar; + var addCookie = function (cookie) { + //set the cookie if it's domain in the href's domain. + try { + targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}); + } catch (e) { + self.emit('error', e); + } + } + + if (hasHeader('set-cookie', response.headers) && (!self._disableCookies)) { + var headerName = hasHeader('set-cookie', response.headers) + if (Array.isArray(response.headers[headerName])) response.headers[headerName].forEach(addCookie) + else addCookie(response.headers[headerName]) + } + + var redirectTo = null + if (response.statusCode >= 300 && response.statusCode < 400 && hasHeader('location', response.headers)) { + var location = response.headers[hasHeader('location', response.headers)] + debug('redirect', location) + + if (self.followAllRedirects) { + redirectTo = location + } else if (self.followRedirect) { + switch (self.method) { + case 'PATCH': + case 'PUT': + case 'POST': + case 'DELETE': + // Do not follow redirects + break + default: + redirectTo = location + break + } + } + } else if (response.statusCode == 401 && self._hasAuth && !self._sentAuth) { + var authHeader = response.headers[hasHeader('www-authenticate', response.headers)] + var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() + debug('reauth', authVerb) + + switch (authVerb) { + case 'basic': + self.auth(self._user, self._pass, true) + redirectTo = self.uri + break + + case 'bearer': + self.auth(null, null, true, self._bearer) + redirectTo = self.uri + break + + case 'digest': + // TODO: More complete implementation of RFC 2617. + // - check challenge.algorithm + // - support algorithm="MD5-sess" + // - handle challenge.domain + // - support qop="auth-int" only + // - handle Authentication-Info (not necessarily?) + // - check challenge.stale (not necessarily?) + // - increase nc (not necessarily?) + // For reference: + // http://tools.ietf.org/html/rfc2617#section-3 + // https://github.com/bagder/curl/blob/master/lib/http_digest.c + + var challenge = {} + var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi + for (;;) { + var match = re.exec(authHeader) + if (!match) break + challenge[match[1]] = match[2] || match[3]; + } + + var ha1 = md5(self._user + ':' + challenge.realm + ':' + self._pass) + var ha2 = md5(self.method + ':' + self.uri.path) + var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' + var nc = qop && '00000001' + var cnonce = qop && uuid().replace(/-/g, '') + var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2) + var authValues = { + username: self._user, + realm: challenge.realm, + nonce: challenge.nonce, + uri: self.uri.path, + qop: qop, + response: digestResponse, + nc: nc, + cnonce: cnonce, + algorithm: challenge.algorithm, + opaque: challenge.opaque + } + + authHeader = [] + for (var k in authValues) { + if (!authValues[k]) { + //ignore + } else if (k === 'qop' || k === 'nc' || k === 'algorithm') { + authHeader.push(k + '=' + authValues[k]) + } else { + authHeader.push(k + '="' + authValues[k] + '"') + } + } + authHeader = 'Digest ' + authHeader.join(', ') + self.setHeader('authorization', authHeader) + self._sentAuth = true + + redirectTo = self.uri + break + } + } + + if (redirectTo) { + debug('redirect to', redirectTo) + + // ignore any potential response body. it cannot possibly be useful + // to us at this point. + if (self._paused) response.resume() + + if (self._redirectsFollowed >= self.maxRedirects) { + self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href)) + return + } + self._redirectsFollowed += 1 + + if (!isUrl.test(redirectTo)) { + redirectTo = url.resolve(self.uri.href, redirectTo) + } + + var uriPrev = self.uri + self.uri = url.parse(redirectTo) + + // handle the case where we change protocol from https to http or vice versa + if (self.uri.protocol !== uriPrev.protocol) { + self._updateProtocol() + } + + self.redirects.push( + { statusCode : response.statusCode + , redirectUri: redirectTo + } + ) + if (self.followAllRedirects && response.statusCode != 401 && response.statusCode != 307) self.method = 'GET' + // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215 + delete self.src + delete self.req + delete self.agent + delete self._started + if (response.statusCode != 401 && response.statusCode != 307) { + // Remove parameters from the previous response, unless this is the second request + // for a server that requires digest authentication. + delete self.body + delete self._form + if (self.headers) { + if (self.hasHeader('host')) delete self.headers[self.hasHeader('host')] + if (self.hasHeader('content-type')) delete self.headers[self.hasHeader('content-type')] + if (self.hasHeader('content-length')) delete self.headers[self.hasHeader('content-length')] + } + } + + self.emit('redirect'); + + self.init() + return // Ignore the rest of the response + } else { + self._redirectsFollowed = self._redirectsFollowed || 0 + // Be a good stream and emit end when the response is finished. + // Hack to emit end on close because of a core bug that never fires end + response.on('close', function () { + if (!self._ended) self.response.emit('end') + }) + + var dataStream + if (self.gzip) { + var contentEncoding = response.headers["content-encoding"] || "identity" + contentEncoding = contentEncoding.trim().toLowerCase() + + if (contentEncoding === "gzip") { + dataStream = zlib.createGunzip() + response.pipe(dataStream) + } else { + // Since previous versions didn't check for Content-Encoding header, + // ignore any invalid values to preserve backwards-compatibility + if (contentEncoding !== "identity") { + debug("ignoring unrecognized Content-Encoding " + contentEncoding) + } + dataStream = response + } + } else { + dataStream = response + } + + if (self.encoding) { + if (self.dests.length !== 0) { + console.error("Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") + } else if (dataStream.setEncoding) { + dataStream.setEncoding(self.encoding) + } else { + // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with + // zlib streams. + // If/When support for 0.9.4 is dropped, this should be unnecessary. + dataStream = dataStream.pipe(stringstream(self.encoding)) + } + } + + self.emit('response', response) + + self.dests.forEach(function (dest) { + self.pipeDest(dest) + }) + + dataStream.on("data", function (chunk) { + self._destdata = true + self.emit("data", chunk) + }) + dataStream.on("end", function (chunk) { + self._ended = true + self.emit("end", chunk) + }) + dataStream.on("close", function () {self.emit("close")}) + + if (self.callback) { + var buffer = [] + var bodyLen = 0 + self.on("data", function (chunk) { + buffer.push(chunk) + bodyLen += chunk.length + }) + self.on("end", function () { + debug('end event', self.uri.href) + if (self._aborted) { + debug('aborted', self.uri.href) + return + } + + if (buffer.length && Buffer.isBuffer(buffer[0])) { + debug('has body', self.uri.href, bodyLen) + var body = new Buffer(bodyLen) + var i = 0 + buffer.forEach(function (chunk) { + chunk.copy(body, i, 0, chunk.length) + i += chunk.length + }) + if (self.encoding === null) { + response.body = body + } else { + response.body = body.toString(self.encoding) + } + } else if (buffer.length) { + // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. + // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). + if (self.encoding === 'utf8' && buffer[0].length > 0 && buffer[0][0] === "\uFEFF") { + buffer[0] = buffer[0].substring(1) + } + response.body = buffer.join('') + } + + if (self._json) { + try { + response.body = JSON.parse(response.body) + } catch (e) {} + } + debug('emitting complete', self.uri.href) + if(response.body == undefined && !self._json) { + response.body = ""; + } + self.emit('complete', response, response.body) + }) + } + //if no callback + else{ + self.on("end", function () { + if (self._aborted) { + debug('aborted', self.uri.href) + return + } + self.emit('complete', response); + }); + } + } + debug('finish init function', self.uri.href) +} + +Request.prototype.abort = function () { + this._aborted = true + + if (this.req) { + this.req.abort() + } + else if (this.response) { + this.response.abort() + } + + this.emit("abort") +} + +Request.prototype.pipeDest = function (dest) { + var response = this.response + // Called after the response is received + if (dest.headers && !dest.headersSent) { + if (hasHeader('content-type', response.headers)) { + var ctname = hasHeader('content-type', response.headers) + if (dest.setHeader) dest.setHeader(ctname, response.headers[ctname]) + else dest.headers[ctname] = response.headers[ctname] + } + + if (hasHeader('content-length', response.headers)) { + var clname = hasHeader('content-length', response.headers) + if (dest.setHeader) dest.setHeader(clname, response.headers[clname]) + else dest.headers[clname] = response.headers[clname] + } + } + if (dest.setHeader && !dest.headersSent) { + for (var i in response.headers) { + // If the response content is being decoded, the Content-Encoding header + // of the response doesn't represent the piped content, so don't pass it. + if (!this.gzip || i !== 'content-encoding') { + dest.setHeader(i, response.headers[i]) + } + } + dest.statusCode = response.statusCode + } + if (this.pipefilter) this.pipefilter(response, dest) +} + +// Composable API +Request.prototype.setHeader = function (name, value, clobber) { + if (clobber === undefined) clobber = true + if (clobber || !this.hasHeader(name)) this.headers[name] = value + else this.headers[this.hasHeader(name)] += ',' + value + return this +} +Request.prototype.setHeaders = function (headers) { + for (var i in headers) {this.setHeader(i, headers[i])} + return this +} +Request.prototype.hasHeader = function (header, headers) { + var headers = Object.keys(headers || this.headers) + , lheaders = headers.map(function (h) {return h.toLowerCase()}) + ; + header = header.toLowerCase() + for (var i=0;i.js` +and export your test functions with names that start with "test", for example + + exports["test doing the foo bar"] = function (assert, util) { + ... + }; + +The new test will be located automatically when you run the suite. + +The `util` argument is the test utility module located at `test/source-map/util`. + +The `assert` argument is a cut down version of node's assert module. You have +access to the following assertion functions: + +* `doesNotThrow` + +* `equal` + +* `ok` + +* `strictEqual` + +* `throws` + +(The reason for the restricted set of test functions is because we need the +tests to run inside Firefox's test suite as well and so the assert module is +shimmed in that environment. See `build/assert-shim.js`.) + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit +[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap +[Dryice]: https://github.com/mozilla/dryice diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/assert-shim.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/assert-shim.js new file mode 100644 index 000000000..daa1a623c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/assert-shim.js @@ -0,0 +1,56 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +define('test/source-map/assert', ['exports'], function (exports) { + + let do_throw = function (msg) { + throw new Error(msg); + }; + + exports.init = function (throw_fn) { + do_throw = throw_fn; + }; + + exports.doesNotThrow = function (fn) { + try { + fn(); + } + catch (e) { + do_throw(e.message); + } + }; + + exports.equal = function (actual, expected, msg) { + msg = msg || String(actual) + ' != ' + String(expected); + if (actual != expected) { + do_throw(msg); + } + }; + + exports.ok = function (val, msg) { + msg = msg || String(val) + ' is falsey'; + if (!Boolean(val)) { + do_throw(msg); + } + }; + + exports.strictEqual = function (actual, expected, msg) { + msg = msg || String(actual) + ' !== ' + String(expected); + if (actual !== expected) { + do_throw(msg); + } + }; + + exports.throws = function (fn) { + try { + fn(); + do_throw('Expected an error to be thrown, but it wasn\'t.'); + } + catch (e) { + } + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/mini-require.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/mini-require.js new file mode 100644 index 000000000..0daf45377 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/mini-require.js @@ -0,0 +1,152 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * Define a module along with a payload. + * @param {string} moduleName Name for the payload + * @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec + * @param {function} payload Function with (require, exports, module) params + */ +function define(moduleName, deps, payload) { + if (typeof moduleName != "string") { + throw new TypeError('Expected string, got: ' + moduleName); + } + + if (arguments.length == 2) { + payload = deps; + } + + if (moduleName in define.modules) { + throw new Error("Module already defined: " + moduleName); + } + define.modules[moduleName] = payload; +}; + +/** + * The global store of un-instantiated modules + */ +define.modules = {}; + + +/** + * We invoke require() in the context of a Domain so we can have multiple + * sets of modules running separate from each other. + * This contrasts with JSMs which are singletons, Domains allows us to + * optionally load a CommonJS module twice with separate data each time. + * Perhaps you want 2 command lines with a different set of commands in each, + * for example. + */ +function Domain() { + this.modules = {}; + this._currentModule = null; +} + +(function () { + + /** + * Lookup module names and resolve them by calling the definition function if + * needed. + * There are 2 ways to call this, either with an array of dependencies and a + * callback to call when the dependencies are found (which can happen + * asynchronously in an in-page context) or with a single string an no callback + * where the dependency is resolved synchronously and returned. + * The API is designed to be compatible with the CommonJS AMD spec and + * RequireJS. + * @param {string[]|string} deps A name, or names for the payload + * @param {function|undefined} callback Function to call when the dependencies + * are resolved + * @return {undefined|object} The module required or undefined for + * array/callback method + */ + Domain.prototype.require = function(deps, callback) { + if (Array.isArray(deps)) { + var params = deps.map(function(dep) { + return this.lookup(dep); + }, this); + if (callback) { + callback.apply(null, params); + } + return undefined; + } + else { + return this.lookup(deps); + } + }; + + function normalize(path) { + var bits = path.split('/'); + var i = 1; + while (i < bits.length) { + if (bits[i] === '..') { + bits.splice(i-1, 1); + } else if (bits[i] === '.') { + bits.splice(i, 1); + } else { + i++; + } + } + return bits.join('/'); + } + + function join(a, b) { + a = a.trim(); + b = b.trim(); + if (/^\//.test(b)) { + return b; + } else { + return a.replace(/\/*$/, '/') + b; + } + } + + function dirname(path) { + var bits = path.split('/'); + bits.pop(); + return bits.join('/'); + } + + /** + * Lookup module names and resolve them by calling the definition function if + * needed. + * @param {string} moduleName A name for the payload to lookup + * @return {object} The module specified by aModuleName or null if not found. + */ + Domain.prototype.lookup = function(moduleName) { + if (/^\./.test(moduleName)) { + moduleName = normalize(join(dirname(this._currentModule), moduleName)); + } + + if (moduleName in this.modules) { + var module = this.modules[moduleName]; + return module; + } + + if (!(moduleName in define.modules)) { + throw new Error("Module not defined: " + moduleName); + } + + var module = define.modules[moduleName]; + + if (typeof module == "function") { + var exports = {}; + var previousModule = this._currentModule; + this._currentModule = moduleName; + module(this.require.bind(this), exports, { id: moduleName, uri: "" }); + this._currentModule = previousModule; + module = exports; + } + + // cache the resulting module object for next time + this.modules[moduleName] = module; + + return module; + }; + +}()); + +define.Domain = Domain; +define.globalDomain = new Domain(); +var require = define.globalDomain.require.bind(define.globalDomain); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-source-map.jsm b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-source-map.jsm new file mode 100644 index 000000000..ee2539d81 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-source-map.jsm @@ -0,0 +1,20 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +/////////////////////////////////////////////////////////////////////////////// + + +this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ]; + +Components.utils.import('resource://gre/modules/devtools/Require.jsm'); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-utils.jsm b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-utils.jsm new file mode 100644 index 000000000..80341d452 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/prefix-utils.jsm @@ -0,0 +1,18 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +Components.utils.import('resource://gre/modules/devtools/Require.jsm'); +Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm'); + +this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ]; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-browser.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-browser.js new file mode 100644 index 000000000..fb29ff5fd --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-browser.js @@ -0,0 +1,8 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/////////////////////////////////////////////////////////////////////////////// + +this.sourceMap = { + SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer, + SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator, + SourceNode: require('source-map/source-node').SourceNode +}; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-source-map.jsm b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-source-map.jsm new file mode 100644 index 000000000..cf3c2d8d3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-source-map.jsm @@ -0,0 +1,6 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/////////////////////////////////////////////////////////////////////////////// + +this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer; +this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator; +this.SourceNode = require('source-map/source-node').SourceNode; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-utils.jsm b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-utils.jsm new file mode 100644 index 000000000..b31b84cb6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/suffix-utils.jsm @@ -0,0 +1,21 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +function runSourceMapTests(modName, do_throw) { + let mod = require(modName); + let assert = require('test/source-map/assert'); + let util = require('test/source-map/util'); + + assert.init(do_throw); + + for (let k in mod) { + if (/^test/.test(k)) { + mod[k](assert, util); + } + } + +} +this.runSourceMapTests = runSourceMapTests; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-prefix.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-prefix.js new file mode 100644 index 000000000..1b13f300e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-prefix.js @@ -0,0 +1,8 @@ +/* + * WARNING! + * + * Do not edit this file directly, it is built from the sources at + * https://github.com/mozilla/source-map/ + */ + +Components.utils.import('resource://test/Utils.jsm'); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-suffix.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-suffix.js new file mode 100644 index 000000000..bec2de3f2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/build/test-suffix.js @@ -0,0 +1,3 @@ +function run_test() { + runSourceMapTests('{THIS_MODULE}', do_throw); +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map.js new file mode 100644 index 000000000..121ad2416 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./source-map/source-node').SourceNode; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/array-set.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/array-set.js new file mode 100644 index 000000000..40f9a18b1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/array-set.js @@ -0,0 +1,97 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = {}; + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var isDuplicate = this.has(aStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[util.toSetString(aStr)] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + return Object.prototype.hasOwnProperty.call(this._set, + util.toSetString(aStr)); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (this.has(aStr)) { + return this._set[util.toSetString(aStr)]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64-vlq.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64-vlq.js new file mode 100644 index 000000000..1b67bb375 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64-vlq.js @@ -0,0 +1,144 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64 = require('./base64'); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string. + */ + exports.decode = function base64VLQ_decode(aStr) { + var i = 0; + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (i >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + digit = base64.decode(aStr.charAt(i++)); + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + return { + value: fromVLQSigned(result), + rest: aStr.slice(i) + }; + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64.js new file mode 100644 index 000000000..863cc4650 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/base64.js @@ -0,0 +1,42 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var charToIntMap = {}; + var intToCharMap = {}; + + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + .split('') + .forEach(function (ch, index) { + charToIntMap[ch] = index; + intToCharMap[index] = ch; + }); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function base64_encode(aNumber) { + if (aNumber in intToCharMap) { + return intToCharMap[aNumber]; + } + throw new TypeError("Must be between 0 and 63: " + aNumber); + }; + + /** + * Decode a single base 64 digit to an integer. + */ + exports.decode = function base64_decode(aChar) { + if (aChar in charToIntMap) { + return charToIntMap[aChar]; + } + throw new TypeError("Not a valid base 64 digit: " + aChar); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/binary-search.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/binary-search.js new file mode 100644 index 000000000..ff347c68b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/binary-search.js @@ -0,0 +1,81 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the next + // closest element that is less than that element. + // + // 3. We did not find the exact element, and there is no next-closest + // element which is less than the one we are searching for, so we + // return null. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return aHaystack[mid]; + } + else if (cmp > 0) { + // aHaystack[mid] is greater than our needle. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); + } + // We did not find an exact match, return the next closest one + // (termination case 2). + return aHaystack[mid]; + } + else { + // aHaystack[mid] is less than our needle. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); + } + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (2) or (3) and return the appropriate thing. + return aLow < 0 + ? null + : aHaystack[aLow]; + } + } + + /** + * This is an implementation of binary search which will always try and return + * the next lowest value checked if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + */ + exports.search = function search(aNeedle, aHaystack, aCompare) { + return aHaystack.length > 0 + ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) + : null; + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-consumer.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-consumer.js new file mode 100644 index 000000000..eec18bd3a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-consumer.js @@ -0,0 +1,478 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + var binarySearch = require('./binary-search'); + var ArraySet = require('./array-set').ArraySet; + var base64VLQ = require('./base64-vlq'); + + /** + * A SourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names, true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + /** + * Create a SourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns SourceMapConsumer + */ + SourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(SourceMapConsumer.prototype); + + smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + smc.__generatedMappings = aSourceMap._mappings.slice() + .sort(util.compareByGeneratedPositions); + smc.__originalMappings = aSourceMap._mappings.slice() + .sort(util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(SourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var mappingSeparator = /^[,;]/; + var str = aStr; + var mapping; + var temp; + + while (str.length > 0) { + if (str.charAt(0) === ';') { + generatedLine++; + str = str.slice(1); + previousGeneratedColumn = 0; + } + else if (str.charAt(0) === ',') { + str = str.slice(1); + } + else { + mapping = {}; + mapping.generatedLine = generatedLine; + + // Generated column. + temp = base64VLQ.decode(str); + mapping.generatedColumn = previousGeneratedColumn + temp.value; + previousGeneratedColumn = mapping.generatedColumn; + str = temp.rest; + + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + // Original source. + temp = base64VLQ.decode(str); + mapping.source = this._sources.at(previousSource + temp.value); + previousSource += temp.value; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source, but no line and column'); + } + + // Original line. + temp = base64VLQ.decode(str); + mapping.originalLine = previousOriginalLine + temp.value; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source and line, but no column'); + } + + // Original column. + temp = base64VLQ.decode(str); + mapping.originalColumn = previousOriginalColumn + temp.value; + previousOriginalColumn = mapping.originalColumn; + str = temp.rest; + + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + // Original name. + temp = base64VLQ.decode(str); + mapping.name = this._names.at(previousName + temp.value); + previousName += temp.value; + str = temp.rest; + } + } + + this.__generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + this.__originalMappings.push(mapping); + } + } + } + + this.__generatedMappings.sort(util.compareByGeneratedPositions); + this.__originalMappings.sort(util.compareByOriginalPositions); + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + SourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator); + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + SourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var mapping = this._findMapping(needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositions); + + if (mapping && mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source != null && this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: util.getArg(mapping, 'name', null) + }; + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * availible. + */ + SourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + throw new Error('"' + aSource + '" is not in the SourceMap.'); + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + + var mapping = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions); + + if (mapping) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null) + }; + } + + return { + line: null, + column: null + }; + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source; + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name + }; + }).forEach(aCallback, context); + }; + + exports.SourceMapConsumer = SourceMapConsumer; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-generator.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-generator.js new file mode 100644 index 000000000..1135c3d86 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-map-generator.js @@ -0,0 +1,403 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64VLQ = require('./base64-vlq'); + var util = require('./util'); + var ArraySet = require('./array-set').ArraySet; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = []; + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + this._validateMapping(generated, original, source, name); + + if (source != null && !this._sources.has(source)) { + this._sources.add(source); + } + + if (name != null && !this._names.has(name)) { + this._names.add(name); + } + + this._mappings.push({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = {}; + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.forEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null && mapping.name != null) { + // Only use the identifier name if it's an identifier + // in both SourceMaps + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var mapping; + + // The mappings must be guaranteed to be in sorted order before we start + // serializing them or else the generated line numbers (which are defined + // via the ';' separators) will be all messed up. Note: it might be more + // performant to maintain the sorting as we insert them, rather than as we + // serialize them, but the big O is the same either way. + this._mappings.sort(util.compareByGeneratedPositions); + + for (var i = 0, len = this._mappings.length; i < len; i++) { + mapping = this._mappings[i]; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + result += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { + continue; + } + result += ','; + } + } + + result += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + result += base64VLQ.encode(this._sources.indexOf(mapping.source) + - previousSource); + previousSource = this._sources.indexOf(mapping.source); + + // lines are stored 0-based in SourceMap spec version 3 + result += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + result += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + result += base64VLQ.encode(this._names.indexOf(mapping.name) + - previousName); + previousName = this._names.indexOf(mapping.name); + } + } + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, + key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-node.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-node.js new file mode 100644 index 000000000..baa5f4092 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/source-node.js @@ -0,0 +1,408 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; + var util = require('./util'); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Matches a Windows-style newline, or any character. + var REGEX_CHARACTER = /\r\n|[\s\S]/g; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + var code = ""; + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk instanceof SourceNode || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk instanceof SourceNode || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk instanceof SourceNode) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild instanceof SourceNode) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i] instanceof SourceNode) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) { + if (REGEX_NEWLINE.test(ch)) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === array.length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column += ch.length; + } + }); + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/util.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/util.js new file mode 100644 index 000000000..976f6cabb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/lib/source-map/util.js @@ -0,0 +1,319 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '
    /..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = (path.charAt(0) === '/'); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // XXX: It is possible to remove this block, and the tests still pass! + var url = urlParse(aRoot); + if (aPath.charAt(0) == "/" && url && url.path == "/") { + return aPath.slice(1); + } + + return aPath.indexOf(aRoot + '/') === 0 + ? aPath.substr(aRoot.length + 1) + : aPath; + } + exports.relative = relative; + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + return '$' + aStr; + } + exports.toSetString = toSetString; + + function fromSetString(aStr) { + return aStr.substr(1); + } + exports.fromSetString = fromSetString; + + function strcmp(aStr1, aStr2) { + var s1 = aStr1 || ""; + var s2 = aStr2 || ""; + return (s1 > s2) - (s1 < s2); + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp; + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp || onlyCompareOriginal) { + return cmp; + } + + cmp = strcmp(mappingA.name, mappingB.name); + if (cmp) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + + return mappingA.generatedColumn - mappingB.generatedColumn; + }; + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings where the generated positions are + * compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { + var cmp; + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + }; + exports.compareByGeneratedPositions = compareByGeneratedPositions; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/LICENSE b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/LICENSE new file mode 100644 index 000000000..f33d665de --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/LICENSE @@ -0,0 +1,58 @@ +amdefine is released under two licenses: new BSD, and MIT. You may pick the +license that best suits your development needs. The text of both licenses are +provided below. + + +The "New" BSD License: +---------------------- + +Copyright (c) 2011, The Dojo Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the Dojo Foundation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +MIT License +----------- + +Copyright (c) 2011, The Dojo Foundation + +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/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/README.md b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/README.md new file mode 100644 index 000000000..c6995c072 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/README.md @@ -0,0 +1,171 @@ +# amdefine + +A module that can be used to implement AMD's define() in Node. This allows you +to code to the AMD API and have the module work in node programs without +requiring those other programs to use AMD. + +## Usage + +**1)** Update your package.json to indicate amdefine as a dependency: + +```javascript + "dependencies": { + "amdefine": ">=0.1.0" + } +``` + +Then run `npm install` to get amdefine into your project. + +**2)** At the top of each module that uses define(), place this code: + +```javascript +if (typeof define !== 'function') { var define = require('amdefine')(module) } +``` + +**Only use these snippets** when loading amdefine. If you preserve the basic structure, +with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer). + +You can add spaces, line breaks and even require amdefine with a local path, but +keep the rest of the structure to get the stripping behavior. + +As you may know, because `if` statements in JavaScript don't have their own scope, the var +declaration in the above snippet is made whether the `if` expression is truthy or not. If +RequireJS is loaded then the declaration is superfluous because `define` is already already +declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var` +declarations of the same variable in the same scope gracefully. + +If you want to deliver amdefine.js with your code rather than specifying it as a dependency +with npm, then just download the latest release and refer to it using a relative path: + +[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js) + +### amdefine/intercept + +Consider this very experimental. + +Instead of pasting the piece of text for the amdefine setup of a `define` +variable in each module you create or consume, you can use `amdefine/intercept` +instead. It will automatically insert the above snippet in each .js file loaded +by Node. + +**Warning**: you should only use this if you are creating an application that +is consuming AMD style defined()'d modules that are distributed via npm and want +to run that code in Node. + +For library code where you are not sure if it will be used by others in Node or +in the browser, then explicitly depending on amdefine and placing the code +snippet above is suggested path, instead of using `amdefine/intercept`. The +intercept module affects all .js files loaded in the Node app, and it is +inconsiderate to modify global state like that unless you are also controlling +the top level app. + +#### Why distribute AMD-style nodes via npm? + +npm has a lot of weaknesses for front-end use (installed layout is not great, +should have better support for the `baseUrl + moduleID + '.js' style of loading, +single file JS installs), but some people want a JS package manager and are +willing to live with those constraints. If that is you, but still want to author +in AMD style modules to get dynamic require([]), better direct source usage and +powerful loader plugin support in the browser, then this tool can help. + +#### amdefine/intercept usage + +Just require it in your top level app module (for example index.js, server.js): + +```javascript +require('amdefine/intercept'); +``` + +The module does not return a value, so no need to assign the result to a local +variable. + +Then just require() code as you normally would with Node's require(). Any .js +loaded after the intercept require will have the amdefine check injected in +the .js source as it is loaded. It does not modify the source on disk, just +prepends some content to the text of the module as it is loaded by Node. + +#### How amdefine/intercept works + +It overrides the `Module._extensions['.js']` in Node to automatically prepend +the amdefine snippet above. So, it will affect any .js file loaded by your +app. + +## define() usage + +It is best if you use the anonymous forms of define() in your module: + +```javascript +define(function (require) { + var dependency = require('dependency'); +}); +``` + +or + +```javascript +define(['dependency'], function (dependency) { + +}); +``` + +## RequireJS optimizer integration. + +Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html) +will have support for stripping the `if (typeof define !== 'function')` check +mentioned above, so you can include this snippet for code that runs in the +browser, but avoid taking the cost of the if() statement once the code is +optimized for deployment. + +## Node 0.4 Support + +If you want to support Node 0.4, then add `require` as the second parameter to amdefine: + +```javascript +//Only if you want Node 0.4. If using 0.5 or later, use the above snippet. +if (typeof define !== 'function') { var define = require('amdefine')(module, require) } +``` + +## Limitations + +### Synchronous vs Asynchronous + +amdefine creates a define() function that is callable by your code. It will +execute and trace dependencies and call the factory function *synchronously*, +to keep the behavior in line with Node's synchronous dependency tracing. + +The exception: calling AMD's callback-style require() from inside a factory +function. The require callback is called on process.nextTick(): + +```javascript +define(function (require) { + require(['a'], function(a) { + //'a' is loaded synchronously, but + //this callback is called on process.nextTick(). + }); +}); +``` + +### Loader Plugins + +Loader plugins are supported as long as they call their load() callbacks +synchronously. So ones that do network requests will not work. However plugins +like [text](http://requirejs.org/docs/api.html#text) can load text files locally. + +The plugin API's `load.fromText()` is **not supported** in amdefine, so this means +transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs) +will not work. This may be fixable, but it is a bit complex, and I do not have +enough node-fu to figure it out yet. See the source for amdefine.js if you want +to get an idea of the issues involved. + +## Tests + +To run the tests, cd to **tests** and run: + +``` +node all.js +node all-intercept.js +``` + +## License + +New BSD and MIT. Check the LICENSE file for all the details. diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/amdefine.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/amdefine.js new file mode 100644 index 000000000..53bf5a686 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/amdefine.js @@ -0,0 +1,299 @@ +/** vim: et:ts=4:sw=4:sts=4 + * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/jrburke/amdefine for details + */ + +/*jslint node: true */ +/*global module, process */ +'use strict'; + +/** + * Creates a define for node. + * @param {Object} module the "module" object that is defined by Node for the + * current module. + * @param {Function} [requireFn]. Node's require function for the current module. + * It only needs to be passed in Node versions before 0.5, when module.require + * did not exist. + * @returns {Function} a define function that is usable for the current node + * module. + */ +function amdefine(module, requireFn) { + 'use strict'; + var defineCache = {}, + loaderCache = {}, + alreadyCalled = false, + path = require('path'), + makeRequire, stringRequire; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; ary[i]; i+= 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + function normalize(name, baseName) { + var baseParts; + + //Adjust any relative paths. + if (name && name.charAt(0) === '.') { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if (baseName) { + baseParts = baseName.split('/'); + baseParts = baseParts.slice(0, baseParts.length - 1); + baseParts = baseParts.concat(name.split('/')); + trimDots(baseParts); + name = baseParts.join('/'); + } + } + + return name; + } + + /** + * Create the normalize() function passed to a loader plugin's + * normalize method. + */ + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } + + function makeLoad(id) { + function load(value) { + loaderCache[id] = value; + } + + load.fromText = function (id, text) { + //This one is difficult because the text can/probably uses + //define, and any relative paths and requires should be relative + //to that id was it would be found on disk. But this would require + //bootstrapping a module/require fairly deeply from node core. + //Not sure how best to go about that yet. + throw new Error('amdefine does not implement load.fromText'); + }; + + return load; + } + + makeRequire = function (systemRequire, exports, module, relId) { + function amdRequire(deps, callback) { + if (typeof deps === 'string') { + //Synchronous, single module require('') + return stringRequire(systemRequire, exports, module, deps, relId); + } else { + //Array of dependencies with a callback. + + //Convert the dependencies to modules. + deps = deps.map(function (depName) { + return stringRequire(systemRequire, exports, module, depName, relId); + }); + + //Wait for next tick to call back the require call. + process.nextTick(function () { + callback.apply(null, deps); + }); + } + } + + amdRequire.toUrl = function (filePath) { + if (filePath.indexOf('.') === 0) { + return normalize(filePath, path.dirname(module.filename)); + } else { + return filePath; + } + }; + + return amdRequire; + }; + + //Favor explicit value, passed in if the module wants to support Node 0.4. + requireFn = requireFn || function req() { + return module.require.apply(module, arguments); + }; + + function runFactory(id, deps, factory) { + var r, e, m, result; + + if (id) { + e = loaderCache[id] = {}; + m = { + id: id, + uri: __filename, + exports: e + }; + r = makeRequire(requireFn, e, m, id); + } else { + //Only support one define call per file + if (alreadyCalled) { + throw new Error('amdefine with no module ID cannot be called more than once per file.'); + } + alreadyCalled = true; + + //Use the real variables from node + //Use module.exports for exports, since + //the exports in here is amdefine exports. + e = module.exports; + m = module; + r = makeRequire(requireFn, e, m, module.id); + } + + //If there are dependencies, they are strings, so need + //to convert them to dependency values. + if (deps) { + deps = deps.map(function (depName) { + return r(depName); + }); + } + + //Call the factory with the right dependencies. + if (typeof factory === 'function') { + result = factory.apply(m.exports, deps); + } else { + result = factory; + } + + if (result !== undefined) { + m.exports = result; + if (id) { + loaderCache[id] = m.exports; + } + } + } + + stringRequire = function (systemRequire, exports, module, id, relId) { + //Split the ID by a ! so that + var index = id.indexOf('!'), + originalId = id, + prefix, plugin; + + if (index === -1) { + id = normalize(id, relId); + + //Straight module lookup. If it is one of the special dependencies, + //deal with it, otherwise, delegate to node. + if (id === 'require') { + return makeRequire(systemRequire, exports, module, relId); + } else if (id === 'exports') { + return exports; + } else if (id === 'module') { + return module; + } else if (loaderCache.hasOwnProperty(id)) { + return loaderCache[id]; + } else if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; + } else { + if(systemRequire) { + return systemRequire(originalId); + } else { + throw new Error('No module with ID: ' + id); + } + } + } else { + //There is a plugin in play. + prefix = id.substring(0, index); + id = id.substring(index + 1, id.length); + + plugin = stringRequire(systemRequire, exports, module, prefix, relId); + + if (plugin.normalize) { + id = plugin.normalize(id, makeNormalize(relId)); + } else { + //Normalize the ID normally. + id = normalize(id, relId); + } + + if (loaderCache[id]) { + return loaderCache[id]; + } else { + plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); + + return loaderCache[id]; + } + } + }; + + //Create a define function specific to the module asking for amdefine. + function define(id, deps, factory) { + if (Array.isArray(id)) { + factory = deps; + deps = id; + id = undefined; + } else if (typeof id !== 'string') { + factory = id; + id = deps = undefined; + } + + if (deps && !Array.isArray(deps)) { + factory = deps; + deps = undefined; + } + + if (!deps) { + deps = ['require', 'exports', 'module']; + } + + //Set up properties for this module. If an ID, then use + //internal cache. If no ID, then use the external variables + //for this node module. + if (id) { + //Put the module in deep freeze until there is a + //require call for it. + defineCache[id] = [id, deps, factory]; + } else { + runFactory(id, deps, factory); + } + } + + //define.require, which has access to all the values in the + //cache. Useful for AMD modules that all have IDs in the file, + //but need to finally export a value to node based on one of those + //IDs. + define.require = function (id) { + if (loaderCache[id]) { + return loaderCache[id]; + } + + if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; + } + }; + + define.amd = {}; + + return define; +} + +module.exports = amdefine; diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/intercept.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/intercept.js new file mode 100644 index 000000000..771a98301 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/intercept.js @@ -0,0 +1,36 @@ +/*jshint node: true */ +var inserted, + Module = require('module'), + fs = require('fs'), + existingExtFn = Module._extensions['.js'], + amdefineRegExp = /amdefine\.js/; + +inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}"; + +//From the node/lib/module.js source: +function stripBOM(content) { + // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + // because the buffer-to-string conversion in `fs.readFileSync()` + // translates it to FEFF, the UTF-16 BOM. + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +//Also adapted from the node/lib/module.js source: +function intercept(module, filename) { + var content = stripBOM(fs.readFileSync(filename, 'utf8')); + + if (!amdefineRegExp.test(module.id)) { + content = inserted + content; + } + + module._compile(content, filename); +} + +intercept._id = 'amdefine/intercept'; + +if (!existingExtFn._id || existingExtFn._id !== intercept._id) { + Module._extensions['.js'] = intercept; +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/package.json b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/package.json new file mode 100644 index 000000000..bca411dbd --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/node_modules/amdefine/package.json @@ -0,0 +1,37 @@ +{ + "name": "amdefine", + "description": "Provide AMD's define() API for declaring modules in the AMD format", + "version": "0.1.0", + "homepage": "http://github.com/jrburke/amdefine", + "author": { + "name": "James Burke", + "email": "jrburke@gmail.com", + "url": "http://github.com/jrburke" + }, + "licenses": [ + { + "type": "BSD", + "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" + }, + { + "type": "MIT", + "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/jrburke/amdefine.git" + }, + "main": "./amdefine.js", + "engines": { + "node": ">=0.4.2" + }, + "readme": "# amdefine\n\nA module that can be used to implement AMD's define() in Node. This allows you\nto code to the AMD API and have the module work in node programs without\nrequiring those other programs to use AMD.\n\n## Usage\n\n**1)** Update your package.json to indicate amdefine as a dependency:\n\n```javascript\n \"dependencies\": {\n \"amdefine\": \">=0.1.0\"\n }\n```\n\nThen run `npm install` to get amdefine into your project.\n\n**2)** At the top of each module that uses define(), place this code:\n\n```javascript\nif (typeof define !== 'function') { var define = require('amdefine')(module) }\n```\n\n**Only use these snippets** when loading amdefine. If you preserve the basic structure,\nwith the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).\n\nYou can add spaces, line breaks and even require amdefine with a local path, but\nkeep the rest of the structure to get the stripping behavior.\n\nAs you may know, because `if` statements in JavaScript don't have their own scope, the var\ndeclaration in the above snippet is made whether the `if` expression is truthy or not. If\nRequireJS is loaded then the declaration is superfluous because `define` is already already\ndeclared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`\ndeclarations of the same variable in the same scope gracefully.\n\nIf you want to deliver amdefine.js with your code rather than specifying it as a dependency\nwith npm, then just download the latest release and refer to it using a relative path:\n\n[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)\n\n### amdefine/intercept\n\nConsider this very experimental.\n\nInstead of pasting the piece of text for the amdefine setup of a `define`\nvariable in each module you create or consume, you can use `amdefine/intercept`\ninstead. It will automatically insert the above snippet in each .js file loaded\nby Node.\n\n**Warning**: you should only use this if you are creating an application that\nis consuming AMD style defined()'d modules that are distributed via npm and want\nto run that code in Node.\n\nFor library code where you are not sure if it will be used by others in Node or\nin the browser, then explicitly depending on amdefine and placing the code\nsnippet above is suggested path, instead of using `amdefine/intercept`. The\nintercept module affects all .js files loaded in the Node app, and it is\ninconsiderate to modify global state like that unless you are also controlling\nthe top level app.\n\n#### Why distribute AMD-style nodes via npm?\n\nnpm has a lot of weaknesses for front-end use (installed layout is not great,\nshould have better support for the `baseUrl + moduleID + '.js' style of loading,\nsingle file JS installs), but some people want a JS package manager and are\nwilling to live with those constraints. If that is you, but still want to author\nin AMD style modules to get dynamic require([]), better direct source usage and\npowerful loader plugin support in the browser, then this tool can help.\n\n#### amdefine/intercept usage\n\nJust require it in your top level app module (for example index.js, server.js):\n\n```javascript\nrequire('amdefine/intercept');\n```\n\nThe module does not return a value, so no need to assign the result to a local\nvariable.\n\nThen just require() code as you normally would with Node's require(). Any .js\nloaded after the intercept require will have the amdefine check injected in\nthe .js source as it is loaded. It does not modify the source on disk, just\nprepends some content to the text of the module as it is loaded by Node.\n\n#### How amdefine/intercept works\n\nIt overrides the `Module._extensions['.js']` in Node to automatically prepend\nthe amdefine snippet above. So, it will affect any .js file loaded by your\napp.\n\n## define() usage\n\nIt is best if you use the anonymous forms of define() in your module:\n\n```javascript\ndefine(function (require) {\n var dependency = require('dependency');\n});\n```\n\nor\n\n```javascript\ndefine(['dependency'], function (dependency) {\n\n});\n```\n\n## RequireJS optimizer integration. \n\nVersion 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)\nwill have support for stripping the `if (typeof define !== 'function')` check\nmentioned above, so you can include this snippet for code that runs in the\nbrowser, but avoid taking the cost of the if() statement once the code is\noptimized for deployment.\n\n## Node 0.4 Support\n\nIf you want to support Node 0.4, then add `require` as the second parameter to amdefine:\n\n```javascript\n//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.\nif (typeof define !== 'function') { var define = require('amdefine')(module, require) }\n```\n\n## Limitations\n\n### Synchronous vs Asynchronous\n\namdefine creates a define() function that is callable by your code. It will\nexecute and trace dependencies and call the factory function *synchronously*,\nto keep the behavior in line with Node's synchronous dependency tracing.\n\nThe exception: calling AMD's callback-style require() from inside a factory\nfunction. The require callback is called on process.nextTick():\n\n```javascript\ndefine(function (require) {\n require(['a'], function(a) {\n //'a' is loaded synchronously, but\n //this callback is called on process.nextTick().\n });\n});\n```\n\n### Loader Plugins\n\nLoader plugins are supported as long as they call their load() callbacks\nsynchronously. So ones that do network requests will not work. However plugins\nlike [text](http://requirejs.org/docs/api.html#text) can load text files locally.\n\nThe plugin API's `load.fromText()` is **not supported** in amdefine, so this means\ntranspiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)\nwill not work. This may be fixable, but it is a bit complex, and I do not have\nenough node-fu to figure it out yet. See the source for amdefine.js if you want\nto get an idea of the issues involved.\n\n## Tests\n\nTo run the tests, cd to **tests** and run:\n\n```\nnode all.js\nnode all-intercept.js\n```\n\n## License\n\nNew BSD and MIT. Check the LICENSE file for all the details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/jrburke/amdefine/issues" + }, + "_id": "amdefine@0.1.0", + "_from": "amdefine@>=0.0.4", + "scripts": {} +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/package.json b/node_modules/less-middleware/node_modules/less/node_modules/source-map/package.json new file mode 100644 index 000000000..10d4cb0fb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/package.json @@ -0,0 +1,148 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.1.39", + "homepage": "https://github.com/mozilla/source-map", + "author": { + "name": "Nick Fitzgerald", + "email": "nfitzgerald@mozilla.com" + }, + "contributors": [ + { + "name": "Tobias Koppers", + "email": "tobias.koppers@googlemail.com" + }, + { + "name": "Duncan Beevers", + "email": "duncan@dweebd.com" + }, + { + "name": "Stephen Crane", + "email": "scrane@mozilla.com" + }, + { + "name": "Ryan Seddon", + "email": "seddon.ryan@gmail.com" + }, + { + "name": "Miles Elam", + "email": "miles.elam@deem.com" + }, + { + "name": "Mihai Bazon", + "email": "mihai.bazon@gmail.com" + }, + { + "name": "Michael Ficarra", + "email": "github.public.email@michael.ficarra.me" + }, + { + "name": "Todd Wolfson", + "email": "todd@twolfson.com" + }, + { + "name": "Alexander Solovyov", + "email": "alexander@solovyov.net" + }, + { + "name": "Felix Gnass", + "email": "fgnass@gmail.com" + }, + { + "name": "Conrad Irwin", + "email": "conrad.irwin@gmail.com" + }, + { + "name": "usrbincc", + "email": "usrbincc@yahoo.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Chase Douglas", + "email": "chase@newrelic.com" + }, + { + "name": "Evan Wallace", + "email": "evan.exe@gmail.com" + }, + { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + { + "name": "Hugh Kennedy", + "email": "hughskennedy@gmail.com" + }, + { + "name": "David Glasser", + "email": "glasser@davidglasser.net" + }, + { + "name": "Simon Lydell", + "email": "simon.lydell@gmail.com" + }, + { + "name": "Jmeas Smith", + "email": "jellyes2@gmail.com" + }, + { + "name": "Michael Z Goddard", + "email": "mzgoddard@gmail.com" + }, + { + "name": "azu", + "email": "azu@users.noreply.github.com" + }, + { + "name": "John Gozde", + "email": "john@gozde.ca" + }, + { + "name": "Adam Kirkton", + "email": "akirkton@truefitinnovation.com" + }, + { + "name": "Chris Montgomery", + "email": "christopher.montgomery@dowjones.com" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "directories": { + "lib": "./lib" + }, + "main": "./lib/source-map.js", + "engines": { + "node": ">=0.8.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://opensource.org/licenses/BSD-3-Clause" + } + ], + "dependencies": { + "amdefine": ">=0.0.4" + }, + "devDependencies": { + "dryice": ">=0.4.8" + }, + "scripts": { + "test": "node test/run-tests.js", + "build": "node Makefile.dryice.js" + }, + "readme": "# Source Map\n\nThis is a library to generate and consume the source map format\n[described here][format].\n\nThis library is written in the Asynchronous Module Definition format, and works\nin the following environments:\n\n* Modern Browsers supporting ECMAScript 5 (either after the build, or with an\n AMD loader such as RequireJS)\n\n* Inside Firefox (as a JSM file, after the build)\n\n* With NodeJS versions 0.8.X and higher\n\n## Node\n\n $ npm install source-map\n\n## Building from Source (for everywhere else)\n\nInstall Node and then run\n\n $ git clone https://fitzgen@github.com/mozilla/source-map.git\n $ cd source-map\n $ npm link .\n\nNext, run\n\n $ node Makefile.dryice.js\n\nThis should spew a bunch of stuff to stdout, and create the following files:\n\n* `dist/source-map.js` - The unminified browser version.\n\n* `dist/source-map.min.js` - The minified browser version.\n\n* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source.\n\n## Examples\n\n### Consuming a source map\n\n var rawSourceMap = {\n version: 3,\n file: 'min.js',\n names: ['bar', 'baz', 'n'],\n sources: ['one.js', 'two.js'],\n sourceRoot: 'http://example.com/www/js/',\n mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'\n };\n\n var smc = new SourceMapConsumer(rawSourceMap);\n\n console.log(smc.sources);\n // [ 'http://example.com/www/js/one.js',\n // 'http://example.com/www/js/two.js' ]\n\n console.log(smc.originalPositionFor({\n line: 2,\n column: 28\n }));\n // { source: 'http://example.com/www/js/two.js',\n // line: 2,\n // column: 10,\n // name: 'n' }\n\n console.log(smc.generatedPositionFor({\n source: 'http://example.com/www/js/two.js',\n line: 2,\n column: 10\n }));\n // { line: 2, column: 28 }\n\n smc.eachMapping(function (m) {\n // ...\n });\n\n### Generating a source map\n\nIn depth guide:\n[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)\n\n#### With SourceNode (high level API)\n\n function compile(ast) {\n switch (ast.type) {\n case 'BinaryExpression':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n [compile(ast.left), \" + \", compile(ast.right)]\n );\n case 'Literal':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n String(ast.value)\n );\n // ...\n default:\n throw new Error(\"Bad AST\");\n }\n }\n\n var ast = parse(\"40 + 2\", \"add.js\");\n console.log(compile(ast).toStringWithSourceMap({\n file: 'add.js'\n }));\n // { code: '40 + 2',\n // map: [object SourceMapGenerator] }\n\n#### With SourceMapGenerator (low level API)\n\n var map = new SourceMapGenerator({\n file: \"source-mapped.js\"\n });\n\n map.addMapping({\n generated: {\n line: 10,\n column: 35\n },\n source: \"foo.js\",\n original: {\n line: 33,\n column: 2\n },\n name: \"christopher\"\n });\n\n console.log(map.toString());\n // '{\"version\":3,\"file\":\"source-mapped.js\",\"sources\":[\"foo.js\"],\"names\":[\"christopher\"],\"mappings\":\";;;;;;;;;mCAgCEA\"}'\n\n## API\n\nGet a reference to the module:\n\n // NodeJS\n var sourceMap = require('source-map');\n\n // Browser builds\n var sourceMap = window.sourceMap;\n\n // Inside Firefox\n let sourceMap = {};\n Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);\n\n### SourceMapConsumer\n\nA SourceMapConsumer instance represents a parsed source map which we can query\nfor information about the original file positions by giving it a file position\nin the generated source.\n\n#### new SourceMapConsumer(rawSourceMap)\n\nThe only parameter is the raw source map (either as a string which can be\n`JSON.parse`'d, or an object). According to the spec, source maps have the\nfollowing attributes:\n\n* `version`: Which version of the source map spec this map is following.\n\n* `sources`: An array of URLs to the original source files.\n\n* `names`: An array of identifiers which can be referrenced by individual\n mappings.\n\n* `sourceRoot`: Optional. The URL root from which all sources are relative.\n\n* `sourcesContent`: Optional. An array of contents of the original source files.\n\n* `mappings`: A string of base64 VLQs which contain the actual mappings.\n\n* `file`: Optional. The generated filename this source map is associated with.\n\n#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)\n\nReturns the original source, line, and column information for the generated\nsource's line and column positions provided. The only argument is an object with\nthe following properties:\n\n* `line`: The line number in the generated source.\n\n* `column`: The column number in the generated source.\n\nand an object is returned with the following properties:\n\n* `source`: The original source file, or null if this information is not\n available.\n\n* `line`: The line number in the original source, or null if this information is\n not available.\n\n* `column`: The column number in the original source, or null or null if this\n information is not available.\n\n* `name`: The original identifier, or null if this information is not available.\n\n#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)\n\nReturns the generated line and column information for the original source,\nline, and column positions provided. The only argument is an object with\nthe following properties:\n\n* `source`: The filename of the original source.\n\n* `line`: The line number in the original source.\n\n* `column`: The column number in the original source.\n\nand an object is returned with the following properties:\n\n* `line`: The line number in the generated source, or null.\n\n* `column`: The column number in the generated source, or null.\n\n#### SourceMapConsumer.prototype.sourceContentFor(source)\n\nReturns the original source content for the source provided. The only\nargument is the URL of the original source file.\n\n#### SourceMapConsumer.prototype.eachMapping(callback, context, order)\n\nIterate over each mapping between an original source/line/column and a\ngenerated line/column in this source map.\n\n* `callback`: The function that is called with each mapping. Mappings have the\n form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,\n name }`\n\n* `context`: Optional. If specified, this object will be the value of `this`\n every time that `callback` is called.\n\n* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or\n `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over\n the mappings sorted by the generated file's line/column order or the\n original's source/line/column order, respectively. Defaults to\n `SourceMapConsumer.GENERATED_ORDER`.\n\n### SourceMapGenerator\n\nAn instance of the SourceMapGenerator represents a source map which is being\nbuilt incrementally.\n\n#### new SourceMapGenerator([startOfSourceMap])\n\nYou may pass an object with the following properties:\n\n* `file`: The filename of the generated source that this source map is\n associated with.\n\n* `sourceRoot`: A root for all relative URLs in this source map.\n\n#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)\n\nCreates a new SourceMapGenerator based on a SourceMapConsumer\n\n* `sourceMapConsumer` The SourceMap.\n\n#### SourceMapGenerator.prototype.addMapping(mapping)\n\nAdd a single mapping from original source line and column to the generated\nsource's line and column for this source map being created. The mapping object\nshould have the following properties:\n\n* `generated`: An object with the generated line and column positions.\n\n* `original`: An object with the original line and column positions.\n\n* `source`: The original source file (relative to the sourceRoot).\n\n* `name`: An optional original token name for this mapping.\n\n#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for an original source file.\n\n* `sourceFile` the URL of the original source file.\n\n* `sourceContent` the content of the source file.\n\n#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])\n\nApplies a SourceMap for a source file to the SourceMap.\nEach mapping to the supplied source file is rewritten using the\nsupplied SourceMap. Note: The resolution for the resulting mappings\nis the minimium of this map and the supplied map.\n\n* `sourceMapConsumer`: The SourceMap to be applied.\n\n* `sourceFile`: Optional. The filename of the source file.\n If omitted, sourceMapConsumer.file will be used, if it exists.\n Otherwise an error will be thrown.\n\n* `sourceMapPath`: Optional. The dirname of the path to the SourceMap\n to be applied. If relative, it is relative to the SourceMap.\n\n This parameter is needed when the two SourceMaps aren't in the same\n directory, and the SourceMap to be applied contains relative source\n paths. If so, those relative source paths need to be rewritten\n relative to the SourceMap.\n\n If omitted, it is assumed that both SourceMaps are in the same directory,\n thus not needing any rewriting. (Supplying `'.'` has the same effect.)\n\n#### SourceMapGenerator.prototype.toString()\n\nRenders the source map being generated to a string.\n\n### SourceNode\n\nSourceNodes provide a way to abstract over interpolating and/or concatenating\nsnippets of generated JavaScript source code, while maintaining the line and\ncolumn information associated between those snippets and the original source\ncode. This is useful as the final intermediate representation a compiler might\nuse before outputting the generated JS and source map.\n\n#### new SourceNode([line, column, source[, chunk[, name]]])\n\n* `line`: The original line number associated with this source node, or null if\n it isn't associated with an original line.\n\n* `column`: The original column number associated with this source node, or null\n if it isn't associated with an original column.\n\n* `source`: The original source's filename; null if no filename is provided.\n\n* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see\n below.\n\n* `name`: Optional. The original identifier.\n\n#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])\n\nCreates a SourceNode from generated code and a SourceMapConsumer.\n\n* `code`: The generated code\n\n* `sourceMapConsumer` The SourceMap for the generated code\n\n* `relativePath` The optional path that relative sources in `sourceMapConsumer`\n should be relative to.\n\n#### SourceNode.prototype.add(chunk)\n\nAdd a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.prepend(chunk)\n\nPrepend a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for a source file. This will be added to the\n`SourceMap` in the `sourcesContent` field.\n\n* `sourceFile`: The filename of the source file\n\n* `sourceContent`: The content of the source file\n\n#### SourceNode.prototype.walk(fn)\n\nWalk over the tree of JS snippets in this node and its children. The walking\nfunction is called once for each snippet of JS and is passed that snippet and\nthe its original associated source's line/column location.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.walkSourceContents(fn)\n\nWalk over the tree of SourceNodes. The walking function is called for each\nsource file content and is passed the filename and source content.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.join(sep)\n\nLike `Array.prototype.join` except for SourceNodes. Inserts the separator\nbetween each of this source node's children.\n\n* `sep`: The separator.\n\n#### SourceNode.prototype.replaceRight(pattern, replacement)\n\nCall `String.prototype.replace` on the very right-most source snippet. Useful\nfor trimming whitespace from the end of a source node, etc.\n\n* `pattern`: The pattern to replace.\n\n* `replacement`: The thing to replace the pattern with.\n\n#### SourceNode.prototype.toString()\n\nReturn the string representation of this source node. Walks over the tree and\nconcatenates all the various snippets together to one string.\n\n#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])\n\nReturns the string representation of this tree of source nodes, plus a\nSourceMapGenerator which contains all the mappings between the generated and\noriginal sources.\n\nThe arguments are the same as those to `new SourceMapGenerator`.\n\n## Tests\n\n[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)\n\nInstall NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.\n\nTo add new tests, create a new file named `test/test-.js`\nand export your test functions with names that start with \"test\", for example\n\n exports[\"test doing the foo bar\"] = function (assert, util) {\n ...\n };\n\nThe new test will be located automatically when you run the suite.\n\nThe `util` argument is the test utility module located at `test/source-map/util`.\n\nThe `assert` argument is a cut down version of node's assert module. You have\naccess to the following assertion functions:\n\n* `doesNotThrow`\n\n* `equal`\n\n* `ok`\n\n* `strictEqual`\n\n* `throws`\n\n(The reason for the restricted set of test functions is because we need the\ntests to run inside Firefox's test suite as well and so the assert module is\nshimmed in that environment. See `build/assert-shim.js`.)\n\n[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit\n[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap\n[Dryice]: https://github.com/mozilla/dryice\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mozilla/source-map/issues" + }, + "_id": "source-map@0.1.39", + "_shasum": "64ad329c4761ab956ff7d011c6b205aeb66a2d4a", + "_from": "source-map@0.1.x", + "_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.39.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/run-tests.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/run-tests.js new file mode 100644 index 000000000..64a7c3a3d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/run-tests.js @@ -0,0 +1,62 @@ +#!/usr/bin/env node +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var util = require('./source-map/util'); + +function run(tests) { + var total = 0; + var passed = 0; + + for (var i = 0; i < tests.length; i++) { + for (var k in tests[i].testCase) { + if (/^test/.test(k)) { + total++; + try { + tests[i].testCase[k](assert, util); + passed++; + } + catch (e) { + console.log('FAILED ' + tests[i].name + ': ' + k + '!'); + console.log(e.stack); + } + } + } + } + + console.log(''); + console.log(passed + ' / ' + total + ' tests passed.'); + console.log(''); + + return total - passed; +} + +function isTestFile(f) { + var testToRun = process.argv[2]; + return testToRun + ? path.basename(testToRun) === f + : /^test\-.*?\.js/.test(f); +} + +function toModule(f) { + return './source-map/' + f.replace(/\.js$/, ''); +} + +var requires = fs.readdirSync(path.join(__dirname, 'source-map')) + .filter(isTestFile) + .map(toModule); + +var code = run(requires.map(require).map(function (mod, i) { + return { + name: requires[i], + testCase: mod + }; +})); + +process.exit(code); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-api.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-api.js new file mode 100644 index 000000000..3801233c0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-api.js @@ -0,0 +1,26 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2012 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var sourceMap; + try { + sourceMap = require('../../lib/source-map'); + } catch (e) { + sourceMap = {}; + Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); + } + + exports['test that the api is properly exposed in the top level'] = function (assert, util) { + assert.equal(typeof sourceMap.SourceMapGenerator, "function"); + assert.equal(typeof sourceMap.SourceMapConsumer, "function"); + assert.equal(typeof sourceMap.SourceNode, "function"); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-array-set.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-array-set.js new file mode 100644 index 000000000..b5797edd5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-array-set.js @@ -0,0 +1,104 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var ArraySet = require('../../lib/source-map/array-set').ArraySet; + + function makeTestSet() { + var set = new ArraySet(); + for (var i = 0; i < 100; i++) { + set.add(String(i)); + } + return set; + } + + exports['test .has() membership'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.ok(set.has(String(i))); + } + }; + + exports['test .indexOf() elements'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.strictEqual(set.indexOf(String(i)), i); + } + }; + + exports['test .at() indexing'] = function (assert, util) { + var set = makeTestSet(); + for (var i = 0; i < 100; i++) { + assert.strictEqual(set.at(i), String(i)); + } + }; + + exports['test creating from an array'] = function (assert, util) { + var set = ArraySet.fromArray(['foo', 'bar', 'baz', 'quux', 'hasOwnProperty']); + + assert.ok(set.has('foo')); + assert.ok(set.has('bar')); + assert.ok(set.has('baz')); + assert.ok(set.has('quux')); + assert.ok(set.has('hasOwnProperty')); + + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.indexOf('bar'), 1); + assert.strictEqual(set.indexOf('baz'), 2); + assert.strictEqual(set.indexOf('quux'), 3); + + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'bar'); + assert.strictEqual(set.at(2), 'baz'); + assert.strictEqual(set.at(3), 'quux'); + }; + + exports['test that you can add __proto__; see github issue #30'] = function (assert, util) { + var set = new ArraySet(); + set.add('__proto__'); + assert.ok(set.has('__proto__')); + assert.strictEqual(set.at(0), '__proto__'); + assert.strictEqual(set.indexOf('__proto__'), 0); + }; + + exports['test .fromArray() with duplicates'] = function (assert, util) { + var set = ArraySet.fromArray(['foo', 'foo']); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 1); + + set = ArraySet.fromArray(['foo', 'foo'], true); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 2); + }; + + exports['test .add() with duplicates'] = function (assert, util) { + var set = new ArraySet(); + set.add('foo'); + + set.add('foo'); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 1); + + set.add('foo', true); + assert.ok(set.has('foo')); + assert.strictEqual(set.at(0), 'foo'); + assert.strictEqual(set.at(1), 'foo'); + assert.strictEqual(set.indexOf('foo'), 0); + assert.strictEqual(set.toArray().length, 2); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64-vlq.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64-vlq.js new file mode 100644 index 000000000..653a874e9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64-vlq.js @@ -0,0 +1,24 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64VLQ = require('../../lib/source-map/base64-vlq'); + + exports['test normal encoding and decoding'] = function (assert, util) { + var result; + for (var i = -255; i < 256; i++) { + result = base64VLQ.decode(base64VLQ.encode(i)); + assert.ok(result); + assert.equal(result.value, i); + assert.equal(result.rest, ""); + } + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64.js new file mode 100644 index 000000000..ff3a24456 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-base64.js @@ -0,0 +1,35 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64 = require('../../lib/source-map/base64'); + + exports['test out of range encoding'] = function (assert, util) { + assert.throws(function () { + base64.encode(-1); + }); + assert.throws(function () { + base64.encode(64); + }); + }; + + exports['test out of range decoding'] = function (assert, util) { + assert.throws(function () { + base64.decode('='); + }); + }; + + exports['test normal encoding and decoding'] = function (assert, util) { + for (var i = 0; i < 64; i++) { + assert.equal(base64.decode(base64.encode(i)), i); + } + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-binary-search.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-binary-search.js new file mode 100644 index 000000000..ee306830d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-binary-search.js @@ -0,0 +1,54 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var binarySearch = require('../../lib/source-map/binary-search'); + + function numberCompare(a, b) { + return a - b; + } + + exports['test too high'] = function (assert, util) { + var needle = 30; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.doesNotThrow(function () { + binarySearch.search(needle, haystack, numberCompare); + }); + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 20); + }; + + exports['test too low'] = function (assert, util) { + var needle = 1; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.doesNotThrow(function () { + binarySearch.search(needle, haystack, numberCompare); + }); + + assert.equal(binarySearch.search(needle, haystack, numberCompare), null); + }; + + exports['test exact search'] = function (assert, util) { + var needle = 4; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 4); + }; + + exports['test fuzzy search'] = function (assert, util) { + var needle = 19; + var haystack = [2,4,6,8,10,12,14,16,18,20]; + + assert.equal(binarySearch.search(needle, haystack, numberCompare), 18); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-dog-fooding.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-dog-fooding.js new file mode 100644 index 000000000..26757b2d1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-dog-fooding.js @@ -0,0 +1,84 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + + exports['test eating our own dog food'] = function (assert, util) { + var smg = new SourceMapGenerator({ + file: 'testing.js', + sourceRoot: '/wu/tang' + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 1, column: 0 }, + generated: { line: 2, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 2, column: 0 }, + generated: { line: 3, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 3, column: 0 }, + generated: { line: 4, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 4, column: 0 }, + generated: { line: 5, column: 2 } + }); + + smg.addMapping({ + source: 'gza.coffee', + original: { line: 5, column: 10 }, + generated: { line: 6, column: 12 } + }); + + var smc = new SourceMapConsumer(smg.toString()); + + // Exact + util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 0, null, smc, assert); + util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 0, null, smc, assert); + util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 0, null, smc, assert); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 0, null, smc, assert); + util.assertMapping(6, 12, '/wu/tang/gza.coffee', 5, 10, null, smc, assert); + + // Fuzzy + + // Generated to original + util.assertMapping(2, 0, null, null, null, null, smc, assert, true); + util.assertMapping(2, 9, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); + util.assertMapping(3, 0, null, null, null, null, smc, assert, true); + util.assertMapping(3, 9, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); + util.assertMapping(4, 0, null, null, null, null, smc, assert, true); + util.assertMapping(4, 9, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); + util.assertMapping(5, 0, null, null, null, null, smc, assert, true); + util.assertMapping(5, 9, '/wu/tang/gza.coffee', 4, 0, null, smc, assert, true); + util.assertMapping(6, 0, null, null, null, null, smc, assert, true); + util.assertMapping(6, 9, null, null, null, null, smc, assert, true); + util.assertMapping(6, 13, '/wu/tang/gza.coffee', 5, 10, null, smc, assert, true); + + // Original to generated + util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 1, null, smc, assert, null, true); + util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 3, null, smc, assert, null, true); + util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 6, null, smc, assert, null, true); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 9, null, smc, assert, null, true); + util.assertMapping(5, 2, '/wu/tang/gza.coffee', 5, 9, null, smc, assert, null, true); + util.assertMapping(6, 12, '/wu/tang/gza.coffee', 6, 19, null, smc, assert, null, true); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-consumer.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-consumer.js new file mode 100644 index 000000000..a4c66590a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-consumer.js @@ -0,0 +1,531 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + + exports['test that we can instantiate with a string or an object'] = function (assert, util) { + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(util.testMap); + }); + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(JSON.stringify(util.testMap)); + }); + }; + + exports['test that the `sources` field has the original sources'] = function (assert, util) { + var map; + var sources; + + map = new SourceMapConsumer(util.testMap); + sources = map.sources; + assert.equal(sources[0], '/the/root/one.js'); + assert.equal(sources[1], '/the/root/two.js'); + assert.equal(sources.length, 2); + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + sources = map.sources; + assert.equal(sources[0], 'one.js'); + assert.equal(sources[1], 'two.js'); + assert.equal(sources.length, 2); + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + sources = map.sources; + assert.equal(sources[0], 'one.js'); + assert.equal(sources[1], 'two.js'); + assert.equal(sources.length, 2); + }; + + exports['test that the source root is reflected in a mapping\'s source field'] = function (assert, util) { + var map; + var mapping; + + map = new SourceMapConsumer(util.testMap); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, '/the/root/two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, '/the/root/one.js'); + + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, 'two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, 'one.js'); + + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + + mapping = map.originalPositionFor({ + line: 2, + column: 1 + }); + assert.equal(mapping.source, 'two.js'); + + mapping = map.originalPositionFor({ + line: 1, + column: 1 + }); + assert.equal(mapping.source, 'one.js'); + }; + + exports['test mapping tokens back exactly'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + + util.assertMapping(1, 1, '/the/root/one.js', 1, 1, null, map, assert); + util.assertMapping(1, 5, '/the/root/one.js', 1, 5, null, map, assert); + util.assertMapping(1, 9, '/the/root/one.js', 1, 11, null, map, assert); + util.assertMapping(1, 18, '/the/root/one.js', 1, 21, 'bar', map, assert); + util.assertMapping(1, 21, '/the/root/one.js', 2, 3, null, map, assert); + util.assertMapping(1, 28, '/the/root/one.js', 2, 10, 'baz', map, assert); + util.assertMapping(1, 32, '/the/root/one.js', 2, 14, 'bar', map, assert); + + util.assertMapping(2, 1, '/the/root/two.js', 1, 1, null, map, assert); + util.assertMapping(2, 5, '/the/root/two.js', 1, 5, null, map, assert); + util.assertMapping(2, 9, '/the/root/two.js', 1, 11, null, map, assert); + util.assertMapping(2, 18, '/the/root/two.js', 1, 21, 'n', map, assert); + util.assertMapping(2, 21, '/the/root/two.js', 2, 3, null, map, assert); + util.assertMapping(2, 28, '/the/root/two.js', 2, 10, 'n', map, assert); + }; + + exports['test mapping tokens fuzzy'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + + // Finding original positions + util.assertMapping(1, 20, '/the/root/one.js', 1, 21, 'bar', map, assert, true); + util.assertMapping(1, 30, '/the/root/one.js', 2, 10, 'baz', map, assert, true); + util.assertMapping(2, 12, '/the/root/two.js', 1, 11, null, map, assert, true); + + // Finding generated positions + util.assertMapping(1, 18, '/the/root/one.js', 1, 22, 'bar', map, assert, null, true); + util.assertMapping(1, 28, '/the/root/one.js', 2, 13, 'baz', map, assert, null, true); + util.assertMapping(2, 9, '/the/root/two.js', 1, 16, null, map, assert, null, true); + }; + + exports['test mappings and end of lines'] = function (assert, util) { + var smg = new SourceMapGenerator({ + file: 'foo.js' + }); + smg.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 1, column: 1 }, + source: 'bar.js' + }); + smg.addMapping({ + original: { line: 2, column: 2 }, + generated: { line: 2, column: 2 }, + source: 'bar.js' + }); + + var map = SourceMapConsumer.fromSourceMap(smg); + + // When finding original positions, mappings end at the end of the line. + util.assertMapping(2, 1, null, null, null, null, map, assert, true) + + // When finding generated positions, mappings do not end at the end of the line. + util.assertMapping(1, 1, 'bar.js', 2, 1, null, map, assert, null, true); + }; + + exports['test creating source map consumers with )]}\' prefix'] = function (assert, util) { + assert.doesNotThrow(function () { + var map = new SourceMapConsumer(")]}'" + JSON.stringify(util.testMap)); + }); + }; + + exports['test eachMapping'] = function (assert, util) { + var map; + + map = new SourceMapConsumer(util.testMap); + var previousLine = -Infinity; + var previousColumn = -Infinity; + map.eachMapping(function (mapping) { + assert.ok(mapping.generatedLine >= previousLine); + + assert.ok(mapping.source === '/the/root/one.js' || mapping.source === '/the/root/two.js'); + + if (mapping.generatedLine === previousLine) { + assert.ok(mapping.generatedColumn >= previousColumn); + previousColumn = mapping.generatedColumn; + } + else { + previousLine = mapping.generatedLine; + previousColumn = -Infinity; + } + }); + + map = new SourceMapConsumer(util.testMapNoSourceRoot); + map.eachMapping(function (mapping) { + assert.ok(mapping.source === 'one.js' || mapping.source === 'two.js'); + }); + + map = new SourceMapConsumer(util.testMapEmptySourceRoot); + map.eachMapping(function (mapping) { + assert.ok(mapping.source === 'one.js' || mapping.source === 'two.js'); + }); + }; + + exports['test iterating over mappings in a different order'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + var previousLine = -Infinity; + var previousColumn = -Infinity; + var previousSource = ""; + map.eachMapping(function (mapping) { + assert.ok(mapping.source >= previousSource); + + if (mapping.source === previousSource) { + assert.ok(mapping.originalLine >= previousLine); + + if (mapping.originalLine === previousLine) { + assert.ok(mapping.originalColumn >= previousColumn); + previousColumn = mapping.originalColumn; + } + else { + previousLine = mapping.originalLine; + previousColumn = -Infinity; + } + } + else { + previousSource = mapping.source; + previousLine = -Infinity; + previousColumn = -Infinity; + } + }, null, SourceMapConsumer.ORIGINAL_ORDER); + }; + + exports['test that we can set the context for `this` in eachMapping'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMap); + var context = {}; + map.eachMapping(function () { + assert.equal(this, context); + }, context); + }; + + exports['test that the `sourcesContent` field has the original sources'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMapWithSourcesContent); + var sourcesContent = map.sourcesContent; + + assert.equal(sourcesContent[0], ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(sourcesContent[1], ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.equal(sourcesContent.length, 2); + }; + + exports['test that we can get the original sources for the sources'] = function (assert, util) { + var map = new SourceMapConsumer(util.testMapWithSourcesContent); + var sources = map.sources; + + assert.equal(map.sourceContentFor(sources[0]), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(map.sourceContentFor(sources[1]), ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.equal(map.sourceContentFor("one.js"), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); + assert.equal(map.sourceContentFor("two.js"), ' TWO.inc = function (n) {\n return n + 1;\n };'); + assert.throws(function () { + map.sourceContentFor(""); + }, Error); + assert.throws(function () { + map.sourceContentFor("/the/root/three.js"); + }, Error); + assert.throws(function () { + map.sourceContentFor("three.js"); + }, Error); + }; + + exports['test sourceRoot + generatedPositionFor'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'foo/bar', + file: 'baz.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bang.coffee' + }); + map.addMapping({ + original: { line: 5, column: 5 }, + generated: { line: 6, column: 6 }, + source: 'bang.coffee' + }); + map = new SourceMapConsumer(map.toString()); + + // Should handle without sourceRoot. + var pos = map.generatedPositionFor({ + line: 1, + column: 1, + source: 'bang.coffee' + }); + + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + + // Should handle with sourceRoot. + var pos = map.generatedPositionFor({ + line: 1, + column: 1, + source: 'foo/bar/bang.coffee' + }); + + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + }; + + exports['test sourceRoot + originalPositionFor'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'foo/bar', + file: 'baz.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bang.coffee' + }); + map = new SourceMapConsumer(map.toString()); + + var pos = map.originalPositionFor({ + line: 2, + column: 2, + }); + + // Should always have the prepended source root + assert.equal(pos.source, 'foo/bar/bang.coffee'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + }; + + exports['test github issue #56'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://', + file: 'www.example.com/foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'www.example.com/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1); + assert.equal(sources[0], 'http://www.example.com/original.js'); + }; + + exports['test github issue #43'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://example.com', + file: 'foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'http://cdn.example.com/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1, + 'Should only be one source.'); + assert.equal(sources[0], 'http://cdn.example.com/original.js', + 'Should not be joined with the sourceRoot.'); + }; + + exports['test absolute path, but same host sources'] = function (assert, util) { + var map = new SourceMapGenerator({ + sourceRoot: 'http://example.com/foo/bar', + file: 'foo.js' + }); + map.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: '/original.js' + }); + map = new SourceMapConsumer(map.toString()); + + var sources = map.sources; + assert.equal(sources.length, 1, + 'Should only be one source.'); + assert.equal(sources[0], 'http://example.com/original.js', + 'Source should be relative the host of the source root.'); + }; + + exports['test github issue #64'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sourceRoot": "http://example.com/", + "sources": ["/a"], + "names": [], + "mappings": "AACA", + "sourcesContent": ["foo"] + }); + + assert.equal(map.sourceContentFor("a"), "foo"); + assert.equal(map.sourceContentFor("/a"), "foo"); + }; + + exports['test bug 885597'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sourceRoot": "file:///Users/AlGore/Invented/The/Internet/", + "sources": ["/a"], + "names": [], + "mappings": "AACA", + "sourcesContent": ["foo"] + }); + + var s = map.sources[0]; + assert.equal(map.sourceContentFor(s), "foo"); + }; + + exports['test github issue #72, duplicate sources'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sources": ["source1.js", "source1.js", "source3.js"], + "names": [], + "mappings": ";EAAC;;IAEE;;MEEE", + "sourceRoot": "http://example.com" + }); + + var pos = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.source, 'http://example.com/source1.js'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + + var pos = map.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.source, 'http://example.com/source1.js'); + assert.equal(pos.line, 3); + assert.equal(pos.column, 3); + + var pos = map.originalPositionFor({ + line: 6, + column: 6 + }); + assert.equal(pos.source, 'http://example.com/source3.js'); + assert.equal(pos.line, 5); + assert.equal(pos.column, 5); + }; + + exports['test github issue #72, duplicate names'] = function (assert, util) { + var map = new SourceMapConsumer({ + "version": 3, + "file": "foo.js", + "sources": ["source.js"], + "names": ["name1", "name1", "name3"], + "mappings": ";EAACA;;IAEEA;;MAEEE", + "sourceRoot": "http://example.com" + }); + + var pos = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.name, 'name1'); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + + var pos = map.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.name, 'name1'); + assert.equal(pos.line, 3); + assert.equal(pos.column, 3); + + var pos = map.originalPositionFor({ + line: 6, + column: 6 + }); + assert.equal(pos.name, 'name3'); + assert.equal(pos.line, 5); + assert.equal(pos.column, 5); + }; + + exports['test SourceMapConsumer.fromSourceMap'] = function (assert, util) { + var smg = new SourceMapGenerator({ + sourceRoot: 'http://example.com/', + file: 'foo.js' + }); + smg.addMapping({ + original: { line: 1, column: 1 }, + generated: { line: 2, column: 2 }, + source: 'bar.js' + }); + smg.addMapping({ + original: { line: 2, column: 2 }, + generated: { line: 4, column: 4 }, + source: 'baz.js', + name: 'dirtMcGirt' + }); + smg.setSourceContent('baz.js', 'baz.js content'); + + var smc = SourceMapConsumer.fromSourceMap(smg); + assert.equal(smc.file, 'foo.js'); + assert.equal(smc.sourceRoot, 'http://example.com/'); + assert.equal(smc.sources.length, 2); + assert.equal(smc.sources[0], 'http://example.com/bar.js'); + assert.equal(smc.sources[1], 'http://example.com/baz.js'); + assert.equal(smc.sourceContentFor('baz.js'), 'baz.js content'); + + var pos = smc.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(pos.line, 1); + assert.equal(pos.column, 1); + assert.equal(pos.source, 'http://example.com/bar.js'); + assert.equal(pos.name, null); + + pos = smc.generatedPositionFor({ + line: 1, + column: 1, + source: 'http://example.com/bar.js' + }); + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + + pos = smc.originalPositionFor({ + line: 4, + column: 4 + }); + assert.equal(pos.line, 2); + assert.equal(pos.column, 2); + assert.equal(pos.source, 'http://example.com/baz.js'); + assert.equal(pos.name, 'dirtMcGirt'); + + pos = smc.generatedPositionFor({ + line: 2, + column: 2, + source: 'http://example.com/baz.js' + }); + assert.equal(pos.line, 4); + assert.equal(pos.column, 4); + }; +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-generator.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-generator.js new file mode 100644 index 000000000..ed86114c6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-map-generator.js @@ -0,0 +1,602 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceNode = require('../../lib/source-map/source-node').SourceNode; + var util = require('./util'); + + exports['test some simple stuff'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'foo.js', + sourceRoot: '.' + }); + assert.ok(true); + + var map = new SourceMapGenerator().toJSON(); + assert.ok(!('file' in map)); + assert.ok(!('sourceRoot' in map)); + }; + + exports['test JSON serialization'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'foo.js', + sourceRoot: '.' + }); + assert.equal(map.toString(), JSON.stringify(map)); + }; + + exports['test adding mappings (case 1)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 } + }); + }); + }; + + exports['test adding mappings (case 2)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 } + }); + }); + }; + + exports['test adding mappings (case 3)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + assert.doesNotThrow(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 }, + name: 'someToken' + }); + }); + }; + + exports['test adding mappings (invalid)'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + // Not enough info. + assert.throws(function () { + map.addMapping({}); + }); + + // Original file position, but no source. + assert.throws(function () { + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 } + }); + }); + }; + + exports['test that the correct mappings are being generated'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'min.js', + sourceRoot: '/the/root' + }); + + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 5 }, + original: { line: 1, column: 5 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 9 }, + original: { line: 1, column: 11 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 18 }, + original: { line: 1, column: 21 }, + source: 'one.js', + name: 'bar' + }); + map.addMapping({ + generated: { line: 1, column: 21 }, + original: { line: 2, column: 3 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 1, column: 28 }, + original: { line: 2, column: 10 }, + source: 'one.js', + name: 'baz' + }); + map.addMapping({ + generated: { line: 1, column: 32 }, + original: { line: 2, column: 14 }, + source: 'one.js', + name: 'bar' + }); + + map.addMapping({ + generated: { line: 2, column: 1 }, + original: { line: 1, column: 1 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 5 }, + original: { line: 1, column: 5 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 9 }, + original: { line: 1, column: 11 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 18 }, + original: { line: 1, column: 21 }, + source: 'two.js', + name: 'n' + }); + map.addMapping({ + generated: { line: 2, column: 21 }, + original: { line: 2, column: 3 }, + source: 'two.js' + }); + map.addMapping({ + generated: { line: 2, column: 28 }, + original: { line: 2, column: 10 }, + source: 'two.js', + name: 'n' + }); + + map = JSON.parse(map.toString()); + + util.assertEqualMaps(assert, map, util.testMap); + }; + + exports['test that adding a mapping with an empty string name does not break generation'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'generated-foo.js', + sourceRoot: '.' + }); + + map.addMapping({ + generated: { line: 1, column: 1 }, + source: 'bar.js', + original: { line: 1, column: 1 }, + name: '' + }); + + assert.doesNotThrow(function () { + JSON.parse(map.toString()); + }); + }; + + exports['test that source content can be set'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'min.js', + sourceRoot: '/the/root' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 1, column: 1 }, + source: 'one.js' + }); + map.addMapping({ + generated: { line: 2, column: 1 }, + original: { line: 1, column: 1 }, + source: 'two.js' + }); + map.setSourceContent('one.js', 'one file content'); + + map = JSON.parse(map.toString()); + assert.equal(map.sources[0], 'one.js'); + assert.equal(map.sources[1], 'two.js'); + assert.equal(map.sourcesContent[0], 'one file content'); + assert.equal(map.sourcesContent[1], null); + }; + + exports['test .fromSourceMap'] = function (assert, util) { + var map = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(util.testMap)); + util.assertEqualMaps(assert, map.toJSON(), util.testMap); + }; + + exports['test .fromSourceMap with sourcesContent'] = function (assert, util) { + var map = SourceMapGenerator.fromSourceMap( + new SourceMapConsumer(util.testMapWithSourcesContent)); + util.assertEqualMaps(assert, map.toJSON(), util.testMapWithSourcesContent); + }; + + exports['test applySourceMap'] = function (assert, util) { + var node = new SourceNode(null, null, null, [ + new SourceNode(2, 0, 'fileX', 'lineX2\n'), + 'genA1\n', + new SourceNode(2, 0, 'fileY', 'lineY2\n'), + 'genA2\n', + new SourceNode(1, 0, 'fileX', 'lineX1\n'), + 'genA3\n', + new SourceNode(1, 0, 'fileY', 'lineY1\n') + ]); + var mapStep1 = node.toStringWithSourceMap({ + file: 'fileA' + }).map; + mapStep1.setSourceContent('fileX', 'lineX1\nlineX2\n'); + mapStep1 = mapStep1.toJSON(); + + node = new SourceNode(null, null, null, [ + 'gen1\n', + new SourceNode(1, 0, 'fileA', 'lineA1\n'), + new SourceNode(2, 0, 'fileA', 'lineA2\n'), + new SourceNode(3, 0, 'fileA', 'lineA3\n'), + new SourceNode(4, 0, 'fileA', 'lineA4\n'), + new SourceNode(1, 0, 'fileB', 'lineB1\n'), + new SourceNode(2, 0, 'fileB', 'lineB2\n'), + 'gen2\n' + ]); + var mapStep2 = node.toStringWithSourceMap({ + file: 'fileGen' + }).map; + mapStep2.setSourceContent('fileB', 'lineB1\nlineB2\n'); + mapStep2 = mapStep2.toJSON(); + + node = new SourceNode(null, null, null, [ + 'gen1\n', + new SourceNode(2, 0, 'fileX', 'lineA1\n'), + new SourceNode(2, 0, 'fileA', 'lineA2\n'), + new SourceNode(2, 0, 'fileY', 'lineA3\n'), + new SourceNode(4, 0, 'fileA', 'lineA4\n'), + new SourceNode(1, 0, 'fileB', 'lineB1\n'), + new SourceNode(2, 0, 'fileB', 'lineB2\n'), + 'gen2\n' + ]); + var expectedMap = node.toStringWithSourceMap({ + file: 'fileGen' + }).map; + expectedMap.setSourceContent('fileX', 'lineX1\nlineX2\n'); + expectedMap.setSourceContent('fileB', 'lineB1\nlineB2\n'); + expectedMap = expectedMap.toJSON(); + + // apply source map "mapStep1" to "mapStep2" + var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapStep2)); + generator.applySourceMap(new SourceMapConsumer(mapStep1)); + var actualMap = generator.toJSON(); + + util.assertEqualMaps(assert, actualMap, expectedMap); + }; + + exports['test applySourceMap throws when file is missing'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + var map2 = new SourceMapGenerator(); + assert.throws(function() { + map.applySourceMap(new SourceMapConsumer(map2.toJSON())); + }); + }; + + exports['test the two additional parameters of applySourceMap'] = function (assert, util) { + // Assume the following directory structure: + // + // http://foo.org/ + // bar.coffee + // app/ + // coffee/ + // foo.coffee + // temp/ + // bundle.js + // temp_maps/ + // bundle.js.map + // public/ + // bundle.min.js + // bundle.min.js.map + // + // http://www.example.com/ + // baz.coffee + + var bundleMap = new SourceMapGenerator({ + file: 'bundle.js' + }); + bundleMap.addMapping({ + generated: { line: 3, column: 3 }, + original: { line: 2, column: 2 }, + source: '../../coffee/foo.coffee' + }); + bundleMap.setSourceContent('../../coffee/foo.coffee', 'foo coffee'); + bundleMap.addMapping({ + generated: { line: 13, column: 13 }, + original: { line: 12, column: 12 }, + source: '/bar.coffee' + }); + bundleMap.setSourceContent('/bar.coffee', 'bar coffee'); + bundleMap.addMapping({ + generated: { line: 23, column: 23 }, + original: { line: 22, column: 22 }, + source: 'http://www.example.com/baz.coffee' + }); + bundleMap.setSourceContent( + 'http://www.example.com/baz.coffee', + 'baz coffee' + ); + bundleMap = new SourceMapConsumer(bundleMap.toJSON()); + + var minifiedMap = new SourceMapGenerator({ + file: 'bundle.min.js', + sourceRoot: '..' + }); + minifiedMap.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 3, column: 3 }, + source: 'temp/bundle.js' + }); + minifiedMap.addMapping({ + generated: { line: 11, column: 11 }, + original: { line: 13, column: 13 }, + source: 'temp/bundle.js' + }); + minifiedMap.addMapping({ + generated: { line: 21, column: 21 }, + original: { line: 23, column: 23 }, + source: 'temp/bundle.js' + }); + minifiedMap = new SourceMapConsumer(minifiedMap.toJSON()); + + var expectedMap = function (sources) { + var map = new SourceMapGenerator({ + file: 'bundle.min.js', + sourceRoot: '..' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 2, column: 2 }, + source: sources[0] + }); + map.setSourceContent(sources[0], 'foo coffee'); + map.addMapping({ + generated: { line: 11, column: 11 }, + original: { line: 12, column: 12 }, + source: sources[1] + }); + map.setSourceContent(sources[1], 'bar coffee'); + map.addMapping({ + generated: { line: 21, column: 21 }, + original: { line: 22, column: 22 }, + source: sources[2] + }); + map.setSourceContent(sources[2], 'baz coffee'); + return map.toJSON(); + } + + var actualMap = function (aSourceMapPath) { + var map = SourceMapGenerator.fromSourceMap(minifiedMap); + // Note that relying on `bundleMap.file` (which is simply 'bundle.js') + // instead of supplying the second parameter wouldn't work here. + map.applySourceMap(bundleMap, '../temp/bundle.js', aSourceMapPath); + return map.toJSON(); + } + + util.assertEqualMaps(assert, actualMap('../temp/temp_maps'), expectedMap([ + 'coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('/app/temp/temp_maps'), expectedMap([ + '/app/coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('http://foo.org/app/temp/temp_maps'), expectedMap([ + 'http://foo.org/app/coffee/foo.coffee', + 'http://foo.org/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + // If the third parameter is omitted or set to the current working + // directory we get incorrect source paths: + + util.assertEqualMaps(assert, actualMap(), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap(''), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('.'), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + + util.assertEqualMaps(assert, actualMap('./'), expectedMap([ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee' + ])); + }; + + exports['test sorting with duplicate generated mappings'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + map.addMapping({ + generated: { line: 3, column: 0 }, + original: { line: 2, column: 0 }, + source: 'a.js' + }); + map.addMapping({ + generated: { line: 2, column: 0 } + }); + map.addMapping({ + generated: { line: 2, column: 0 } + }); + map.addMapping({ + generated: { line: 1, column: 0 }, + original: { line: 1, column: 0 }, + source: 'a.js' + }); + + util.assertEqualMaps(assert, map.toJSON(), { + version: 3, + file: 'test.js', + sources: ['a.js'], + names: [], + mappings: 'AAAA;A;AACA' + }); + }; + + exports['test ignore duplicate mappings.'] = function (assert, util) { + var init = { file: 'min.js', sourceRoot: '/the/root' }; + var map1, map2; + + // null original source location + var nullMapping1 = { + generated: { line: 1, column: 0 } + }; + var nullMapping2 = { + generated: { line: 2, column: 2 } + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(nullMapping1); + map1.addMapping(nullMapping1); + + map2.addMapping(nullMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(nullMapping2); + map1.addMapping(nullMapping1); + + map2.addMapping(nullMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + // original source location + var srcMapping1 = { + generated: { line: 1, column: 0 }, + original: { line: 11, column: 0 }, + source: 'srcMapping1.js' + }; + var srcMapping2 = { + generated: { line: 2, column: 2 }, + original: { line: 11, column: 0 }, + source: 'srcMapping2.js' + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(srcMapping1); + map1.addMapping(srcMapping1); + + map2.addMapping(srcMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(srcMapping2); + map1.addMapping(srcMapping1); + + map2.addMapping(srcMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + // full original source and name information + var fullMapping1 = { + generated: { line: 1, column: 0 }, + original: { line: 11, column: 0 }, + source: 'fullMapping1.js', + name: 'fullMapping1' + }; + var fullMapping2 = { + generated: { line: 2, column: 2 }, + original: { line: 11, column: 0 }, + source: 'fullMapping2.js', + name: 'fullMapping2' + }; + + map1 = new SourceMapGenerator(init); + map2 = new SourceMapGenerator(init); + + map1.addMapping(fullMapping1); + map1.addMapping(fullMapping1); + + map2.addMapping(fullMapping1); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + + map1.addMapping(fullMapping2); + map1.addMapping(fullMapping1); + + map2.addMapping(fullMapping2); + + util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); + }; + + exports['test github issue #72, check for duplicate names or sources'] = function (assert, util) { + var map = new SourceMapGenerator({ + file: 'test.js' + }); + map.addMapping({ + generated: { line: 1, column: 1 }, + original: { line: 2, column: 2 }, + source: 'a.js', + name: 'foo' + }); + map.addMapping({ + generated: { line: 3, column: 3 }, + original: { line: 4, column: 4 }, + source: 'a.js', + name: 'foo' + }); + util.assertEqualMaps(assert, map.toJSON(), { + version: 3, + file: 'test.js', + sources: ['a.js'], + names: ['foo'], + mappings: 'CACEA;;GAEEA' + }); + }; + + exports['test setting sourcesContent to null when already null'] = function (assert, util) { + var smg = new SourceMapGenerator({ file: "foo.js" }); + assert.doesNotThrow(function() { + smg.setSourceContent("bar.js", null); + }); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-node.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-node.js new file mode 100644 index 000000000..139af4e44 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-source-node.js @@ -0,0 +1,612 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; + var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; + var SourceNode = require('../../lib/source-map/source-node').SourceNode; + + function forEachNewline(fn) { + return function (assert, util) { + ['\n', '\r\n'].forEach(fn.bind(null, assert, util)); + } + } + + exports['test .add()'] = function (assert, util) { + var node = new SourceNode(null, null, null); + + // Adding a string works. + node.add('function noop() {}'); + + // Adding another source node works. + node.add(new SourceNode(null, null, null)); + + // Adding an array works. + node.add(['function foo() {', + new SourceNode(null, null, null, + 'return 10;'), + '}']); + + // Adding other stuff doesn't. + assert.throws(function () { + node.add({}); + }); + assert.throws(function () { + node.add(function () {}); + }); + }; + + exports['test .prepend()'] = function (assert, util) { + var node = new SourceNode(null, null, null); + + // Prepending a string works. + node.prepend('function noop() {}'); + assert.equal(node.children[0], 'function noop() {}'); + assert.equal(node.children.length, 1); + + // Prepending another source node works. + node.prepend(new SourceNode(null, null, null)); + assert.equal(node.children[0], ''); + assert.equal(node.children[1], 'function noop() {}'); + assert.equal(node.children.length, 2); + + // Prepending an array works. + node.prepend(['function foo() {', + new SourceNode(null, null, null, + 'return 10;'), + '}']); + assert.equal(node.children[0], 'function foo() {'); + assert.equal(node.children[1], 'return 10;'); + assert.equal(node.children[2], '}'); + assert.equal(node.children[3], ''); + assert.equal(node.children[4], 'function noop() {}'); + assert.equal(node.children.length, 5); + + // Prepending other stuff doesn't. + assert.throws(function () { + node.prepend({}); + }); + assert.throws(function () { + node.prepend(function () {}); + }); + }; + + exports['test .toString()'] = function (assert, util) { + assert.equal((new SourceNode(null, null, null, + ['function foo() {', + new SourceNode(null, null, null, 'return 10;'), + '}'])).toString(), + 'function foo() {return 10;}'); + }; + + exports['test .join()'] = function (assert, util) { + assert.equal((new SourceNode(null, null, null, + ['a', 'b', 'c', 'd'])).join(', ').toString(), + 'a, b, c, d'); + }; + + exports['test .walk()'] = function (assert, util) { + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', new SourceNode(1, 0, 'a.js', ['someCall()']), ';\n', + ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n', + '}());']); + var expected = [ + { str: '(function () {\n', source: null, line: null, column: null }, + { str: ' ', source: null, line: null, column: null }, + { str: 'someCall()', source: 'a.js', line: 1, column: 0 }, + { str: ';\n', source: null, line: null, column: null }, + { str: ' ', source: null, line: null, column: null }, + { str: 'if (foo) bar()', source: 'b.js', line: 2, column: 0 }, + { str: ';\n', source: null, line: null, column: null }, + { str: '}());', source: null, line: null, column: null }, + ]; + var i = 0; + node.walk(function (chunk, loc) { + assert.equal(expected[i].str, chunk); + assert.equal(expected[i].source, loc.source); + assert.equal(expected[i].line, loc.line); + assert.equal(expected[i].column, loc.column); + i++; + }); + }; + + exports['test .replaceRight'] = function (assert, util) { + var node; + + // Not nested + node = new SourceNode(null, null, null, 'hello world'); + node.replaceRight(/world/, 'universe'); + assert.equal(node.toString(), 'hello universe'); + + // Nested + node = new SourceNode(null, null, null, + [new SourceNode(null, null, null, 'hey sexy mama, '), + new SourceNode(null, null, null, 'want to kill all humans?')]); + node.replaceRight(/kill all humans/, 'watch Futurama'); + assert.equal(node.toString(), 'hey sexy mama, want to watch Futurama?'); + }; + + exports['test .toStringWithSourceMap()'] = forEachNewline(function (assert, util, nl) { + var node = new SourceNode(null, null, null, + ['(function () {' + nl, + ' ', + new SourceNode(1, 0, 'a.js', 'someCall', 'originalCall'), + new SourceNode(1, 8, 'a.js', '()'), + ';' + nl, + ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';' + nl, + '}());']); + var result = node.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(result.code, [ + '(function () {', + ' someCall();', + ' if (foo) bar();', + '}());' + ].join(nl)); + + var map = result.map; + var mapWithoutOptions = node.toStringWithSourceMap().map; + + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + assert.ok(mapWithoutOptions instanceof SourceMapGenerator, 'mapWithoutOptions instanceof SourceMapGenerator'); + assert.ok(!('file' in mapWithoutOptions)); + mapWithoutOptions._file = 'foo.js'; + util.assertEqualMaps(assert, map.toJSON(), mapWithoutOptions.toJSON()); + + map = new SourceMapConsumer(map.toString()); + + var actual; + + actual = map.originalPositionFor({ + line: 1, + column: 4 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + + actual = map.originalPositionFor({ + line: 2, + column: 2 + }); + assert.equal(actual.source, 'a.js'); + assert.equal(actual.line, 1); + assert.equal(actual.column, 0); + assert.equal(actual.name, 'originalCall'); + + actual = map.originalPositionFor({ + line: 3, + column: 2 + }); + assert.equal(actual.source, 'b.js'); + assert.equal(actual.line, 2); + assert.equal(actual.column, 0); + + actual = map.originalPositionFor({ + line: 3, + column: 16 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + + actual = map.originalPositionFor({ + line: 4, + column: 2 + }); + assert.equal(actual.source, null); + assert.equal(actual.line, null); + assert.equal(actual.column, null); + }); + + exports['test .fromStringWithSourceMap()'] = forEachNewline(function (assert, util, nl) { + var testCode = util.testGeneratedCode.replace(/\n/g, nl); + var node = SourceNode.fromStringWithSourceMap( + testCode, + new SourceMapConsumer(util.testMap)); + + var result = node.toStringWithSourceMap({ + file: 'min.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, testCode); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + assert.equal(map.version, util.testMap.version); + assert.equal(map.file, util.testMap.file); + assert.equal(map.mappings, util.testMap.mappings); + }); + + exports['test .fromStringWithSourceMap() empty map'] = forEachNewline(function (assert, util, nl) { + var node = SourceNode.fromStringWithSourceMap( + util.testGeneratedCode.replace(/\n/g, nl), + new SourceMapConsumer(util.emptyMap)); + var result = node.toStringWithSourceMap({ + file: 'min.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, util.testGeneratedCode.replace(/\n/g, nl)); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + assert.equal(map.version, util.emptyMap.version); + assert.equal(map.file, util.emptyMap.file); + assert.equal(map.mappings.length, util.emptyMap.mappings.length); + assert.equal(map.mappings, util.emptyMap.mappings); + }); + + exports['test .fromStringWithSourceMap() complex version'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + "(function() {" + nl, + " var Test = {};" + nl, + " ", new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };" + nl), + " ", new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), nl, + "}());" + nl, + "/* Generated Source */"]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + var node = SourceNode.fromStringWithSourceMap( + input.code, + new SourceMapConsumer(input.map.toString())); + + var result = node.toStringWithSourceMap({ + file: 'foo.js' + }); + var map = result.map; + var code = result.code; + + assert.equal(code, input.code); + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = map.toJSON(); + var inputMap = input.map.toJSON(); + util.assertEqualMaps(assert, map, inputMap); + }); + + exports['test .fromStringWithSourceMap() third argument'] = function (assert, util) { + // Assume the following directory structure: + // + // http://foo.org/ + // bar.coffee + // app/ + // coffee/ + // foo.coffee + // coffeeBundle.js # Made from {foo,bar,baz}.coffee + // maps/ + // coffeeBundle.js.map + // js/ + // foo.js + // public/ + // app.js # Made from {foo,coffeeBundle}.js + // app.js.map + // + // http://www.example.com/ + // baz.coffee + + var coffeeBundle = new SourceNode(1, 0, 'foo.coffee', 'foo(coffee);\n'); + coffeeBundle.setSourceContent('foo.coffee', 'foo coffee'); + coffeeBundle.add(new SourceNode(2, 0, '/bar.coffee', 'bar(coffee);\n')); + coffeeBundle.add(new SourceNode(3, 0, 'http://www.example.com/baz.coffee', 'baz(coffee);')); + coffeeBundle = coffeeBundle.toStringWithSourceMap({ + file: 'foo.js', + sourceRoot: '..' + }); + + var foo = new SourceNode(1, 0, 'foo.js', 'foo(js);'); + + var test = function(relativePath, expectedSources) { + var app = new SourceNode(); + app.add(SourceNode.fromStringWithSourceMap( + coffeeBundle.code, + new SourceMapConsumer(coffeeBundle.map.toString()), + relativePath)); + app.add(foo); + var i = 0; + app.walk(function (chunk, loc) { + assert.equal(loc.source, expectedSources[i]); + i++; + }); + app.walkSourceContents(function (sourceFile, sourceContent) { + assert.equal(sourceFile, expectedSources[0]); + assert.equal(sourceContent, 'foo coffee'); + }) + }; + + test('../coffee/maps', [ + '../coffee/foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + // If the third parameter is omitted or set to the current working + // directory we get incorrect source paths: + + test(undefined, [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('.', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + + test('./', [ + '../foo.coffee', + '/bar.coffee', + 'http://www.example.com/baz.coffee', + 'foo.js' + ]); + }; + + exports['test .toStringWithSourceMap() merging duplicate mappings'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + new SourceNode(1, 0, "a.js", "(function"), + new SourceNode(1, 0, "a.js", "() {" + nl), + " ", + new SourceNode(1, 0, "a.js", "var Test = "), + new SourceNode(1, 0, "b.js", "{};" + nl), + new SourceNode(2, 0, "b.js", "Test"), + new SourceNode(2, 0, "b.js", ".A", "A"), + new SourceNode(2, 20, "b.js", " = { value: ", "A"), + "1234", + new SourceNode(2, 40, "b.js", " };" + nl, "A"), + "}());" + nl, + "/* Generated Source */" + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "(function() {", + " var Test = {};", + "Test.A = { value: 1234 };", + "}());", + "/* Generated Source */" + ].join(nl)) + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 1, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + // Here is no need for a empty mapping, + // because mappings ends at eol + correctMap.addMapping({ + generated: { line: 2, column: 2 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 2, column: 13 }, + source: 'b.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'b.js', + original: { line: 2, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 4 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 6 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 20 } + }); + // This empty mapping is required, + // because there is a hole in the middle of the line + correctMap.addMapping({ + generated: { line: 3, column: 18 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 22 }, + source: 'b.js', + name: 'A', + original: { line: 2, column: 40 } + }); + // Here is no need for a empty mapping, + // because mappings ends at eol + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test .toStringWithSourceMap() multi-line SourceNodes'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + new SourceNode(1, 0, "a.js", "(function() {" + nl + "var nextLine = 1;" + nl + "anotherLine();" + nl), + new SourceNode(2, 2, "b.js", "Test.call(this, 123);" + nl), + new SourceNode(2, 2, "b.js", "this['stuff'] = 'v';" + nl), + new SourceNode(2, 2, "b.js", "anotherLine();" + nl), + "/*" + nl + "Generated" + nl + "Source" + nl + "*/" + nl, + new SourceNode(3, 4, "c.js", "anotherLine();" + nl), + "/*" + nl + "Generated" + nl + "Source" + nl + "*/" + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "(function() {", + "var nextLine = 1;", + "anotherLine();", + "Test.call(this, 123);", + "this['stuff'] = 'v';", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/" + ].join(nl)); + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 1, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 2, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 4, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 5, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 6, column: 0 }, + source: 'b.js', + original: { line: 2, column: 2 } + }); + correctMap.addMapping({ + generated: { line: 11, column: 0 }, + source: 'c.js', + original: { line: 3, column: 4 } + }); + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test .toStringWithSourceMap() with empty string'] = function (assert, util) { + var node = new SourceNode(1, 0, 'empty.js', ''); + var result = node.toStringWithSourceMap(); + assert.equal(result.code, ''); + }; + + exports['test .toStringWithSourceMap() with consecutive newlines'] = forEachNewline(function (assert, util, nl) { + var input = new SourceNode(null, null, null, [ + "/***/" + nl + nl, + new SourceNode(1, 0, "a.js", "'use strict';" + nl), + new SourceNode(2, 0, "a.js", "a();"), + ]); + input = input.toStringWithSourceMap({ + file: 'foo.js' + }); + + assert.equal(input.code, [ + "/***/", + "", + "'use strict';", + "a();", + ].join(nl)); + + var correctMap = new SourceMapGenerator({ + file: 'foo.js' + }); + correctMap.addMapping({ + generated: { line: 3, column: 0 }, + source: 'a.js', + original: { line: 1, column: 0 } + }); + correctMap.addMapping({ + generated: { line: 4, column: 0 }, + source: 'a.js', + original: { line: 2, column: 0 } + }); + + var inputMap = input.map.toJSON(); + correctMap = correctMap.toJSON(); + util.assertEqualMaps(assert, inputMap, correctMap); + }); + + exports['test setSourceContent with toStringWithSourceMap'] = function (assert, util) { + var aNode = new SourceNode(1, 1, 'a.js', 'a'); + aNode.setSourceContent('a.js', 'someContent'); + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', aNode, + ' ', new SourceNode(1, 1, 'b.js', 'b'), + '}());']); + node.setSourceContent('b.js', 'otherContent'); + var map = node.toStringWithSourceMap({ + file: 'foo.js' + }).map; + + assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); + map = new SourceMapConsumer(map.toString()); + + assert.equal(map.sources.length, 2); + assert.equal(map.sources[0], 'a.js'); + assert.equal(map.sources[1], 'b.js'); + assert.equal(map.sourcesContent.length, 2); + assert.equal(map.sourcesContent[0], 'someContent'); + assert.equal(map.sourcesContent[1], 'otherContent'); + }; + + exports['test walkSourceContents'] = function (assert, util) { + var aNode = new SourceNode(1, 1, 'a.js', 'a'); + aNode.setSourceContent('a.js', 'someContent'); + var node = new SourceNode(null, null, null, + ['(function () {\n', + ' ', aNode, + ' ', new SourceNode(1, 1, 'b.js', 'b'), + '}());']); + node.setSourceContent('b.js', 'otherContent'); + var results = []; + node.walkSourceContents(function (sourceFile, sourceContent) { + results.push([sourceFile, sourceContent]); + }); + assert.equal(results.length, 2); + assert.equal(results[0][0], 'a.js'); + assert.equal(results[0][1], 'someContent'); + assert.equal(results[1][0], 'b.js'); + assert.equal(results[1][1], 'otherContent'); + }; +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-util.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-util.js new file mode 100644 index 000000000..997d1a269 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/test-util.js @@ -0,0 +1,216 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var libUtil = require('../../lib/source-map/util'); + + exports['test urls'] = function (assert, util) { + var assertUrl = function (url) { + assert.equal(url, libUtil.urlGenerate(libUtil.urlParse(url))); + }; + assertUrl('http://'); + assertUrl('http://www.example.com'); + assertUrl('http://user:pass@www.example.com'); + assertUrl('http://www.example.com:80'); + assertUrl('http://www.example.com/'); + assertUrl('http://www.example.com/foo/bar'); + assertUrl('http://www.example.com/foo/bar/'); + assertUrl('http://user:pass@www.example.com:80/foo/bar/'); + + assertUrl('//'); + assertUrl('//www.example.com'); + assertUrl('file:///www.example.com'); + + assert.equal(libUtil.urlParse(''), null); + assert.equal(libUtil.urlParse('.'), null); + assert.equal(libUtil.urlParse('..'), null); + assert.equal(libUtil.urlParse('a'), null); + assert.equal(libUtil.urlParse('a/b'), null); + assert.equal(libUtil.urlParse('a//b'), null); + assert.equal(libUtil.urlParse('/a'), null); + assert.equal(libUtil.urlParse('data:foo,bar'), null); + }; + + exports['test normalize()'] = function (assert, util) { + assert.equal(libUtil.normalize('/..'), '/'); + assert.equal(libUtil.normalize('/../'), '/'); + assert.equal(libUtil.normalize('/../../../..'), '/'); + assert.equal(libUtil.normalize('/../../../../a/b/c'), '/a/b/c'); + assert.equal(libUtil.normalize('/a/b/c/../../../d/../../e'), '/e'); + + assert.equal(libUtil.normalize('..'), '..'); + assert.equal(libUtil.normalize('../'), '../'); + assert.equal(libUtil.normalize('../../a/'), '../../a/'); + assert.equal(libUtil.normalize('a/..'), '.'); + assert.equal(libUtil.normalize('a/../../..'), '../..'); + + assert.equal(libUtil.normalize('/.'), '/'); + assert.equal(libUtil.normalize('/./'), '/'); + assert.equal(libUtil.normalize('/./././.'), '/'); + assert.equal(libUtil.normalize('/././././a/b/c'), '/a/b/c'); + assert.equal(libUtil.normalize('/a/b/c/./././d/././e'), '/a/b/c/d/e'); + + assert.equal(libUtil.normalize(''), '.'); + assert.equal(libUtil.normalize('.'), '.'); + assert.equal(libUtil.normalize('./'), '.'); + assert.equal(libUtil.normalize('././a'), 'a'); + assert.equal(libUtil.normalize('a/./'), 'a/'); + assert.equal(libUtil.normalize('a/././.'), 'a'); + + assert.equal(libUtil.normalize('/a/b//c////d/////'), '/a/b/c/d/'); + assert.equal(libUtil.normalize('///a/b//c////d/////'), '///a/b/c/d/'); + assert.equal(libUtil.normalize('a/b//c////d'), 'a/b/c/d'); + + assert.equal(libUtil.normalize('.///.././../a/b//./..'), '../../a') + + assert.equal(libUtil.normalize('http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.normalize('http://www.example.com/'), 'http://www.example.com/'); + assert.equal(libUtil.normalize('http://www.example.com/./..//a/b/c/.././d//'), 'http://www.example.com/a/b/d/'); + }; + + exports['test join()'] = function (assert, util) { + assert.equal(libUtil.join('a', 'b'), 'a/b'); + assert.equal(libUtil.join('a/', 'b'), 'a/b'); + assert.equal(libUtil.join('a//', 'b'), 'a/b'); + assert.equal(libUtil.join('a', 'b/'), 'a/b/'); + assert.equal(libUtil.join('a', 'b//'), 'a/b/'); + assert.equal(libUtil.join('a/', '/b'), '/b'); + assert.equal(libUtil.join('a//', '//b'), '//b'); + + assert.equal(libUtil.join('a', '..'), '.'); + assert.equal(libUtil.join('a', '../b'), 'b'); + assert.equal(libUtil.join('a/b', '../c'), 'a/c'); + + assert.equal(libUtil.join('a', '.'), 'a'); + assert.equal(libUtil.join('a', './b'), 'a/b'); + assert.equal(libUtil.join('a/b', './c'), 'a/b/c'); + + assert.equal(libUtil.join('a', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('a', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('', 'b'), 'b'); + assert.equal(libUtil.join('.', 'b'), 'b'); + assert.equal(libUtil.join('', 'b/'), 'b/'); + assert.equal(libUtil.join('.', 'b/'), 'b/'); + assert.equal(libUtil.join('', 'b//'), 'b/'); + assert.equal(libUtil.join('.', 'b//'), 'b/'); + + assert.equal(libUtil.join('', '..'), '..'); + assert.equal(libUtil.join('.', '..'), '..'); + assert.equal(libUtil.join('', '../b'), '../b'); + assert.equal(libUtil.join('.', '../b'), '../b'); + + assert.equal(libUtil.join('', '.'), '.'); + assert.equal(libUtil.join('.', '.'), '.'); + assert.equal(libUtil.join('', './b'), 'b'); + assert.equal(libUtil.join('.', './b'), 'b'); + + assert.equal(libUtil.join('', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('.', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('', 'data:foo,bar'), 'data:foo,bar'); + assert.equal(libUtil.join('.', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('..', 'b'), '../b'); + assert.equal(libUtil.join('..', 'b/'), '../b/'); + assert.equal(libUtil.join('..', 'b//'), '../b/'); + + assert.equal(libUtil.join('..', '..'), '../..'); + assert.equal(libUtil.join('..', '../b'), '../../b'); + + assert.equal(libUtil.join('..', '.'), '..'); + assert.equal(libUtil.join('..', './b'), '../b'); + + assert.equal(libUtil.join('..', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('..', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('a', ''), 'a'); + assert.equal(libUtil.join('a', '.'), 'a'); + assert.equal(libUtil.join('a/', ''), 'a'); + assert.equal(libUtil.join('a/', '.'), 'a'); + assert.equal(libUtil.join('a//', ''), 'a'); + assert.equal(libUtil.join('a//', '.'), 'a'); + assert.equal(libUtil.join('/a', ''), '/a'); + assert.equal(libUtil.join('/a', '.'), '/a'); + assert.equal(libUtil.join('', ''), '.'); + assert.equal(libUtil.join('.', ''), '.'); + assert.equal(libUtil.join('.', ''), '.'); + assert.equal(libUtil.join('.', '.'), '.'); + assert.equal(libUtil.join('..', ''), '..'); + assert.equal(libUtil.join('..', '.'), '..'); + assert.equal(libUtil.join('http://foo.org/a', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a/', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a/', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a//', ''), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a//', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org//', ''), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org//', '.'), 'http://foo.org/'); + assert.equal(libUtil.join('//www.example.com', ''), '//www.example.com/'); + assert.equal(libUtil.join('//www.example.com', '.'), '//www.example.com/'); + + + assert.equal(libUtil.join('http://foo.org/a', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a/', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a//', 'b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a', 'b/'), 'http://foo.org/a/b/'); + assert.equal(libUtil.join('http://foo.org/a', 'b//'), 'http://foo.org/a/b/'); + assert.equal(libUtil.join('http://foo.org/a/', '/b'), 'http://foo.org/b'); + assert.equal(libUtil.join('http://foo.org/a//', '//b'), 'http://b'); + + assert.equal(libUtil.join('http://foo.org/a', '..'), 'http://foo.org/'); + assert.equal(libUtil.join('http://foo.org/a', '../b'), 'http://foo.org/b'); + assert.equal(libUtil.join('http://foo.org/a/b', '../c'), 'http://foo.org/a/c'); + + assert.equal(libUtil.join('http://foo.org/a', '.'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/a', './b'), 'http://foo.org/a/b'); + assert.equal(libUtil.join('http://foo.org/a/b', './c'), 'http://foo.org/a/b/c'); + + assert.equal(libUtil.join('http://foo.org/a', 'http://www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('http://foo.org/a', 'data:foo,bar'), 'data:foo,bar'); + + + assert.equal(libUtil.join('http://foo.org', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org//', 'a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org', '/a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org/', '/a'), 'http://foo.org/a'); + assert.equal(libUtil.join('http://foo.org//', '/a'), 'http://foo.org/a'); + + + assert.equal(libUtil.join('http://', 'www.example.com'), 'http://www.example.com'); + assert.equal(libUtil.join('file:///', 'www.example.com'), 'file:///www.example.com'); + assert.equal(libUtil.join('http://', 'ftp://example.com'), 'ftp://example.com'); + + assert.equal(libUtil.join('http://www.example.com', '//foo.org/bar'), 'http://foo.org/bar'); + assert.equal(libUtil.join('//www.example.com', '//foo.org/bar'), '//foo.org/bar'); + }; + + // TODO Issue #128: Define and test this function properly. + exports['test relative()'] = function (assert, util) { + assert.equal(libUtil.relative('/the/root', '/the/root/one.js'), 'one.js'); + assert.equal(libUtil.relative('/the/root', '/the/rootone.js'), '/the/rootone.js'); + + assert.equal(libUtil.relative('', '/the/root/one.js'), '/the/root/one.js'); + assert.equal(libUtil.relative('.', '/the/root/one.js'), '/the/root/one.js'); + assert.equal(libUtil.relative('', 'the/root/one.js'), 'the/root/one.js'); + assert.equal(libUtil.relative('.', 'the/root/one.js'), 'the/root/one.js'); + + assert.equal(libUtil.relative('/', '/the/root/one.js'), 'the/root/one.js'); + assert.equal(libUtil.relative('/', 'the/root/one.js'), 'the/root/one.js'); + }; + +}); diff --git a/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/util.js b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/util.js new file mode 100644 index 000000000..fa213ce13 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/node_modules/source-map/test/source-map/util.js @@ -0,0 +1,176 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('../../lib/source-map/util'); + + // This is a test mapping which maps functions from two different files + // (one.js and two.js) to a minified generated source. + // + // Here is one.js: + // + // ONE.foo = function (bar) { + // return baz(bar); + // }; + // + // Here is two.js: + // + // TWO.inc = function (n) { + // return n + 1; + // }; + // + // And here is the generated code (min.js): + // + // ONE.foo=function(a){return baz(a);}; + // TWO.inc=function(a){return a+1;}; + exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n"+ + " TWO.inc=function(a){return a+1;};"; + exports.testMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: '/the/root', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapNoSourceRoot = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapEmptySourceRoot = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: '', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.testMapWithSourcesContent = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourcesContent: [ + ' ONE.foo = function (bar) {\n' + + ' return baz(bar);\n' + + ' };', + ' TWO.inc = function (n) {\n' + + ' return n + 1;\n' + + ' };' + ], + sourceRoot: '/the/root', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + }; + exports.emptyMap = { + version: 3, + file: 'min.js', + names: [], + sources: [], + mappings: '' + }; + + + function assertMapping(generatedLine, generatedColumn, originalSource, + originalLine, originalColumn, name, map, assert, + dontTestGenerated, dontTestOriginal) { + if (!dontTestOriginal) { + var origMapping = map.originalPositionFor({ + line: generatedLine, + column: generatedColumn + }); + assert.equal(origMapping.name, name, + 'Incorrect name, expected ' + JSON.stringify(name) + + ', got ' + JSON.stringify(origMapping.name)); + assert.equal(origMapping.line, originalLine, + 'Incorrect line, expected ' + JSON.stringify(originalLine) + + ', got ' + JSON.stringify(origMapping.line)); + assert.equal(origMapping.column, originalColumn, + 'Incorrect column, expected ' + JSON.stringify(originalColumn) + + ', got ' + JSON.stringify(origMapping.column)); + + var expectedSource; + + if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) { + expectedSource = originalSource; + } else if (originalSource) { + expectedSource = map.sourceRoot + ? util.join(map.sourceRoot, originalSource) + : originalSource; + } else { + expectedSource = null; + } + + assert.equal(origMapping.source, expectedSource, + 'Incorrect source, expected ' + JSON.stringify(expectedSource) + + ', got ' + JSON.stringify(origMapping.source)); + } + + if (!dontTestGenerated) { + var genMapping = map.generatedPositionFor({ + source: originalSource, + line: originalLine, + column: originalColumn + }); + assert.equal(genMapping.line, generatedLine, + 'Incorrect line, expected ' + JSON.stringify(generatedLine) + + ', got ' + JSON.stringify(genMapping.line)); + assert.equal(genMapping.column, generatedColumn, + 'Incorrect column, expected ' + JSON.stringify(generatedColumn) + + ', got ' + JSON.stringify(genMapping.column)); + } + } + exports.assertMapping = assertMapping; + + function assertEqualMaps(assert, actualMap, expectedMap) { + assert.equal(actualMap.version, expectedMap.version, "version mismatch"); + assert.equal(actualMap.file, expectedMap.file, "file mismatch"); + assert.equal(actualMap.names.length, + expectedMap.names.length, + "names length mismatch: " + + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + for (var i = 0; i < actualMap.names.length; i++) { + assert.equal(actualMap.names[i], + expectedMap.names[i], + "names[" + i + "] mismatch: " + + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + } + assert.equal(actualMap.sources.length, + expectedMap.sources.length, + "sources length mismatch: " + + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + for (var i = 0; i < actualMap.sources.length; i++) { + assert.equal(actualMap.sources[i], + expectedMap.sources[i], + "sources[" + i + "] length mismatch: " + + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + } + assert.equal(actualMap.sourceRoot, + expectedMap.sourceRoot, + "sourceRoot mismatch: " + + actualMap.sourceRoot + " != " + expectedMap.sourceRoot); + assert.equal(actualMap.mappings, expectedMap.mappings, + "mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings); + if (actualMap.sourcesContent) { + assert.equal(actualMap.sourcesContent.length, + expectedMap.sourcesContent.length, + "sourcesContent length mismatch"); + for (var i = 0; i < actualMap.sourcesContent.length; i++) { + assert.equal(actualMap.sourcesContent[i], + expectedMap.sourcesContent[i], + "sourcesContent[" + i + "] mismatch"); + } + } + } + exports.assertEqualMaps = assertEqualMaps; + +}); diff --git a/node_modules/less-middleware/node_modules/less/package.json b/node_modules/less-middleware/node_modules/less/package.json new file mode 100644 index 000000000..d54acfc32 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/package.json @@ -0,0 +1,105 @@ +{ + "name": "less", + "version": "1.7.5", + "description": "Leaner CSS", + "homepage": "http://lesscss.org", + "author": { + "name": "Alexis Sellier", + "email": "self@cloudhead.net" + }, + "contributors": [ + { + "name": "The Core Less Team" + } + ], + "bugs": { + "url": "https://github.com/less/less.js/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/less/less.js.git" + }, + "licenses": [ + { + "type": "Apache v2", + "url": "https://github.com/less/less.js/blob/master/LICENSE" + } + ], + "bin": { + "lessc": "./bin/lessc" + }, + "main": "./lib/less/index", + "directories": { + "test": "./test" + }, + "jam": { + "main": "./dist/less-1.7.5.js" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "test": "grunt test" + }, + "optionalDependencies": { + "graceful-fs": "~3.0.2", + "mime": "~1.2.11", + "request": "~2.40.0", + "mkdirp": "~0.5.0", + "clean-css": "2.2.x", + "source-map": "0.1.x" + }, + "devDependencies": { + "diff": "~1.0", + "grunt": "~0.4.2", + "grunt-contrib-clean": "~0.5.0", + "grunt-contrib-concat": "~0.4.0", + "grunt-contrib-connect": "~0.7.0", + "grunt-contrib-jasmine": "~0.5.2", + "grunt-contrib-jshint": "~0.10.0", + "grunt-contrib-uglify": "~0.4.0", + "grunt-shell": "~0.7.0", + "http-server": "~0.6.1", + "matchdep": "~0.3.0", + "time-grunt": "~0.3.1" + }, + "keywords": [ + "compile less", + "css nesting", + "css variable", + "css", + "gradients css", + "gradients css3", + "less compiler", + "less css", + "less mixins", + "less", + "less.js", + "lesscss", + "mixins", + "nested css", + "parser", + "preprocessor", + "bootstrap css", + "bootstrap less", + "style", + "styles", + "stylesheet", + "variables in css", + "css less" + ], + "readme": "[![NPM version](https://badge.fury.io/js/less.svg)](http://badge.fury.io/js/less) [![Build Status](https://travis-ci.org/less/less.js.png?branch=master)](https://travis-ci.org/less/less.js)\n [![Dependencies](https://david-dm.org/less/less.js.png)](https://david-dm.org/less/less.js) [![devDependency Status](https://david-dm.org/less/less.js/dev-status.png)](https://david-dm.org/less/less.js#info=devDependencies) [![optionalDependency Status](https://david-dm.org/less/less.js/optional-status.png)](https://david-dm.org/less/less.js#info=optionalDependencies)\n\n# [Less.js](http://lesscss.org)\n\n> The **dynamic** stylesheet language. [http://lesscss.org](http://lesscss.org).\n\nThis is the JavaScript, official, stable version of Less.\n\n\n## Getting Started\n\nOptions for adding Less.js to your project:\n\n* Install with [NPM](https://npmjs.org/): `npm install less`\n* [Download the latest release][download]\n* Clone the repo: `git clone git://github.com/less/less.js.git`\n\n## More information\n\nFor general information on the language, configuration options or usage visit [lesscss.org](http://lesscss.org).\n\nHere are other resources for using Less.js:\n\n* [stackoverflow.com][so] is a great place to get answers about Less.\n* [Less.js Issues][issues] for reporting bugs\n\n\n## Contributing\nPlease read [CONTRIBUTING.md](./CONTRIBUTING.md). Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).\n\n### Reporting Issues\n\nBefore opening any issue, please search for existing issues and read the [Issue Guidelines](https://github.com/necolas/issue-guidelines), written by [Nicolas Gallagher](https://github.com/necolas/). After that if you find a bug or would like to make feature request, [please open a new issue][issues].\n\nPlease report documentation issues in [the documentation project](https://github.com/less/less-docs).\n\n### Development\n\nRead [Developing Less](http://lesscss.org/usage/#developing-less).\n\n## Release History\nSee the [changelog](CHANGELOG.md)\n\n## [License](LICENSE)\n\nCopyright (c) 2009-2014 [Alexis Sellier](http://cloudhead.io/) & The Core Less Team\nLicensed under the [Apache License](LICENSE).\n\n\n[so]: http://stackoverflow.com/questions/tagged/twitter-bootstrap+less \"StackOverflow.com\"\n[issues]: https://github.com/less/less.js/issues \"GitHub Issues for Less.js\"\n[download]: https://github.com/less/less.js/zipball/master \"Download Less.js\"\n", + "readmeFilename": "README.md", + "dependencies": { + "graceful-fs": "~3.0.2", + "mime": "~1.2.11", + "request": "~2.40.0", + "mkdirp": "~0.5.0", + "clean-css": "2.2.x", + "source-map": "0.1.x" + }, + "_id": "less@1.7.5", + "_shasum": "4f220cf7288a27eaca739df6e4808a2d4c0d5756", + "_from": "less@1.7.x", + "_resolved": "https://registry.npmjs.org/less/-/less-1.7.5.tgz" +} diff --git a/node_modules/less-middleware/node_modules/less/projectFilesBackup/.idea/libraries/sass_stdlib.xml b/node_modules/less-middleware/node_modules/less/projectFilesBackup/.idea/libraries/sass_stdlib.xml new file mode 100644 index 000000000..546bfd172 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/projectFilesBackup/.idea/libraries/sass_stdlib.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/common.js b/node_modules/less-middleware/node_modules/less/test/browser/common.js new file mode 100644 index 000000000..6e2bb3826 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/common.js @@ -0,0 +1,201 @@ +/* record log messages for testing */ +// var logAllIds = function() { +// var allTags = document.head.getElementsByTagName('style'); +// var ids = []; +// for (var tg = 0; tg < allTags.length; tg++) { +// var tag = allTags[tg]; +// if (tag.id) { +// console.log(tag.id); +// } +// } +// }; + +var logMessages = [], + realConsoleLog = console.log; +console.log = function(msg) { + logMessages.push(msg); + realConsoleLog.call(console, msg); +}; + +var testLessEqualsInDocument = function() { + testLessInDocument(testSheet); +}; + +var testLessErrorsInDocument = function(isConsole) { + testLessInDocument(isConsole ? testErrorSheetConsole : testErrorSheet); +}; + +var testLessInDocument = function(testFunc) { + var links = document.getElementsByTagName('link'), + typePattern = /^text\/(x-)?less$/; + + for (var i = 0; i < links.length; i++) { + if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && + (links[i].type.match(typePattern)))) { + testFunc(links[i]); + } + } +}; + +var testSheet = function(sheet) { + it(sheet.id + " should match the expected output", function() { + var lessOutputId = sheet.id.replace("original-", ""), + expectedOutputId = "expected-" + lessOutputId, + lessOutputObj, + lessOutput, + expectedOutputHref = document.getElementById(expectedOutputId).href, + expectedOutput = loadFile(expectedOutputHref); + + // Browser spec generates less on the fly, so we need to loose control + waitsFor(function() { + lessOutputObj = document.getElementById(lessOutputId); + // the type condition is necessary because of inline browser tests + return lessOutputObj !== null && lessOutputObj.type === "text/css"; + }, "generation of " + lessOutputId + "", 700); + + runs(function() { + lessOutput = lessOutputObj.innerText || lessOutputObj.innerHTML; + }); + + waitsFor(function() { + return expectedOutput.loaded; + }, "failed to load expected outout", 10000); + + runs(function() { + // use sheet to do testing + expect(expectedOutput.text).toEqual(lessOutput); + }); + }); +}; + +//TODO: do it cleaner - the same way as in css + +function extractId(href) { + return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain + .replace(/^\//, '') // Remove root / + .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension + .replace(/[^\.\w-]+/g, '-') // Replace illegal characters + .replace(/\./g, ':'); // Replace dots with colons(for valid id) +} + +var testErrorSheet = function(sheet) { + it(sheet.id + " should match an error", function() { + var lessHref = sheet.href, + id = "less-error-message:" + extractId(lessHref), + // id = sheet.id.replace(/^original-less:/, "less-error-message:"), + errorHref = lessHref.replace(/.less$/, ".txt"), + errorFile = loadFile(errorHref), + actualErrorElement, + actualErrorMsg; + + // Less.js sets 10ms timer in order to add error message on top of page. + waitsFor(function() { + actualErrorElement = document.getElementById(id); + return actualErrorElement !== null; + }, "error message was not generated", 70); + + runs(function() { + actualErrorMsg = actualErrorElement.innerText + .replace(/\n\d+/g, function(lineNo) { + return lineNo + " "; + }) + .replace(/\n\s*in /g, " in ") + .replace("\n\n", "\n"); + }); + + waitsFor(function() { + return errorFile.loaded; + }, "failed to load expected outout", 10000); + + runs(function() { + var errorTxt = errorFile.text + .replace("{path}", "") + .replace("{pathrel}", "") + .replace("{pathhref}", "http://localhost:8081/test/less/errors/") + .replace("{404status}", " (404)"); + expect(errorTxt).toEqual(actualErrorMsg); + if (errorTxt == actualErrorMsg) { + actualErrorElement.style.display = "none"; + } + }); + }); +}; + +var testErrorSheetConsole = function(sheet) { + it(sheet.id + " should match an error", function() { + var lessHref = sheet.href, + id = sheet.id.replace(/^original-less:/, "less-error-message:"), + errorHref = lessHref.replace(/.less$/, ".txt"), + errorFile = loadFile(errorHref), + actualErrorElement = document.getElementById(id), + actualErrorMsg = logMessages[logMessages.length - 1]; + + describe("the error", function() { + expect(actualErrorElement).toBe(null); + + }); + + /*actualErrorMsg = actualErrorElement.innerText + .replace(/\n\d+/g, function(lineNo) { return lineNo + " "; }) + .replace(/\n\s*in /g, " in ") + .replace("\n\n", "\n");*/ + + waitsFor(function() { + return errorFile.loaded; + }, "failed to load expected outout", 10000); + + runs(function() { + var errorTxt = errorFile.text + .replace("{path}", "") + .replace("{pathrel}", "") + .replace("{pathhref}", "http://localhost:8081/browser/less/") + .replace("{404status}", " (404)") + .trim(); + expect(errorTxt).toEqual(actualErrorMsg); + }); + }); +}; + +var loadFile = function(href) { + var request = new XMLHttpRequest(), + response = { + loaded: false, + text: "" + }; + request.open('GET', href, true); + request.onload = function(e) { + response.text = request.response.replace(/\r/g, ""); + response.loaded = true; + }; + request.send(); + return response; +}; + +(function() { + var jasmineEnv = jasmine.getEnv(); + jasmineEnv.updateInterval = 1000; + + var htmlReporter = new jasmine.HtmlReporter(); + + jasmineEnv.addReporter(htmlReporter); + + jasmineEnv.specFilter = function(spec) { + return htmlReporter.specFilter(spec); + }; + + var currentWindowOnload = window.onload; + + window.onload = function() { + if (currentWindowOnload) { + currentWindowOnload(); + } + execJasmine(); + }; + + function execJasmine() { + setTimeout(function() { + jasmineEnv.execute(); + }, 3000); + } + +})(); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/global-vars/simple.css b/node_modules/less-middleware/node_modules/less/test/browser/css/global-vars/simple.css new file mode 100644 index 000000000..05b9fb02f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/global-vars/simple.css @@ -0,0 +1,3 @@ +.test { + color: #ff0000; +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/modify-vars/simple.css b/node_modules/less-middleware/node_modules/less/test/browser/css/modify-vars/simple.css new file mode 100644 index 000000000..889cd53d9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/modify-vars/simple.css @@ -0,0 +1,8 @@ +.testisimported { + color: gainsboro; +} +.test { + color1: #008000; + color2: #800080; + scalar: 20; +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/postProcessor/postProcessor.css b/node_modules/less-middleware/node_modules/less/test/browser/css/postProcessor/postProcessor.css new file mode 100644 index 000000000..76de30bd0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/postProcessor/postProcessor.css @@ -0,0 +1,4 @@ +hr {height:50px;} +.test { + color: #ffffff; +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/relative-urls/urls.css b/node_modules/less-middleware/node_modules/less/test/browser/css/relative-urls/urls.css new file mode 100644 index 000000000..891d5977b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/relative-urls/urls.css @@ -0,0 +1,35 @@ +@import "http://localhost:8081/test/browser/less/imports/modify-this.css"; +@import "http://localhost:8081/test/browser/less/imports/modify-again.css"; +.modify { + my-url: url("http://localhost:8081/test/browser/less/imports/a.png"); +} +.modify { + my-url: url("http://localhost:8081/test/browser/less/imports/b.png"); +} +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(http://localhost:8081/test/browser/less/relative-urls/fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(http://localhost:8081/test/browser/less/relative-urls/images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(http://localhost:8081/test/browser/less/relative-urls/bg.jpg) no-repeat, url(http://localhost:8081/test/browser/less/relative-urls/bg.png) repeat-x top left, url(http://localhost:8081/test/browser/less/relative-urls/bg); +} +.values { + url: url('http://localhost:8081/test/browser/less/relative-urls/Trebuchet'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath-relative/urls.css b/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath-relative/urls.css new file mode 100644 index 000000000..20b08339d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath-relative/urls.css @@ -0,0 +1,35 @@ +@import "https://www.github.com/cloudhead/imports/modify-this.css"; +@import "https://www.github.com/cloudhead/imports/modify-again.css"; +.modify { + my-url: url("https://www.github.com/cloudhead/imports/a.png"); +} +.modify { + my-url: url("https://www.github.com/cloudhead/imports/b.png"); +} +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(https://www.github.com/cloudhead/less.js/fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(https://www.github.com/cloudhead/less.js/images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(https://www.github.com/cloudhead/less.js/bg.jpg) no-repeat, url(https://www.github.com/cloudhead/less.js/bg.png) repeat-x top left, url(https://www.github.com/cloudhead/less.js/bg); +} +.values { + url: url('https://www.github.com/cloudhead/less.js/Trebuchet'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath/urls.css b/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath/urls.css new file mode 100644 index 000000000..9618e8e50 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/rootpath/urls.css @@ -0,0 +1,35 @@ +@import "https://www.github.com/modify-this.css"; +@import "https://www.github.com/modify-again.css"; +.modify { + my-url: url("https://www.github.com/a.png"); +} +.modify { + my-url: url("https://www.github.com/b.png"); +} +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(https://www.github.com/fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(https://www.github.com/images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(https://www.github.com/bg.jpg) no-repeat, url(https://www.github.com/bg.png) repeat-x top left, url(https://www.github.com/bg); +} +.values { + url: url('https://www.github.com/Trebuchet'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/css/urls.css b/node_modules/less-middleware/node_modules/less/test/browser/css/urls.css new file mode 100644 index 000000000..c15105127 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/css/urls.css @@ -0,0 +1,53 @@ +@import "http://localhost:8081/test/browser/less/modify-this.css"; +@import "http://localhost:8081/test/browser/less/modify-again.css"; +.modify { + my-url: url("http://localhost:8081/test/browser/less/a.png"); +} +.modify { + my-url: url("http://localhost:8081/test/browser/less/b.png"); +} +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(http://localhost:8081/test/browser/less/fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(http://localhost:8081/test/browser/less/images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(http://localhost:8081/test/browser/less/bg.jpg) no-repeat, url(http://localhost:8081/test/browser/less/bg.png) repeat-x top left, url(http://localhost:8081/test/browser/less/bg); +} +.values { + url: url('http://localhost:8081/test/browser/less/Trebuchet'); +} +#data-uri { + uri: url('http://localhost:8081/test/data/image.jpg'); +} +#data-uri-guess { + uri: url('http://localhost:8081/test/data/image.jpg'); +} +#data-uri-ascii { + uri-1: url('http://localhost:8081/test/data/page.html'); + uri-2: url('http://localhost:8081/test/data/page.html'); +} +#data-uri-toobig { + uri: url('http://localhost:8081/test/data/data-uri-fail.png'); +} +#svg-functions { + background-image: url('data:image/svg+xml,'); + background-image: url('data:image/svg+xml,'); + background-image: url('data:image/svg+xml,'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/es5.js b/node_modules/less-middleware/node_modules/less/test/browser/es5.js new file mode 100644 index 000000000..c4fcc8023 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/es5.js @@ -0,0 +1,27 @@ +/* + PhantomJS does not implement bind. this is from + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind + */ +if (!Function.prototype.bind) { + Function.prototype.bind = function (oThis) { + if (typeof this !== "function") { + // closest thing possible to the ECMAScript 5 internal IsCallable function + throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function () {}, + fBound = function () { + return fToBind.apply(this instanceof fNOP && oThis + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + fNOP.prototype = this.prototype; + fBound.prototype = new fNOP(); + + return fBound; + }; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/jasmine-html.js b/node_modules/less-middleware/node_modules/less/test/browser/jasmine-html.js new file mode 100644 index 000000000..543d56963 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/jasmine-html.js @@ -0,0 +1,681 @@ +jasmine.HtmlReporterHelpers = {}; + +jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { + var el = document.createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(document.createTextNode(child)); + } else { + if (child) { + el.appendChild(child); + } + } + } + + for (var attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; +}; + +jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { + var results = child.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.skipped) { + status = 'skipped'; + } + + return status; +}; + +jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { + var parentDiv = this.dom.summary; + var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; + var parent = child[parentSuite]; + + if (parent) { + if (typeof this.views.suites[parent.id] == 'undefined') { + this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); + } + parentDiv = this.views.suites[parent.id].element; + } + + parentDiv.appendChild(childElement); +}; + + +jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { + for(var fn in jasmine.HtmlReporterHelpers) { + ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; + } +}; + +jasmine.HtmlReporter = function(_doc) { + var self = this; + var doc = _doc || window.document; + + var reporterView; + + var dom = {}; + + // Jasmine Reporter Public Interface + self.logRunningSpecs = false; + + self.reportRunnerStarting = function(runner) { + var specs = runner.specs() || []; + + if (specs.length == 0) { + return; + } + + createReporterDom(runner.env.versionString()); + doc.body.appendChild(dom.reporter); + setExceptionHandling(); + + reporterView = new jasmine.HtmlReporter.ReporterView(dom); + reporterView.addSpecs(specs, self.specFilter); + }; + + self.reportRunnerResults = function(runner) { + reporterView && reporterView.complete(); + }; + + self.reportSuiteResults = function(suite) { + reporterView.suiteComplete(suite); + }; + + self.reportSpecStarting = function(spec) { + if (self.logRunningSpecs) { + self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + } + }; + + self.reportSpecResults = function(spec) { + reporterView.specComplete(spec); + }; + + self.log = function() { + var console = jasmine.getGlobal().console; + if (console && console.log) { + if (console.log.apply) { + console.log.apply(console, arguments); + } else { + console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + } + } + }; + + self.specFilter = function(spec) { + if (!focusedSpecName()) { + return true; + } + + return spec.getFullName().indexOf(focusedSpecName()) === 0; + }; + + return self; + + function focusedSpecName() { + var specName; + + (function memoizeFocusedSpec() { + if (specName) { + return; + } + + var paramMap = []; + var params = jasmine.HtmlReporter.parameters(doc); + + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + } + + specName = paramMap.spec; + })(); + + return specName; + } + + function createReporterDom(version) { + dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, + dom.banner = self.createDom('div', { className: 'banner' }, + self.createDom('span', { className: 'title' }, "Jasmine "), + self.createDom('span', { className: 'version' }, version)), + + dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), + dom.alert = self.createDom('div', {className: 'alert'}, + self.createDom('span', { className: 'exceptions' }, + self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'), + self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))), + dom.results = self.createDom('div', {className: 'results'}, + dom.summary = self.createDom('div', { className: 'summary' }), + dom.details = self.createDom('div', { id: 'details' })) + ); + } + + function noTryCatch() { + return window.location.search.match(/catch=false/); + } + + function searchWithCatch() { + var params = jasmine.HtmlReporter.parameters(window.document); + var removed = false; + var i = 0; + + while (!removed && i < params.length) { + if (params[i].match(/catch=/)) { + params.splice(i, 1); + removed = true; + } + i++; + } + if (jasmine.CATCH_EXCEPTIONS) { + params.push("catch=false"); + } + + return params.join("&"); + } + + function setExceptionHandling() { + var chxCatch = document.getElementById('no_try_catch'); + + if (noTryCatch()) { + chxCatch.setAttribute('checked', true); + jasmine.CATCH_EXCEPTIONS = false; + } + chxCatch.onclick = function() { + window.location.search = searchWithCatch(); + }; + } +}; +jasmine.HtmlReporter.parameters = function(doc) { + var paramStr = doc.location.search.substring(1); + var params = []; + + if (paramStr.length > 0) { + params = paramStr.split('&'); + } + return params; +} +jasmine.HtmlReporter.sectionLink = function(sectionName) { + var link = '?'; + var params = []; + + if (sectionName) { + params.push('spec=' + encodeURIComponent(sectionName)); + } + if (!jasmine.CATCH_EXCEPTIONS) { + params.push("catch=false"); + } + if (params.length > 0) { + link += params.join("&"); + } + + return link; +}; +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter); +jasmine.HtmlReporter.ReporterView = function(dom) { + this.startedAt = new Date(); + this.runningSpecCount = 0; + this.completeSpecCount = 0; + this.passedCount = 0; + this.failedCount = 0; + this.skippedCount = 0; + + this.createResultsMenu = function() { + this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, + this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), + ' | ', + this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); + + this.summaryMenuItem.onclick = function() { + dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); + }; + + this.detailsMenuItem.onclick = function() { + showDetails(); + }; + }; + + this.addSpecs = function(specs, specFilter) { + this.totalSpecCount = specs.length; + + this.views = { + specs: {}, + suites: {} + }; + + for (var i = 0; i < specs.length; i++) { + var spec = specs[i]; + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); + if (specFilter(spec)) { + this.runningSpecCount++; + } + } + }; + + this.specComplete = function(spec) { + this.completeSpecCount++; + + if (isUndefined(this.views.specs[spec.id])) { + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); + } + + var specView = this.views.specs[spec.id]; + + switch (specView.status()) { + case 'passed': + this.passedCount++; + break; + + case 'failed': + this.failedCount++; + break; + + case 'skipped': + this.skippedCount++; + break; + } + + specView.refresh(); + this.refresh(); + }; + + this.suiteComplete = function(suite) { + var suiteView = this.views.suites[suite.id]; + if (isUndefined(suiteView)) { + return; + } + suiteView.refresh(); + }; + + this.refresh = function() { + + if (isUndefined(this.resultsMenu)) { + this.createResultsMenu(); + } + + // currently running UI + if (isUndefined(this.runningAlert)) { + this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" }); + dom.alert.appendChild(this.runningAlert); + } + this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); + + // skipped specs UI + if (isUndefined(this.skippedAlert)) { + this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" }); + } + + this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + + if (this.skippedCount === 1 && isDefined(dom.alert)) { + dom.alert.appendChild(this.skippedAlert); + } + + // passing specs UI + if (isUndefined(this.passedAlert)) { + this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" }); + } + this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); + + // failing specs UI + if (isUndefined(this.failedAlert)) { + this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); + } + this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); + + if (this.failedCount === 1 && isDefined(dom.alert)) { + dom.alert.appendChild(this.failedAlert); + dom.alert.appendChild(this.resultsMenu); + } + + // summary info + this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); + this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; + }; + + this.complete = function() { + dom.alert.removeChild(this.runningAlert); + + this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + + if (this.failedCount === 0) { + dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); + } else { + showDetails(); + } + + dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); + }; + + return this; + + function showDetails() { + if (dom.reporter.className.search(/showDetails/) === -1) { + dom.reporter.className += " showDetails"; + } + } + + function isUndefined(obj) { + return typeof obj === 'undefined'; + } + + function isDefined(obj) { + return !isUndefined(obj); + } + + function specPluralizedFor(count) { + var str = count + " spec"; + if (count > 1) { + str += "s" + } + return str; + } + +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); + + +jasmine.HtmlReporter.SpecView = function(spec, dom, views) { + this.spec = spec; + this.dom = dom; + this.views = views; + + this.symbol = this.createDom('li', { className: 'pending' }); + this.dom.symbolSummary.appendChild(this.symbol); + + this.summary = this.createDom('div', { className: 'specSummary' }, + this.createDom('a', { + className: 'description', + href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()), + title: this.spec.getFullName() + }, this.spec.description) + ); + + this.detail = this.createDom('div', { className: 'specDetail' }, + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(this.spec.getFullName()), + title: this.spec.getFullName() + }, this.spec.getFullName()) + ); +}; + +jasmine.HtmlReporter.SpecView.prototype.status = function() { + return this.getSpecStatus(this.spec); +}; + +jasmine.HtmlReporter.SpecView.prototype.refresh = function() { + this.symbol.className = this.status(); + + switch (this.status()) { + case 'skipped': + break; + + case 'passed': + this.appendSummaryToSuiteDiv(); + break; + + case 'failed': + this.appendSummaryToSuiteDiv(); + this.appendFailureDetail(); + break; + } +}; + +jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { + this.summary.className += ' ' + this.status(); + this.appendToSummary(this.spec, this.summary); +}; + +jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { + this.detail.className += ' ' + this.status(); + + var resultItems = this.spec.results().getItems(); + var messagesDiv = this.createDom('div', { className: 'messages' }); + + for (var i = 0; i < resultItems.length; i++) { + var result = resultItems[i]; + + if (result.type == 'log') { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + } else if (result.type == 'expect' && result.passed && !result.passed()) { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + + if (result.trace.stack) { + messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + } + } + } + + if (messagesDiv.childNodes.length > 0) { + this.detail.appendChild(messagesDiv); + this.dom.details.appendChild(this.detail); + } +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { + this.suite = suite; + this.dom = dom; + this.views = views; + + this.element = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) + ); + + this.appendToSummary(this.suite, this.element); +}; + +jasmine.HtmlReporter.SuiteView.prototype.status = function() { + return this.getSpecStatus(this.suite); +}; + +jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { + this.element.className += " " + this.status(); +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); + +/* @deprecated Use jasmine.HtmlReporter instead + */ +jasmine.TrivialReporter = function(doc) { + this.document = doc || document; + this.suiteDivs = {}; + this.logRunningSpecs = false; +}; + +jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { + var el = document.createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(document.createTextNode(child)); + } else { + if (child) { el.appendChild(child); } + } + } + + for (var attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; +}; + +jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { + var showPassed, showSkipped; + + this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, + this.createDom('div', { className: 'banner' }, + this.createDom('div', { className: 'logo' }, + this.createDom('span', { className: 'title' }, "Jasmine"), + this.createDom('span', { className: 'version' }, runner.env.versionString())), + this.createDom('div', { className: 'options' }, + "Show ", + showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), + showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") + ) + ), + + this.runnerDiv = this.createDom('div', { className: 'runner running' }, + this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), + this.runnerMessageSpan = this.createDom('span', {}, "Running..."), + this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) + ); + + this.document.body.appendChild(this.outerDiv); + + var suites = runner.suites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + var suiteDiv = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), + this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); + this.suiteDivs[suite.id] = suiteDiv; + var parentDiv = this.outerDiv; + if (suite.parentSuite) { + parentDiv = this.suiteDivs[suite.parentSuite.id]; + } + parentDiv.appendChild(suiteDiv); + } + + this.startedAt = new Date(); + + var self = this; + showPassed.onclick = function(evt) { + if (showPassed.checked) { + self.outerDiv.className += ' show-passed'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); + } + }; + + showSkipped.onclick = function(evt) { + if (showSkipped.checked) { + self.outerDiv.className += ' show-skipped'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); + } + }; +}; + +jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { + var results = runner.results(); + var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; + this.runnerDiv.setAttribute("class", className); + //do it twice for IE + this.runnerDiv.setAttribute("className", className); + var specs = runner.specs(); + var specCount = 0; + for (var i = 0; i < specs.length; i++) { + if (this.specFilter(specs[i])) { + specCount++; + } + } + var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); + message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; + this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); + + this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); +}; + +jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { + var results = suite.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.totalCount === 0) { // todo: change this to check results.skipped + status = 'skipped'; + } + this.suiteDivs[suite.id].className += " " + status; +}; + +jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { + if (this.logRunningSpecs) { + this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + } +}; + +jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { + var results = spec.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.skipped) { + status = 'skipped'; + } + var specDiv = this.createDom('div', { className: 'spec ' + status }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(spec.getFullName()), + title: spec.getFullName() + }, spec.description)); + + + var resultItems = results.getItems(); + var messagesDiv = this.createDom('div', { className: 'messages' }); + for (var i = 0; i < resultItems.length; i++) { + var result = resultItems[i]; + + if (result.type == 'log') { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + } else if (result.type == 'expect' && result.passed && !result.passed()) { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + + if (result.trace.stack) { + messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + } + } + } + + if (messagesDiv.childNodes.length > 0) { + specDiv.appendChild(messagesDiv); + } + + this.suiteDivs[spec.suite.id].appendChild(specDiv); +}; + +jasmine.TrivialReporter.prototype.log = function() { + var console = jasmine.getGlobal().console; + if (console && console.log) { + if (console.log.apply) { + console.log.apply(console, arguments); + } else { + console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + } + } +}; + +jasmine.TrivialReporter.prototype.getLocation = function() { + return this.document.location; +}; + +jasmine.TrivialReporter.prototype.specFilter = function(spec) { + var paramMap = {}; + var params = this.getLocation().search.substring(1).split('&'); + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + } + + if (!paramMap.spec) { + return true; + } + return spec.getFullName().indexOf(paramMap.spec) === 0; +}; diff --git a/node_modules/less-middleware/node_modules/less/test/browser/jasmine.css b/node_modules/less-middleware/node_modules/less/test/browser/jasmine.css new file mode 100644 index 000000000..8c008dc72 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/jasmine.css @@ -0,0 +1,82 @@ +body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } + +#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } +#HTMLReporter a { text-decoration: none; } +#HTMLReporter a:hover { text-decoration: underline; } +#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } +#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } +#HTMLReporter #jasmine_content { position: fixed; right: 100%; } +#HTMLReporter .version { color: #aaaaaa; } +#HTMLReporter .banner { margin-top: 14px; } +#HTMLReporter .duration { color: #aaaaaa; float: right; } +#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } +#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } +#HTMLReporter .symbolSummary li.passed { font-size: 14px; } +#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } +#HTMLReporter .symbolSummary li.failed { line-height: 9px; } +#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } +#HTMLReporter .symbolSummary li.skipped { font-size: 14px; } +#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } +#HTMLReporter .symbolSummary li.pending { line-height: 11px; } +#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } +#HTMLReporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } +#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } +#HTMLReporter .runningAlert { background-color: #666666; } +#HTMLReporter .skippedAlert { background-color: #aaaaaa; } +#HTMLReporter .skippedAlert:first-child { background-color: #333333; } +#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } +#HTMLReporter .passingAlert { background-color: #a6b779; } +#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } +#HTMLReporter .failingAlert { background-color: #cf867e; } +#HTMLReporter .failingAlert:first-child { background-color: #b03911; } +#HTMLReporter .results { margin-top: 14px; } +#HTMLReporter #details { display: none; } +#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } +#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } +#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } +#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } +#HTMLReporter.showDetails .summary { display: none; } +#HTMLReporter.showDetails #details { display: block; } +#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } +#HTMLReporter .summary { margin-top: 14px; } +#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } +#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } +#HTMLReporter .summary .specSummary.failed a { color: #b03911; } +#HTMLReporter .description + .suite { margin-top: 0; } +#HTMLReporter .suite { margin-top: 14px; } +#HTMLReporter .suite a { color: #333333; } +#HTMLReporter #details .specDetail { margin-bottom: 28px; } +#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } +#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } +#HTMLReporter .resultMessage span.result { display: block; } +#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } + +#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } +#TrivialReporter a:visited, #TrivialReporter a { color: #303; } +#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } +#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } +#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } +#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } +#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } +#TrivialReporter .runner.running { background-color: yellow; } +#TrivialReporter .options { text-align: right; font-size: .8em; } +#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } +#TrivialReporter .suite .suite { margin: 5px; } +#TrivialReporter .suite.passed { background-color: #dfd; } +#TrivialReporter .suite.failed { background-color: #fdd; } +#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } +#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } +#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } +#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } +#TrivialReporter .spec.skipped { background-color: #bbb; } +#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } +#TrivialReporter .passed { background-color: #cfc; display: none; } +#TrivialReporter .failed { background-color: #fbb; } +#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } +#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } +#TrivialReporter .resultMessage .mismatch { color: black; } +#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } +#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } +#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } +#TrivialReporter #jasmine_content { position: fixed; right: 100%; } +#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } diff --git a/node_modules/less-middleware/node_modules/less/test/browser/jasmine.js b/node_modules/less-middleware/node_modules/less/test/browser/jasmine.js new file mode 100644 index 000000000..6b3459b91 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/jasmine.js @@ -0,0 +1,2600 @@ +var isCommonJS = typeof window == "undefined" && typeof exports == "object"; + +/** + * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. + * + * @namespace + */ +var jasmine = {}; +if (isCommonJS) exports.jasmine = jasmine; +/** + * @private + */ +jasmine.unimplementedMethod_ = function() { + throw new Error("unimplemented method"); +}; + +/** + * Use jasmine.undefined instead of undefined, since undefined is just + * a plain old variable and may be redefined by somebody else. + * + * @private + */ +jasmine.undefined = jasmine.___undefined___; + +/** + * Show diagnostic messages in the console if set to true + * + */ +jasmine.VERBOSE = false; + +/** + * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. + * + */ +jasmine.DEFAULT_UPDATE_INTERVAL = 250; + +/** + * Maximum levels of nesting that will be included when an object is pretty-printed + */ +jasmine.MAX_PRETTY_PRINT_DEPTH = 40; + +/** + * Default timeout interval in milliseconds for waitsFor() blocks. + */ +jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; + +/** + * By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite. + * Set to false to let the exception bubble up in the browser. + * + */ +jasmine.CATCH_EXCEPTIONS = true; + +jasmine.getGlobal = function() { + function getGlobal() { + return this; + } + + return getGlobal(); +}; + +/** + * Allows for bound functions to be compared. Internal use only. + * + * @ignore + * @private + * @param base {Object} bound 'this' for the function + * @param name {Function} function to find + */ +jasmine.bindOriginal_ = function(base, name) { + var original = base[name]; + if (original.apply) { + return function() { + return original.apply(base, arguments); + }; + } else { + // IE support + return jasmine.getGlobal()[name]; + } +}; + +jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); +jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); +jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); +jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); + +jasmine.MessageResult = function(values) { + this.type = 'log'; + this.values = values; + this.trace = new Error(); // todo: test better +}; + +jasmine.MessageResult.prototype.toString = function() { + var text = ""; + for (var i = 0; i < this.values.length; i++) { + if (i > 0) text += " "; + if (jasmine.isString_(this.values[i])) { + text += this.values[i]; + } else { + text += jasmine.pp(this.values[i]); + } + } + return text; +}; + +jasmine.ExpectationResult = function(params) { + this.type = 'expect'; + this.matcherName = params.matcherName; + this.passed_ = params.passed; + this.expected = params.expected; + this.actual = params.actual; + this.message = this.passed_ ? 'Passed.' : params.message; + + var trace = (params.trace || new Error(this.message)); + this.trace = this.passed_ ? '' : trace; +}; + +jasmine.ExpectationResult.prototype.toString = function () { + return this.message; +}; + +jasmine.ExpectationResult.prototype.passed = function () { + return this.passed_; +}; + +/** + * Getter for the Jasmine environment. Ensures one gets created + */ +jasmine.getEnv = function() { + var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); + return env; +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isArray_ = function(value) { + return jasmine.isA_("Array", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isString_ = function(value) { + return jasmine.isA_("String", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isNumber_ = function(value) { + return jasmine.isA_("Number", value); +}; + +/** + * @ignore + * @private + * @param {String} typeName + * @param value + * @returns {Boolean} + */ +jasmine.isA_ = function(typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; +}; + +/** + * Pretty printer for expecations. Takes any object and turns it into a human-readable string. + * + * @param value {Object} an object to be outputted + * @returns {String} + */ +jasmine.pp = function(value) { + var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); + stringPrettyPrinter.format(value); + return stringPrettyPrinter.string; +}; + +/** + * Returns true if the object is a DOM Node. + * + * @param {Object} obj object to check + * @returns {Boolean} + */ +jasmine.isDomNode = function(obj) { + return obj.nodeType > 0; +}; + +/** + * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. + * + * @example + * // don't care about which function is passed in, as long as it's a function + * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); + * + * @param {Class} clazz + * @returns matchable object of the type clazz + */ +jasmine.any = function(clazz) { + return new jasmine.Matchers.Any(clazz); +}; + +/** + * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the + * attributes on the object. + * + * @example + * // don't care about any other attributes than foo. + * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"}); + * + * @param sample {Object} sample + * @returns matchable object for the sample + */ +jasmine.objectContaining = function (sample) { + return new jasmine.Matchers.ObjectContaining(sample); +}; + +/** + * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. + * + * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine + * expectation syntax. Spies can be checked if they were called or not and what the calling params were. + * + * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). + * + * Spies are torn down at the end of every spec. + * + * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. + * + * @example + * // a stub + * var myStub = jasmine.createSpy('myStub'); // can be used anywhere + * + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // actual foo.not will not be called, execution stops + * spyOn(foo, 'not'); + + // foo.not spied upon, execution will continue to implementation + * spyOn(foo, 'not').andCallThrough(); + * + * // fake example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // foo.not(val) will return val + * spyOn(foo, 'not').andCallFake(function(value) {return value;}); + * + * // mock example + * foo.not(7 == 7); + * expect(foo.not).toHaveBeenCalled(); + * expect(foo.not).toHaveBeenCalledWith(true); + * + * @constructor + * @see spyOn, jasmine.createSpy, jasmine.createSpyObj + * @param {String} name + */ +jasmine.Spy = function(name) { + /** + * The name of the spy, if provided. + */ + this.identity = name || 'unknown'; + /** + * Is this Object a spy? + */ + this.isSpy = true; + /** + * The actual function this spy stubs. + */ + this.plan = function() { + }; + /** + * Tracking of the most recent call to the spy. + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy.mostRecentCall.args = [1, 2]; + */ + this.mostRecentCall = {}; + + /** + * Holds arguments for each call to the spy, indexed by call count + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy(7, 8); + * mySpy.mostRecentCall.args = [7, 8]; + * mySpy.argsForCall[0] = [1, 2]; + * mySpy.argsForCall[1] = [7, 8]; + */ + this.argsForCall = []; + this.calls = []; +}; + +/** + * Tells a spy to call through to the actual implemenatation. + * + * @example + * var foo = { + * bar: function() { // do some stuff } + * } + * + * // defining a spy on an existing property: foo.bar + * spyOn(foo, 'bar').andCallThrough(); + */ +jasmine.Spy.prototype.andCallThrough = function() { + this.plan = this.originalValue; + return this; +}; + +/** + * For setting the return value of a spy. + * + * @example + * // defining a spy from scratch: foo() returns 'baz' + * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); + * + * // defining a spy on an existing property: foo.bar() returns 'baz' + * spyOn(foo, 'bar').andReturn('baz'); + * + * @param {Object} value + */ +jasmine.Spy.prototype.andReturn = function(value) { + this.plan = function() { + return value; + }; + return this; +}; + +/** + * For throwing an exception when a spy is called. + * + * @example + * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' + * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); + * + * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' + * spyOn(foo, 'bar').andThrow('baz'); + * + * @param {String} exceptionMsg + */ +jasmine.Spy.prototype.andThrow = function(exceptionMsg) { + this.plan = function() { + throw exceptionMsg; + }; + return this; +}; + +/** + * Calls an alternate implementation when a spy is called. + * + * @example + * var baz = function() { + * // do some stuff, return something + * } + * // defining a spy from scratch: foo() calls the function baz + * var foo = jasmine.createSpy('spy on foo').andCall(baz); + * + * // defining a spy on an existing property: foo.bar() calls an anonymnous function + * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); + * + * @param {Function} fakeFunc + */ +jasmine.Spy.prototype.andCallFake = function(fakeFunc) { + this.plan = fakeFunc; + return this; +}; + +/** + * Resets all of a spy's the tracking variables so that it can be used again. + * + * @example + * spyOn(foo, 'bar'); + * + * foo.bar(); + * + * expect(foo.bar.callCount).toEqual(1); + * + * foo.bar.reset(); + * + * expect(foo.bar.callCount).toEqual(0); + */ +jasmine.Spy.prototype.reset = function() { + this.wasCalled = false; + this.callCount = 0; + this.argsForCall = []; + this.calls = []; + this.mostRecentCall = {}; +}; + +jasmine.createSpy = function(name) { + + var spyObj = function() { + spyObj.wasCalled = true; + spyObj.callCount++; + var args = jasmine.util.argsToArray(arguments); + spyObj.mostRecentCall.object = this; + spyObj.mostRecentCall.args = args; + spyObj.argsForCall.push(args); + spyObj.calls.push({object: this, args: args}); + return spyObj.plan.apply(this, arguments); + }; + + var spy = new jasmine.Spy(name); + + for (var prop in spy) { + spyObj[prop] = spy[prop]; + } + + spyObj.reset(); + + return spyObj; +}; + +/** + * Determines whether an object is a spy. + * + * @param {jasmine.Spy|Object} putativeSpy + * @returns {Boolean} + */ +jasmine.isSpy = function(putativeSpy) { + return putativeSpy && putativeSpy.isSpy; +}; + +/** + * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something + * large in one call. + * + * @param {String} baseName name of spy class + * @param {Array} methodNames array of names of methods to make spies + */ +jasmine.createSpyObj = function(baseName, methodNames) { + if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { + throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); + } + var obj = {}; + for (var i = 0; i < methodNames.length; i++) { + obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); + } + return obj; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the current spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.log = function() { + var spec = jasmine.getEnv().currentSpec; + spec.log.apply(spec, arguments); +}; + +/** + * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. + * + * @example + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops + * + * @see jasmine.createSpy + * @param obj + * @param methodName + * @return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods + */ +var spyOn = function(obj, methodName) { + return jasmine.getEnv().currentSpec.spyOn(obj, methodName); +}; +if (isCommonJS) exports.spyOn = spyOn; + +/** + * Creates a Jasmine spec that will be added to the current suite. + * + * // TODO: pending tests + * + * @example + * it('should be true', function() { + * expect(true).toEqual(true); + * }); + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var it = function(desc, func) { + return jasmine.getEnv().it(desc, func); +}; +if (isCommonJS) exports.it = it; + +/** + * Creates a disabled Jasmine spec. + * + * A convenience method that allows existing specs to be disabled temporarily during development. + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var xit = function(desc, func) { + return jasmine.getEnv().xit(desc, func); +}; +if (isCommonJS) exports.xit = xit; + +/** + * Starts a chain for a Jasmine expectation. + * + * It is passed an Object that is the actual value and should chain to one of the many + * jasmine.Matchers functions. + * + * @param {Object} actual Actual value to test against and expected value + * @return {jasmine.Matchers} + */ +var expect = function(actual) { + return jasmine.getEnv().currentSpec.expect(actual); +}; +if (isCommonJS) exports.expect = expect; + +/** + * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. + * + * @param {Function} func Function that defines part of a jasmine spec. + */ +var runs = function(func) { + jasmine.getEnv().currentSpec.runs(func); +}; +if (isCommonJS) exports.runs = runs; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +var waits = function(timeout) { + jasmine.getEnv().currentSpec.waits(timeout); +}; +if (isCommonJS) exports.waits = waits; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); +}; +if (isCommonJS) exports.waitsFor = waitsFor; + +/** + * A function that is called before each spec in a suite. + * + * Used for spec setup, including validating assumptions. + * + * @param {Function} beforeEachFunction + */ +var beforeEach = function(beforeEachFunction) { + jasmine.getEnv().beforeEach(beforeEachFunction); +}; +if (isCommonJS) exports.beforeEach = beforeEach; + +/** + * A function that is called after each spec in a suite. + * + * Used for restoring any state that is hijacked during spec execution. + * + * @param {Function} afterEachFunction + */ +var afterEach = function(afterEachFunction) { + jasmine.getEnv().afterEach(afterEachFunction); +}; +if (isCommonJS) exports.afterEach = afterEach; + +/** + * Defines a suite of specifications. + * + * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared + * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization + * of setup in some tests. + * + * @example + * // TODO: a simple suite + * + * // TODO: a simple suite with a nested describe block + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var describe = function(description, specDefinitions) { + return jasmine.getEnv().describe(description, specDefinitions); +}; +if (isCommonJS) exports.describe = describe; + +/** + * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var xdescribe = function(description, specDefinitions) { + return jasmine.getEnv().xdescribe(description, specDefinitions); +}; +if (isCommonJS) exports.xdescribe = xdescribe; + + +// Provide the XMLHttpRequest class for IE 5.x-6.x: +jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { + function tryIt(f) { + try { + return f(); + } catch(e) { + } + return null; + } + + var xhr = tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP.6.0"); + }) || + tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP.3.0"); + }) || + tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP"); + }) || + tryIt(function() { + return new ActiveXObject("Microsoft.XMLHTTP"); + }); + + if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); + + return xhr; +} : XMLHttpRequest; +/** + * @namespace + */ +jasmine.util = {}; + +/** + * Declare that a child class inherit it's prototype from the parent class. + * + * @private + * @param {Function} childClass + * @param {Function} parentClass + */ +jasmine.util.inherit = function(childClass, parentClass) { + /** + * @private + */ + var subclass = function() { + }; + subclass.prototype = parentClass.prototype; + childClass.prototype = new subclass(); +}; + +jasmine.util.formatException = function(e) { + var lineNumber; + if (e.line) { + lineNumber = e.line; + } + else if (e.lineNumber) { + lineNumber = e.lineNumber; + } + + var file; + + if (e.sourceURL) { + file = e.sourceURL; + } + else if (e.fileName) { + file = e.fileName; + } + + var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); + + if (file && lineNumber) { + message += ' in ' + file + ' (line ' + lineNumber + ')'; + } + + return message; +}; + +jasmine.util.htmlEscape = function(str) { + if (!str) return str; + return str.replace(/&/g, '&') + .replace(//g, '>'); +}; + +jasmine.util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); + return arrayOfArgs; +}; + +jasmine.util.extend = function(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; +}; + +/** + * Environment for Jasmine + * + * @constructor + */ +jasmine.Env = function() { + this.currentSpec = null; + this.currentSuite = null; + this.currentRunner_ = new jasmine.Runner(this); + + this.reporter = new jasmine.MultiReporter(); + + this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; + this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; + this.lastUpdate = 0; + this.specFilter = function() { + return true; + }; + + this.nextSpecId_ = 0; + this.nextSuiteId_ = 0; + this.equalityTesters_ = []; + + // wrap matchers + this.matchersClass = function() { + jasmine.Matchers.apply(this, arguments); + }; + jasmine.util.inherit(this.matchersClass, jasmine.Matchers); + + jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); +}; + + +jasmine.Env.prototype.setTimeout = jasmine.setTimeout; +jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; +jasmine.Env.prototype.setInterval = jasmine.setInterval; +jasmine.Env.prototype.clearInterval = jasmine.clearInterval; + +/** + * @returns an object containing jasmine version build info, if set. + */ +jasmine.Env.prototype.version = function () { + if (jasmine.version_) { + return jasmine.version_; + } else { + throw new Error('Version not set'); + } +}; + +/** + * @returns string containing jasmine version build info, if set. + */ +jasmine.Env.prototype.versionString = function() { + if (!jasmine.version_) { + return "version unknown"; + } + + var version = this.version(); + var versionString = version.major + "." + version.minor + "." + version.build; + if (version.release_candidate) { + versionString += ".rc" + version.release_candidate; + } + versionString += " revision " + version.revision; + return versionString; +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSpecId = function () { + return this.nextSpecId_++; +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSuiteId = function () { + return this.nextSuiteId_++; +}; + +/** + * Register a reporter to receive status updates from Jasmine. + * @param {jasmine.Reporter} reporter An object which will receive status updates. + */ +jasmine.Env.prototype.addReporter = function(reporter) { + this.reporter.addReporter(reporter); +}; + +jasmine.Env.prototype.execute = function() { + this.currentRunner_.execute(); +}; + +jasmine.Env.prototype.describe = function(description, specDefinitions) { + var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); + + var parentSuite = this.currentSuite; + if (parentSuite) { + parentSuite.add(suite); + } else { + this.currentRunner_.add(suite); + } + + this.currentSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch(e) { + declarationError = e; + } + + if (declarationError) { + this.it("encountered a declaration exception", function() { + throw declarationError; + }); + } + + this.currentSuite = parentSuite; + + return suite; +}; + +jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { + if (this.currentSuite) { + this.currentSuite.beforeEach(beforeEachFunction); + } else { + this.currentRunner_.beforeEach(beforeEachFunction); + } +}; + +jasmine.Env.prototype.currentRunner = function () { + return this.currentRunner_; +}; + +jasmine.Env.prototype.afterEach = function(afterEachFunction) { + if (this.currentSuite) { + this.currentSuite.afterEach(afterEachFunction); + } else { + this.currentRunner_.afterEach(afterEachFunction); + } + +}; + +jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { + return { + execute: function() { + } + }; +}; + +jasmine.Env.prototype.it = function(description, func) { + var spec = new jasmine.Spec(this, this.currentSuite, description); + this.currentSuite.add(spec); + this.currentSpec = spec; + + if (func) { + spec.runs(func); + } + + return spec; +}; + +jasmine.Env.prototype.xit = function(desc, func) { + return { + id: this.nextSpecId(), + runs: function() { + } + }; +}; + +jasmine.Env.prototype.compareRegExps_ = function(a, b, mismatchKeys, mismatchValues) { + if (a.source != b.source) + mismatchValues.push("expected pattern /" + b.source + "/ is not equal to the pattern /" + a.source + "/"); + + if (a.ignoreCase != b.ignoreCase) + mismatchValues.push("expected modifier i was" + (b.ignoreCase ? " " : " not ") + "set and does not equal the origin modifier"); + + if (a.global != b.global) + mismatchValues.push("expected modifier g was" + (b.global ? " " : " not ") + "set and does not equal the origin modifier"); + + if (a.multiline != b.multiline) + mismatchValues.push("expected modifier m was" + (b.multiline ? " " : " not ") + "set and does not equal the origin modifier"); + + if (a.sticky != b.sticky) + mismatchValues.push("expected modifier y was" + (b.sticky ? " " : " not ") + "set and does not equal the origin modifier"); + + return (mismatchValues.length === 0); +}; + +jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { + if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { + return true; + } + + a.__Jasmine_been_here_before__ = b; + b.__Jasmine_been_here_before__ = a; + + var hasKey = function(obj, keyName) { + return obj !== null && obj[keyName] !== jasmine.undefined; + }; + + for (var property in b) { + if (!hasKey(a, property) && hasKey(b, property)) { + mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + } + } + for (property in a) { + if (!hasKey(b, property) && hasKey(a, property)) { + mismatchKeys.push("expected missing key '" + property + "', but present in actual."); + } + } + for (property in b) { + if (property == '__Jasmine_been_here_before__') continue; + if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); + } + } + + if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { + mismatchValues.push("arrays were not the same length"); + } + + delete a.__Jasmine_been_here_before__; + delete b.__Jasmine_been_here_before__; + return (mismatchKeys.length === 0 && mismatchValues.length === 0); +}; + +jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + for (var i = 0; i < this.equalityTesters_.length; i++) { + var equalityTester = this.equalityTesters_[i]; + var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); + if (result !== jasmine.undefined) return result; + } + + if (a === b) return true; + + if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { + return (a == jasmine.undefined && b == jasmine.undefined); + } + + if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { + return a === b; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() == b.getTime(); + } + + if (a.jasmineMatches) { + return a.jasmineMatches(b); + } + + if (b.jasmineMatches) { + return b.jasmineMatches(a); + } + + if (a instanceof jasmine.Matchers.ObjectContaining) { + return a.matches(b); + } + + if (b instanceof jasmine.Matchers.ObjectContaining) { + return b.matches(a); + } + + if (jasmine.isString_(a) && jasmine.isString_(b)) { + return (a == b); + } + + if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { + return (a == b); + } + + if (a instanceof RegExp && b instanceof RegExp) { + return this.compareRegExps_(a, b, mismatchKeys, mismatchValues); + } + + if (typeof a === "object" && typeof b === "object") { + return this.compareObjects_(a, b, mismatchKeys, mismatchValues); + } + + //Straight check + return (a === b); +}; + +jasmine.Env.prototype.contains_ = function(haystack, needle) { + if (jasmine.isArray_(haystack)) { + for (var i = 0; i < haystack.length; i++) { + if (this.equals_(haystack[i], needle)) return true; + } + return false; + } + return haystack.indexOf(needle) >= 0; +}; + +jasmine.Env.prototype.addEqualityTester = function(equalityTester) { + this.equalityTesters_.push(equalityTester); +}; +/** No-op base class for Jasmine reporters. + * + * @constructor + */ +jasmine.Reporter = function() { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerResults = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecStarting = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecResults = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.log = function(str) { +}; + +/** + * Blocks are functions with executable code that make up a spec. + * + * @constructor + * @param {jasmine.Env} env + * @param {Function} func + * @param {jasmine.Spec} spec + */ +jasmine.Block = function(env, func, spec) { + this.env = env; + this.func = func; + this.spec = spec; +}; + +jasmine.Block.prototype.execute = function(onComplete) { + if (!jasmine.CATCH_EXCEPTIONS) { + this.func.apply(this.spec); + } + else { + try { + this.func.apply(this.spec); + } catch (e) { + this.spec.fail(e); + } + } + onComplete(); +}; +/** JavaScript API reporter. + * + * @constructor + */ +jasmine.JsApiReporter = function() { + this.started = false; + this.finished = false; + this.suites_ = []; + this.results_ = {}; +}; + +jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { + this.started = true; + var suites = runner.topLevelSuites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + this.suites_.push(this.summarize_(suite)); + } +}; + +jasmine.JsApiReporter.prototype.suites = function() { + return this.suites_; +}; + +jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { + var isSuite = suiteOrSpec instanceof jasmine.Suite; + var summary = { + id: suiteOrSpec.id, + name: suiteOrSpec.description, + type: isSuite ? 'suite' : 'spec', + children: [] + }; + + if (isSuite) { + var children = suiteOrSpec.children(); + for (var i = 0; i < children.length; i++) { + summary.children.push(this.summarize_(children[i])); + } + } + return summary; +}; + +jasmine.JsApiReporter.prototype.results = function() { + return this.results_; +}; + +jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { + return this.results_[specId]; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { + this.finished = true; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { + this.results_[spec.id] = { + messages: spec.results().getItems(), + result: spec.results().failedCount > 0 ? "failed" : "passed" + }; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.log = function(str) { +}; + +jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ + var results = {}; + for (var i = 0; i < specIds.length; i++) { + var specId = specIds[i]; + results[specId] = this.summarizeResult_(this.results_[specId]); + } + return results; +}; + +jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ + var summaryMessages = []; + var messagesLength = result.messages.length; + for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { + var resultMessage = result.messages[messageIndex]; + summaryMessages.push({ + text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, + passed: resultMessage.passed ? resultMessage.passed() : true, + type: resultMessage.type, + message: resultMessage.message, + trace: { + stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined + } + }); + } + + return { + result : result.result, + messages : summaryMessages + }; +}; + +/** + * @constructor + * @param {jasmine.Env} env + * @param actual + * @param {jasmine.Spec} spec + */ +jasmine.Matchers = function(env, actual, spec, opt_isNot) { + this.env = env; + this.actual = actual; + this.spec = spec; + this.isNot = opt_isNot || false; + this.reportWasCalled_ = false; +}; + +// todo: @deprecated as of Jasmine 0.11, remove soon [xw] +jasmine.Matchers.pp = function(str) { + throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); +}; + +// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] +jasmine.Matchers.prototype.report = function(result, failing_message, details) { + throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); +}; + +jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { + for (var methodName in prototype) { + if (methodName == 'report') continue; + var orig = prototype[methodName]; + matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); + } +}; + +jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { + return function() { + var matcherArgs = jasmine.util.argsToArray(arguments); + var result = matcherFunction.apply(this, arguments); + + if (this.isNot) { + result = !result; + } + + if (this.reportWasCalled_) return result; + + var message; + if (!result) { + if (this.message) { + message = this.message.apply(this, arguments); + if (jasmine.isArray_(message)) { + message = message[this.isNot ? 1 : 0]; + } + } else { + var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); + message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; + if (matcherArgs.length > 0) { + for (var i = 0; i < matcherArgs.length; i++) { + if (i > 0) message += ","; + message += " " + jasmine.pp(matcherArgs[i]); + } + } + message += "."; + } + } + var expectationResult = new jasmine.ExpectationResult({ + matcherName: matcherName, + passed: result, + expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], + actual: this.actual, + message: message + }); + this.spec.addMatcherResult(expectationResult); + return jasmine.undefined; + }; +}; + + + + +/** + * toBe: compares the actual to the expected using === + * @param expected + */ +jasmine.Matchers.prototype.toBe = function(expected) { + return this.actual === expected; +}; + +/** + * toNotBe: compares the actual to the expected using !== + * @param expected + * @deprecated as of 1.0. Use not.toBe() instead. + */ +jasmine.Matchers.prototype.toNotBe = function(expected) { + return this.actual !== expected; +}; + +/** + * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. + * + * @param expected + */ +jasmine.Matchers.prototype.toEqual = function(expected) { + return this.env.equals_(this.actual, expected); +}; + +/** + * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual + * @param expected + * @deprecated as of 1.0. Use not.toEqual() instead. + */ +jasmine.Matchers.prototype.toNotEqual = function(expected) { + return !this.env.equals_(this.actual, expected); +}; + +/** + * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes + * a pattern or a String. + * + * @param expected + */ +jasmine.Matchers.prototype.toMatch = function(expected) { + return new RegExp(expected).test(this.actual); +}; + +/** + * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch + * @param expected + * @deprecated as of 1.0. Use not.toMatch() instead. + */ +jasmine.Matchers.prototype.toNotMatch = function(expected) { + return !(new RegExp(expected).test(this.actual)); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeDefined = function() { + return (this.actual !== jasmine.undefined); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeUndefined = function() { + return (this.actual === jasmine.undefined); +}; + +/** + * Matcher that compares the actual to null. + */ +jasmine.Matchers.prototype.toBeNull = function() { + return (this.actual === null); +}; + +/** + * Matcher that compares the actual to NaN. + */ +jasmine.Matchers.prototype.toBeNaN = function() { + this.message = function() { + return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ]; + }; + + return (this.actual !== this.actual); +}; + +/** + * Matcher that boolean not-nots the actual. + */ +jasmine.Matchers.prototype.toBeTruthy = function() { + return !!this.actual; +}; + + +/** + * Matcher that boolean nots the actual. + */ +jasmine.Matchers.prototype.toBeFalsy = function() { + return !this.actual; +}; + + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called. + */ +jasmine.Matchers.prototype.toHaveBeenCalled = function() { + if (arguments.length > 0) { + throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to have been called.", + "Expected spy " + this.actual.identity + " not to have been called." + ]; + }; + + return this.actual.wasCalled; +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ +jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was not called. + * + * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead + */ +jasmine.Matchers.prototype.wasNotCalled = function() { + if (arguments.length > 0) { + throw new Error('wasNotCalled does not take arguments'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to not have been called.", + "Expected spy " + this.actual.identity + " to have been called." + ]; + }; + + return !this.actual.wasCalled; +}; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. + * + * @example + * + */ +jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + this.message = function() { + var invertedMessage = "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."; + var positiveMessage = ""; + if (this.actual.callCount === 0) { + positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called."; + } else { + positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but actual calls were " + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '') + } + return [positiveMessage, invertedMessage]; + }; + + return this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; + +/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasNotCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", + "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" + ]; + }; + + return !this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** + * Matcher that checks that the expected item is an element in the actual Array. + * + * @param {Object} expected + */ +jasmine.Matchers.prototype.toContain = function(expected) { + return this.env.contains_(this.actual, expected); +}; + +/** + * Matcher that checks that the expected item is NOT an element in the actual Array. + * + * @param {Object} expected + * @deprecated as of 1.0. Use not.toContain() instead. + */ +jasmine.Matchers.prototype.toNotContain = function(expected) { + return !this.env.contains_(this.actual, expected); +}; + +jasmine.Matchers.prototype.toBeLessThan = function(expected) { + return this.actual < expected; +}; + +jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { + return this.actual > expected; +}; + +/** + * Matcher that checks that the expected item is equal to the actual item + * up to a given level of decimal precision (default 2). + * + * @param {Number} expected + * @param {Number} precision, as number of decimal places + */ +jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { + if (!(precision === 0)) { + precision = precision || 2; + } + return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2); +}; + +/** + * Matcher that checks that the expected exception was thrown by the actual. + * + * @param {String} [expected] + */ +jasmine.Matchers.prototype.toThrow = function(expected) { + var result = false; + var exception; + if (typeof this.actual != 'function') { + throw new Error('Actual is not a function'); + } + try { + this.actual(); + } catch (e) { + exception = e; + } + if (exception) { + result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); + } + + var not = this.isNot ? "not " : ""; + + this.message = function() { + if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { + return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); + } else { + return "Expected function to throw an exception."; + } + }; + + return result; +}; + +jasmine.Matchers.Any = function(expectedClass) { + this.expectedClass = expectedClass; +}; + +jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { + if (this.expectedClass == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedClass == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedClass == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedClass == Object) { + return typeof other == 'object'; + } + + return other instanceof this.expectedClass; +}; + +jasmine.Matchers.Any.prototype.jasmineToString = function() { + return ''; +}; + +jasmine.Matchers.ObjectContaining = function (sample) { + this.sample = sample; +}; + +jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + var env = jasmine.getEnv(); + + var hasKey = function(obj, keyName) { + return obj != null && obj[keyName] !== jasmine.undefined; + }; + + for (var property in this.sample) { + if (!hasKey(other, property) && hasKey(this.sample, property)) { + mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + } + else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); + } + } + + return (mismatchKeys.length === 0 && mismatchValues.length === 0); +}; + +jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { + return ""; +}; +// Mock setTimeout, clearTimeout +// Contributed by Pivotal Computer Systems, www.pivotalsf.com + +jasmine.FakeTimer = function() { + this.reset(); + + var self = this; + self.setTimeout = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); + return self.timeoutsMade; + }; + + self.setInterval = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); + return self.timeoutsMade; + }; + + self.clearTimeout = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + + self.clearInterval = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + +}; + +jasmine.FakeTimer.prototype.reset = function() { + this.timeoutsMade = 0; + this.scheduledFunctions = {}; + this.nowMillis = 0; +}; + +jasmine.FakeTimer.prototype.tick = function(millis) { + var oldMillis = this.nowMillis; + var newMillis = oldMillis + millis; + this.runFunctionsWithinRange(oldMillis, newMillis); + this.nowMillis = newMillis; +}; + +jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { + var scheduledFunc; + var funcsToRun = []; + for (var timeoutKey in this.scheduledFunctions) { + scheduledFunc = this.scheduledFunctions[timeoutKey]; + if (scheduledFunc != jasmine.undefined && + scheduledFunc.runAtMillis >= oldMillis && + scheduledFunc.runAtMillis <= nowMillis) { + funcsToRun.push(scheduledFunc); + this.scheduledFunctions[timeoutKey] = jasmine.undefined; + } + } + + if (funcsToRun.length > 0) { + funcsToRun.sort(function(a, b) { + return a.runAtMillis - b.runAtMillis; + }); + for (var i = 0; i < funcsToRun.length; ++i) { + try { + var funcToRun = funcsToRun[i]; + this.nowMillis = funcToRun.runAtMillis; + funcToRun.funcToCall(); + if (funcToRun.recurring) { + this.scheduleFunction(funcToRun.timeoutKey, + funcToRun.funcToCall, + funcToRun.millis, + true); + } + } catch(e) { + } + } + this.runFunctionsWithinRange(oldMillis, nowMillis); + } +}; + +jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { + this.scheduledFunctions[timeoutKey] = { + runAtMillis: this.nowMillis + millis, + funcToCall: funcToCall, + recurring: recurring, + timeoutKey: timeoutKey, + millis: millis + }; +}; + +/** + * @namespace + */ +jasmine.Clock = { + defaultFakeTimer: new jasmine.FakeTimer(), + + reset: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.reset(); + }, + + tick: function(millis) { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.tick(millis); + }, + + runFunctionsWithinRange: function(oldMillis, nowMillis) { + jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); + }, + + scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { + jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); + }, + + useMock: function() { + if (!jasmine.Clock.isInstalled()) { + var spec = jasmine.getEnv().currentSpec; + spec.after(jasmine.Clock.uninstallMock); + + jasmine.Clock.installMock(); + } + }, + + installMock: function() { + jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; + }, + + uninstallMock: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.installed = jasmine.Clock.real; + }, + + real: { + setTimeout: jasmine.getGlobal().setTimeout, + clearTimeout: jasmine.getGlobal().clearTimeout, + setInterval: jasmine.getGlobal().setInterval, + clearInterval: jasmine.getGlobal().clearInterval + }, + + assertInstalled: function() { + if (!jasmine.Clock.isInstalled()) { + throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); + } + }, + + isInstalled: function() { + return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; + }, + + installed: null +}; +jasmine.Clock.installed = jasmine.Clock.real; + +//else for IE support +jasmine.getGlobal().setTimeout = function(funcToCall, millis) { + if (jasmine.Clock.installed.setTimeout.apply) { + return jasmine.Clock.installed.setTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.setTimeout(funcToCall, millis); + } +}; + +jasmine.getGlobal().setInterval = function(funcToCall, millis) { + if (jasmine.Clock.installed.setInterval.apply) { + return jasmine.Clock.installed.setInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.setInterval(funcToCall, millis); + } +}; + +jasmine.getGlobal().clearTimeout = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearTimeout(timeoutKey); + } +}; + +jasmine.getGlobal().clearInterval = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearInterval(timeoutKey); + } +}; + +/** + * @constructor + */ +jasmine.MultiReporter = function() { + this.subReporters_ = []; +}; +jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); + +jasmine.MultiReporter.prototype.addReporter = function(reporter) { + this.subReporters_.push(reporter); +}; + +(function() { + var functionNames = [ + "reportRunnerStarting", + "reportRunnerResults", + "reportSuiteResults", + "reportSpecStarting", + "reportSpecResults", + "log" + ]; + for (var i = 0; i < functionNames.length; i++) { + var functionName = functionNames[i]; + jasmine.MultiReporter.prototype[functionName] = (function(functionName) { + return function() { + for (var j = 0; j < this.subReporters_.length; j++) { + var subReporter = this.subReporters_[j]; + if (subReporter[functionName]) { + subReporter[functionName].apply(subReporter, arguments); + } + } + }; + })(functionName); + } +})(); +/** + * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults + * + * @constructor + */ +jasmine.NestedResults = function() { + /** + * The total count of results + */ + this.totalCount = 0; + /** + * Number of passed results + */ + this.passedCount = 0; + /** + * Number of failed results + */ + this.failedCount = 0; + /** + * Was this suite/spec skipped? + */ + this.skipped = false; + /** + * @ignore + */ + this.items_ = []; +}; + +/** + * Roll up the result counts. + * + * @param result + */ +jasmine.NestedResults.prototype.rollupCounts = function(result) { + this.totalCount += result.totalCount; + this.passedCount += result.passedCount; + this.failedCount += result.failedCount; +}; + +/** + * Adds a log message. + * @param values Array of message parts which will be concatenated later. + */ +jasmine.NestedResults.prototype.log = function(values) { + this.items_.push(new jasmine.MessageResult(values)); +}; + +/** + * Getter for the results: message & results. + */ +jasmine.NestedResults.prototype.getItems = function() { + return this.items_; +}; + +/** + * Adds a result, tracking counts (total, passed, & failed) + * @param {jasmine.ExpectationResult|jasmine.NestedResults} result + */ +jasmine.NestedResults.prototype.addResult = function(result) { + if (result.type != 'log') { + if (result.items_) { + this.rollupCounts(result); + } else { + this.totalCount++; + if (result.passed()) { + this.passedCount++; + } else { + this.failedCount++; + } + } + } + this.items_.push(result); +}; + +/** + * @returns {Boolean} True if everything below passed + */ +jasmine.NestedResults.prototype.passed = function() { + return this.passedCount === this.totalCount; +}; +/** + * Base class for pretty printing for expectation results. + */ +jasmine.PrettyPrinter = function() { + this.ppNestLevel_ = 0; +}; + +/** + * Formats a value in a nice, human-readable string. + * + * @param value + */ +jasmine.PrettyPrinter.prototype.format = function(value) { + this.ppNestLevel_++; + try { + if (value === jasmine.undefined) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === jasmine.getGlobal()) { + this.emitScalar(''); + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString()); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (jasmine.isSpy(value)) { + this.emitScalar("spy on " + value.identity); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (typeof value.nodeType === 'number') { + this.emitScalar('HTMLNode'); + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (value.__Jasmine_been_here_before__) { + this.emitScalar(''); + } else if (jasmine.isArray_(value) || typeof value == 'object') { + value.__Jasmine_been_here_before__ = true; + if (jasmine.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + delete value.__Jasmine_been_here_before__; + } else { + this.emitScalar(value.toString()); + } + } finally { + this.ppNestLevel_--; + } +}; + +jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { + for (var property in obj) { + if (!obj.hasOwnProperty(property)) continue; + if (property == '__Jasmine_been_here_before__') continue; + fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && + obj.__lookupGetter__(property) !== null) : false); + } +}; + +jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; + +jasmine.StringPrettyPrinter = function() { + jasmine.PrettyPrinter.call(this); + + this.string = ''; +}; +jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); + +jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { + this.append(value); +}; + +jasmine.StringPrettyPrinter.prototype.emitString = function(value) { + this.append("'" + value + "'"); +}; + +jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { + if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { + this.append("Array"); + return; + } + + this.append('[ '); + for (var i = 0; i < array.length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + this.append(' ]'); +}; + +jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { + if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { + this.append("Object"); + return; + } + + var self = this; + this.append('{ '); + var first = true; + + this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.append(property); + self.append(' : '); + if (isGetter) { + self.append(''); + } else { + self.format(obj[property]); + } + }); + + this.append(' }'); +}; + +jasmine.StringPrettyPrinter.prototype.append = function(value) { + this.string += value; +}; +jasmine.Queue = function(env) { + this.env = env; + + // parallel to blocks. each true value in this array means the block will + // get executed even if we abort + this.ensured = []; + this.blocks = []; + this.running = false; + this.index = 0; + this.offset = 0; + this.abort = false; +}; + +jasmine.Queue.prototype.addBefore = function(block, ensure) { + if (ensure === jasmine.undefined) { + ensure = false; + } + + this.blocks.unshift(block); + this.ensured.unshift(ensure); +}; + +jasmine.Queue.prototype.add = function(block, ensure) { + if (ensure === jasmine.undefined) { + ensure = false; + } + + this.blocks.push(block); + this.ensured.push(ensure); +}; + +jasmine.Queue.prototype.insertNext = function(block, ensure) { + if (ensure === jasmine.undefined) { + ensure = false; + } + + this.ensured.splice((this.index + this.offset + 1), 0, ensure); + this.blocks.splice((this.index + this.offset + 1), 0, block); + this.offset++; +}; + +jasmine.Queue.prototype.start = function(onComplete) { + this.running = true; + this.onComplete = onComplete; + this.next_(); +}; + +jasmine.Queue.prototype.isRunning = function() { + return this.running; +}; + +jasmine.Queue.LOOP_DONT_RECURSE = true; + +jasmine.Queue.prototype.next_ = function() { + var self = this; + var goAgain = true; + + while (goAgain) { + goAgain = false; + + if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) { + var calledSynchronously = true; + var completedSynchronously = false; + + var onComplete = function () { + if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { + completedSynchronously = true; + return; + } + + if (self.blocks[self.index].abort) { + self.abort = true; + } + + self.offset = 0; + self.index++; + + var now = new Date().getTime(); + if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { + self.env.lastUpdate = now; + self.env.setTimeout(function() { + self.next_(); + }, 0); + } else { + if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { + goAgain = true; + } else { + self.next_(); + } + } + }; + self.blocks[self.index].execute(onComplete); + + calledSynchronously = false; + if (completedSynchronously) { + onComplete(); + } + + } else { + self.running = false; + if (self.onComplete) { + self.onComplete(); + } + } + } +}; + +jasmine.Queue.prototype.results = function() { + var results = new jasmine.NestedResults(); + for (var i = 0; i < this.blocks.length; i++) { + if (this.blocks[i].results) { + results.addResult(this.blocks[i].results()); + } + } + return results; +}; + + +/** + * Runner + * + * @constructor + * @param {jasmine.Env} env + */ +jasmine.Runner = function(env) { + var self = this; + self.env = env; + self.queue = new jasmine.Queue(env); + self.before_ = []; + self.after_ = []; + self.suites_ = []; +}; + +jasmine.Runner.prototype.execute = function() { + var self = this; + if (self.env.reporter.reportRunnerStarting) { + self.env.reporter.reportRunnerStarting(this); + } + self.queue.start(function () { + self.finishCallback(); + }); +}; + +jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.splice(0,0,beforeEachFunction); +}; + +jasmine.Runner.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.splice(0,0,afterEachFunction); +}; + + +jasmine.Runner.prototype.finishCallback = function() { + this.env.reporter.reportRunnerResults(this); +}; + +jasmine.Runner.prototype.addSuite = function(suite) { + this.suites_.push(suite); +}; + +jasmine.Runner.prototype.add = function(block) { + if (block instanceof jasmine.Suite) { + this.addSuite(block); + } + this.queue.add(block); +}; + +jasmine.Runner.prototype.specs = function () { + var suites = this.suites(); + var specs = []; + for (var i = 0; i < suites.length; i++) { + specs = specs.concat(suites[i].specs()); + } + return specs; +}; + +jasmine.Runner.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Runner.prototype.topLevelSuites = function() { + var topLevelSuites = []; + for (var i = 0; i < this.suites_.length; i++) { + if (!this.suites_[i].parentSuite) { + topLevelSuites.push(this.suites_[i]); + } + } + return topLevelSuites; +}; + +jasmine.Runner.prototype.results = function() { + return this.queue.results(); +}; +/** + * Internal representation of a Jasmine specification, or test. + * + * @constructor + * @param {jasmine.Env} env + * @param {jasmine.Suite} suite + * @param {String} description + */ +jasmine.Spec = function(env, suite, description) { + if (!env) { + throw new Error('jasmine.Env() required'); + } + if (!suite) { + throw new Error('jasmine.Suite() required'); + } + var spec = this; + spec.id = env.nextSpecId ? env.nextSpecId() : null; + spec.env = env; + spec.suite = suite; + spec.description = description; + spec.queue = new jasmine.Queue(env); + + spec.afterCallbacks = []; + spec.spies_ = []; + + spec.results_ = new jasmine.NestedResults(); + spec.results_.description = description; + spec.matchersClass = null; +}; + +jasmine.Spec.prototype.getFullName = function() { + return this.suite.getFullName() + ' ' + this.description + '.'; +}; + + +jasmine.Spec.prototype.results = function() { + return this.results_; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.Spec.prototype.log = function() { + return this.results_.log(arguments); +}; + +jasmine.Spec.prototype.runs = function (func) { + var block = new jasmine.Block(this.env, func, this); + this.addToQueue(block); + return this; +}; + +jasmine.Spec.prototype.addToQueue = function (block) { + if (this.queue.isRunning()) { + this.queue.insertNext(block); + } else { + this.queue.add(block); + } +}; + +/** + * @param {jasmine.ExpectationResult} result + */ +jasmine.Spec.prototype.addMatcherResult = function(result) { + this.results_.addResult(result); +}; + +jasmine.Spec.prototype.expect = function(actual) { + var positive = new (this.getMatchersClass_())(this.env, actual, this); + positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); + return positive; +}; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +jasmine.Spec.prototype.waits = function(timeout) { + var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); + this.addToQueue(waitsFunc); + return this; +}; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + var latchFunction_ = null; + var optional_timeoutMessage_ = null; + var optional_timeout_ = null; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + switch (typeof arg) { + case 'function': + latchFunction_ = arg; + break; + case 'string': + optional_timeoutMessage_ = arg; + break; + case 'number': + optional_timeout_ = arg; + break; + } + } + + var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); + this.addToQueue(waitsForFunc); + return this; +}; + +jasmine.Spec.prototype.fail = function (e) { + var expectationResult = new jasmine.ExpectationResult({ + passed: false, + message: e ? jasmine.util.formatException(e) : 'Exception', + trace: { stack: e.stack } + }); + this.results_.addResult(expectationResult); +}; + +jasmine.Spec.prototype.getMatchersClass_ = function() { + return this.matchersClass || this.env.matchersClass; +}; + +jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { + var parent = this.getMatchersClass_(); + var newMatchersClass = function() { + parent.apply(this, arguments); + }; + jasmine.util.inherit(newMatchersClass, parent); + jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); + this.matchersClass = newMatchersClass; +}; + +jasmine.Spec.prototype.finishCallback = function() { + this.env.reporter.reportSpecResults(this); +}; + +jasmine.Spec.prototype.finish = function(onComplete) { + this.removeAllSpies(); + this.finishCallback(); + if (onComplete) { + onComplete(); + } +}; + +jasmine.Spec.prototype.after = function(doAfter) { + if (this.queue.isRunning()) { + this.queue.add(new jasmine.Block(this.env, doAfter, this), true); + } else { + this.afterCallbacks.unshift(doAfter); + } +}; + +jasmine.Spec.prototype.execute = function(onComplete) { + var spec = this; + if (!spec.env.specFilter(spec)) { + spec.results_.skipped = true; + spec.finish(onComplete); + return; + } + + this.env.reporter.reportSpecStarting(this); + + spec.env.currentSpec = spec; + + spec.addBeforesAndAftersToQueue(); + + spec.queue.start(function () { + spec.finish(onComplete); + }); +}; + +jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { + var runner = this.env.currentRunner(); + var i; + + for (var suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); + } + } + for (i = 0; i < runner.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); + } + for (i = 0; i < this.afterCallbacks.length; i++) { + this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true); + } + for (suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true); + } + } + for (i = 0; i < runner.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true); + } +}; + +jasmine.Spec.prototype.explodes = function() { + throw 'explodes function should not have been called'; +}; + +jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { + if (obj == jasmine.undefined) { + throw "spyOn could not find an object to spy upon for " + methodName + "()"; + } + + if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { + throw methodName + '() method does not exist'; + } + + if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { + throw new Error(methodName + ' has already been spied upon'); + } + + var spyObj = jasmine.createSpy(methodName); + + this.spies_.push(spyObj); + spyObj.baseObj = obj; + spyObj.methodName = methodName; + spyObj.originalValue = obj[methodName]; + + obj[methodName] = spyObj; + + return spyObj; +}; + +jasmine.Spec.prototype.removeAllSpies = function() { + for (var i = 0; i < this.spies_.length; i++) { + var spy = this.spies_[i]; + spy.baseObj[spy.methodName] = spy.originalValue; + } + this.spies_ = []; +}; + +/** + * Internal representation of a Jasmine suite. + * + * @constructor + * @param {jasmine.Env} env + * @param {String} description + * @param {Function} specDefinitions + * @param {jasmine.Suite} parentSuite + */ +jasmine.Suite = function(env, description, specDefinitions, parentSuite) { + var self = this; + self.id = env.nextSuiteId ? env.nextSuiteId() : null; + self.description = description; + self.queue = new jasmine.Queue(env); + self.parentSuite = parentSuite; + self.env = env; + self.before_ = []; + self.after_ = []; + self.children_ = []; + self.suites_ = []; + self.specs_ = []; +}; + +jasmine.Suite.prototype.getFullName = function() { + var fullName = this.description; + for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { + fullName = parentSuite.description + ' ' + fullName; + } + return fullName; +}; + +jasmine.Suite.prototype.finish = function(onComplete) { + this.env.reporter.reportSuiteResults(this); + this.finished = true; + if (typeof(onComplete) == 'function') { + onComplete(); + } +}; + +jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.unshift(beforeEachFunction); +}; + +jasmine.Suite.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.unshift(afterEachFunction); +}; + +jasmine.Suite.prototype.results = function() { + return this.queue.results(); +}; + +jasmine.Suite.prototype.add = function(suiteOrSpec) { + this.children_.push(suiteOrSpec); + if (suiteOrSpec instanceof jasmine.Suite) { + this.suites_.push(suiteOrSpec); + this.env.currentRunner().addSuite(suiteOrSpec); + } else { + this.specs_.push(suiteOrSpec); + } + this.queue.add(suiteOrSpec); +}; + +jasmine.Suite.prototype.specs = function() { + return this.specs_; +}; + +jasmine.Suite.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Suite.prototype.children = function() { + return this.children_; +}; + +jasmine.Suite.prototype.execute = function(onComplete) { + var self = this; + this.queue.start(function () { + self.finish(onComplete); + }); +}; +jasmine.WaitsBlock = function(env, timeout, spec) { + this.timeout = timeout; + jasmine.Block.call(this, env, null, spec); +}; + +jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); + +jasmine.WaitsBlock.prototype.execute = function (onComplete) { + if (jasmine.VERBOSE) { + this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); + } + this.env.setTimeout(function () { + onComplete(); + }, this.timeout); +}; +/** + * A block which waits for some condition to become true, with timeout. + * + * @constructor + * @extends jasmine.Block + * @param {jasmine.Env} env The Jasmine environment. + * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. + * @param {Function} latchFunction A function which returns true when the desired condition has been met. + * @param {String} message The message to display if the desired condition hasn't been met within the given time period. + * @param {jasmine.Spec} spec The Jasmine spec. + */ +jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { + this.timeout = timeout || env.defaultTimeoutInterval; + this.latchFunction = latchFunction; + this.message = message; + this.totalTimeSpentWaitingForLatch = 0; + jasmine.Block.call(this, env, null, spec); +}; +jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); + +jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; + +jasmine.WaitsForBlock.prototype.execute = function(onComplete) { + if (jasmine.VERBOSE) { + this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); + } + var latchFunctionResult; + try { + latchFunctionResult = this.latchFunction.apply(this.spec); + } catch (e) { + this.spec.fail(e); + onComplete(); + return; + } + + if (latchFunctionResult) { + onComplete(); + } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { + var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); + this.spec.fail({ + name: 'timeout', + message: message + }); + + this.abort = true; + onComplete(); + } else { + this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; + var self = this; + this.env.setTimeout(function() { + self.execute(onComplete); + }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); + } +}; + +jasmine.version_= { + "major": 1, + "minor": 3, + "build": 1, + "revision": 1354556913 +}; diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less.js b/node_modules/less-middleware/node_modules/less/test/browser/less.js new file mode 100644 index 000000000..d902843aa --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less.js @@ -0,0 +1,8307 @@ +/*! + * Less - Leaner CSS v1.7.4 + * http://lesscss.org + * + * Copyright (c) 2009-2014, Alexis Sellier + * Licensed under the Apache v2 License. + * + */ + + /** * @license Apache v2 + */ + +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= level) { + console.log('less: ' + str); + } +} + +/* + TODO - options is now hidden - we should expose it on the less object, but not have it "as" the less object + alternately even have it on environment + e.g. less.environment.options.fileAsync = true; + is it weird you do + less = { fileAsync: true } + then access as less.environment.options.fileAsync ? + */ + +var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol), + options = window.less, + environment = require("./environment/browser.js")(options, isFileProtocol, log, logLevel); + +window.less = less = require('./non-node-index.js')(environment); + +less.env = options.env || (location.hostname == '127.0.0.1' || + location.hostname == '0.0.0.0' || + location.hostname == 'localhost' || + (location.port && + location.port.length > 0) || + isFileProtocol ? 'development' + : 'production'); + +// The amount of logging in the javascript console. +// 3 - Debug, information and errors +// 2 - Information and errors +// 1 - Errors +// 0 - None +// Defaults to 2 +less.logLevel = typeof(options.logLevel) != 'undefined' ? options.logLevel : (less.env === 'development' ? logLevel.debug : logLevel.errors); + +// Load styles asynchronously (default: false) +// +// This is set to `false` by default, so that the body +// doesn't start loading before the stylesheets are parsed. +// Setting this to `true` can result in flickering. +// +options.async = options.async || false; +options.fileAsync = options.fileAsync || false; + +// Interval between watch polls +less.poll = less.poll || (isFileProtocol ? 1000 : 1500); + +//Setup user functions +if (options.functions) { + less.functions.functionRegistry.addMultiple(options.functions); +} + +var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash); +if (dumpLineNumbers) { + less.dumpLineNumbers = dumpLineNumbers[1]; +} + +var typePattern = /^text\/(x-)?less$/; +var cache = null; + +function extractId(href) { + return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain + .replace(/^\//, '' ) // Remove root / + .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension + .replace(/[^\.\w-]+/g, '-') // Replace illegal characters + .replace(/\./g, ':'); // Replace dots with colons(for valid id) +} + +function errorConsole(e, rootHref) { + var template = '{line} {content}'; + var filename = e.filename || rootHref; + var errors = []; + var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + + " in " + filename + " "; + + var errorline = function (e, i, classname) { + if (e.extract[i] !== undefined) { + errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) + .replace(/\{class\}/, classname) + .replace(/\{content\}/, e.extract[i])); + } + }; + + if (e.extract) { + errorline(e, 0, ''); + errorline(e, 1, 'line'); + errorline(e, 2, ''); + content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' + + errors.join('\n'); + } else if (e.stack) { + content += e.stack; + } + log(content, logLevel.errors); +} + +function createCSS(styles, sheet, lastModified) { + // Strip the query-string + var href = sheet.href || ''; + + // If there is no title set, use the filename, minus the extension + var id = 'less:' + (sheet.title || extractId(href)); + + // If this has already been inserted into the DOM, we may need to replace it + var oldCss = document.getElementById(id); + var keepOldCss = false; + + // Create a new stylesheet node for insertion or (if necessary) replacement + var css = document.createElement('style'); + css.setAttribute('type', 'text/css'); + if (sheet.media) { + css.setAttribute('media', sheet.media); + } + css.id = id; + + if (!css.styleSheet) { + css.appendChild(document.createTextNode(styles)); + + // If new contents match contents of oldCss, don't replace oldCss + keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 && + oldCss.firstChild.nodeValue === css.firstChild.nodeValue); + } + + var head = document.getElementsByTagName('head')[0]; + + // If there is no oldCss, just append; otherwise, only append if we need + // to replace oldCss with an updated stylesheet + if (oldCss === null || keepOldCss === false) { + var nextEl = sheet && sheet.nextSibling || null; + if (nextEl) { + nextEl.parentNode.insertBefore(css, nextEl); + } else { + head.appendChild(css); + } + } + if (oldCss && keepOldCss === false) { + oldCss.parentNode.removeChild(oldCss); + } + + // For IE. + // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash. + // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head + if (css.styleSheet) { + try { + css.styleSheet.cssText = styles; + } catch (e) { + throw new(Error)("Couldn't reassign styleSheet.cssText."); + } + } + + // Don't update the local store if the file wasn't modified + if (lastModified && cache) { + log('saving ' + href + ' to cache.', logLevel.info); + try { + cache.setItem(href, styles); + cache.setItem(href + ':timestamp', lastModified); + } catch(e) { + //TODO - could do with adding more robust error handling + log('failed to save', logLevel.errors); + } + } +} + +function postProcessCSS(styles) { + if (options.postProcessor && typeof options.postProcessor === 'function') { + styles = options.postProcessor.call(styles, styles) || styles; + } + return styles; +} + +function errorHTML(e, rootHref) { + var id = 'less-error-message:' + extractId(rootHref || ""); + var template = '
  • {content}
  • '; + var elem = document.createElement('div'), timer, content, errors = []; + var filename = e.filename || rootHref; + var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; + + elem.id = id; + elem.className = "less-error-message"; + + content = '

    ' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + + '

    ' + '

    in ' + filenameNoPath + " "; + + var errorline = function (e, i, classname) { + if (e.extract[i] !== undefined) { + errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) + .replace(/\{class\}/, classname) + .replace(/\{content\}/, e.extract[i])); + } + }; + + if (e.extract) { + errorline(e, 0, ''); + errorline(e, 1, 'line'); + errorline(e, 2, ''); + content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':

    ' + + '
      ' + errors.join('') + '
    '; + } else if (e.stack) { + content += '
    ' + e.stack.split('\n').slice(1).join('
    '); + } + elem.innerHTML = content; + + // CSS for error messages + createCSS([ + '.less-error-message ul, .less-error-message li {', + 'list-style-type: none;', + 'margin-right: 15px;', + 'padding: 4px 0;', + 'margin: 0;', + '}', + '.less-error-message label {', + 'font-size: 12px;', + 'margin-right: 15px;', + 'padding: 4px 0;', + 'color: #cc7777;', + '}', + '.less-error-message pre {', + 'color: #dd6666;', + 'padding: 4px 0;', + 'margin: 0;', + 'display: inline-block;', + '}', + '.less-error-message pre.line {', + 'color: #ff0000;', + '}', + '.less-error-message h3 {', + 'font-size: 20px;', + 'font-weight: bold;', + 'padding: 15px 0 5px 0;', + 'margin: 0;', + '}', + '.less-error-message a {', + 'color: #10a', + '}', + '.less-error-message .error {', + 'color: red;', + 'font-weight: bold;', + 'padding-bottom: 2px;', + 'border-bottom: 1px dashed red;', + '}' + ].join('\n'), { title: 'error-message' }); + + elem.style.cssText = [ + "font-family: Arial, sans-serif", + "border: 1px solid #e00", + "background-color: #eee", + "border-radius: 5px", + "-webkit-border-radius: 5px", + "-moz-border-radius: 5px", + "color: #e00", + "padding: 15px", + "margin-bottom: 15px" + ].join(';'); + + if (less.env == 'development') { + timer = setInterval(function () { + if (document.body) { + if (document.getElementById(id)) { + document.body.replaceChild(elem, document.getElementById(id)); + } else { + document.body.insertBefore(elem, document.body.firstChild); + } + clearInterval(timer); + } + }, 10); + } +} + +function error(e, rootHref) { + if (!options.errorReporting || options.errorReporting === "html") { + errorHTML(e, rootHref); + } else if (options.errorReporting === "console") { + errorConsole(e, rootHref); + } else if (typeof options.errorReporting === 'function') { + options.errorReporting("add", e, rootHref); + } +} + +function removeErrorHTML(path) { + var node = document.getElementById('less-error-message:' + extractId(path)); + if (node) { + node.parentNode.removeChild(node); + } +} + +function removeErrorConsole(path) { + //no action +} + +function removeError(path) { + if (!options.errorReporting || options.errorReporting === "html") { + removeErrorHTML(path); + } else if (options.errorReporting === "console") { + removeErrorConsole(path); + } else if (typeof options.errorReporting === 'function') { + options.errorReporting("remove", path); + } +} + +function loadStyles(modifyVars) { + var styles = document.getElementsByTagName('style'), + style; + for (var i = 0; i < styles.length; i++) { + style = styles[i]; + if (style.type.match(typePattern)) { + var env = new less.contexts.parseEnv(options), + lessText = style.innerHTML || ''; + env.filename = document.location.href.replace(/#.*$/, ''); + + if (modifyVars || options.globalVars) { + env.useFileCache = true; + } + + /*jshint loopfunc:true */ + // use closure to store current value of i + var callback = (function(style) { + return function (e, cssAST) { + if (e) { + return error(e, "inline"); + } + var css = cssAST.toCSS(options); + style.type = 'text/css'; + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { + style.innerHTML = css; + } + }; + })(style); + new(less.Parser)(env).parse(lessText, callback, {globalVars: options.globalVars, modifyVars: modifyVars}); + } + } +} + +function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) { + + var env = new less.contexts.parseEnv(options); + env.mime = sheet.type; + + if (modifyVars || options.globalVars) { + env.useFileCache = true; + } + + less.environment.loadFile(env, sheet.href, null, function loadInitialFileCallback(e, data, path, webInfo) { + + var newFileInfo = { + currentDirectory: less.environment.getPath(env, path), + filename: path, + rootFilename: path, + relativeUrls: env.relativeUrls}; + + newFileInfo.entryPath = newFileInfo.currentDirectory; + newFileInfo.rootpath = env.rootpath || newFileInfo.currentDirectory; + + if (webInfo) { + webInfo.remaining = remaining; + + var css = cache && cache.getItem(path), + timestamp = cache && cache.getItem(path + ':timestamp'); + + if (!reload && timestamp && webInfo.lastModified && + (new(Date)(webInfo.lastModified).valueOf() === + new(Date)(timestamp).valueOf())) { + // Use local copy + createCSS(css, sheet); + webInfo.local = true; + callback(null, null, data, sheet, webInfo, path); + return; + } + } + + //TODO add tests around how this behaves when reloading + removeError(path); + + if (data) { + env.currentFileInfo = newFileInfo; + new(less.Parser)(env).parse(data, function (e, root) { + if (e) { return callback(e, null, null, sheet); } + try { + callback(e, root, data, sheet, webInfo, path); + } catch (e) { + callback(e, null, null, sheet); + } + }, {modifyVars: modifyVars, globalVars: options.globalVars}); + } else { + callback(e, null, null, sheet, webInfo, path); + } + }, env, modifyVars); +} + +function loadStyleSheets(callback, reload, modifyVars) { + for (var i = 0; i < less.sheets.length; i++) { + loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars); + } +} + +function initRunningMode(){ + if (less.env === 'development') { + less.watchTimer = setInterval(function () { + if (less.watchMode) { + loadStyleSheets(function (e, root, _, sheet, env) { + if (e) { + error(e, sheet.href); + } else if (root) { + var styles = root.toCSS(less); + styles = postProcessCSS(styles); + createCSS(styles, sheet, env.lastModified); + } + }); + } + }, options.poll); + } +} + +// +// Watch mode +// +less.watch = function () { + if (!less.watchMode ){ + less.env = 'development'; + initRunningMode(); + } + this.watchMode = true; + return true; +}; + +less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; }; + +if (/!watch/.test(location.hash)) { + less.watch(); +} + +if (less.env != 'development') { + try { + cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; + } catch (_) {} +} + +// +// Get all tags with the 'rel' attribute set to "stylesheet/less" +// +var links = document.getElementsByTagName('link'); + +less.sheets = []; + +for (var i = 0; i < links.length; i++) { + if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && + (links[i].type.match(typePattern)))) { + less.sheets.push(links[i]); + } +} + +// +// With this function, it's possible to alter variables and re-render +// CSS without reloading less-files +// +less.modifyVars = function(record) { + less.refresh(false, record); +}; + +less.refresh = function (reload, modifyVars) { + var startTime, endTime; + startTime = endTime = new Date(); + + loadStyleSheets(function (e, root, _, sheet, env) { + if (e) { + return error(e, sheet.href); + } + if (env.local) { + log("loading " + sheet.href + " from cache.", logLevel.info); + } else { + log("parsed " + sheet.href + " successfully.", logLevel.debug); + var styles = root.toCSS(options); + styles = postProcessCSS(styles); + createCSS(styles, sheet, env.lastModified); + } + log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info); + if (env.remaining === 0) { + log("less has finished. css generated in " + (new Date() - startTime) + 'ms', logLevel.info); + } + endTime = new Date(); + }, reload, modifyVars); + + loadStyles(modifyVars); +}; + +less.refreshStyles = loadStyles; + +less.refresh(less.env === 'development'); + +},{"./environment/browser.js":6,"./non-node-index.js":20}],2:[function(require,module,exports){ +var contexts = {}; +module.exports = contexts; + +var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) { + if (!original) { return; } + + for(var i = 0; i < propertiesToCopy.length; i++) { + if (original.hasOwnProperty(propertiesToCopy[i])) { + destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; + } + } +}; + +var parseCopyProperties = [ + 'paths', // option - unmodified - paths to search for imports on + 'files', // list of files that have been imported, used for import-once + 'contents', // map - filename to contents of all the files + 'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore + 'relativeUrls', // option - whether to adjust URL's to be relative + 'rootpath', // option - rootpath to append to URL's + 'strictImports', // option - + 'insecure', // option - whether to allow imports from insecure ssl hosts + 'dumpLineNumbers', // option - whether to dump line numbers + 'compress', // option - whether to compress + 'processImports', // option - whether to process imports. if false then imports will not be imported + 'syncImport', // option - whether to import synchronously + 'chunkInput', // option - whether to chunk input. more performant but causes parse issues. + 'mime', // browser only - mime type for sheet import + 'useFileCache', // browser only - whether to use the per file session cache + 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc. +]; + +//currentFileInfo = { +// 'relativeUrls' - option - whether to adjust URL's to be relative +// 'filename' - full resolved filename of current file +// 'rootpath' - path to append to normal URLs for this node +// 'currentDirectory' - path to the current file, absolute +// 'rootFilename' - filename of the base file +// 'entryPath' - absolute path to the entry file +// 'reference' - whether the file should not be output and only output parts that are referenced + +contexts.parseEnv = function(options) { + copyFromOriginal(options, this, parseCopyProperties); + + if (!this.contents) { this.contents = {}; } + if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; } + if (!this.files) { this.files = {}; } + + if (typeof this.paths === "string") { this.paths = [this.paths]; } + + if (!this.currentFileInfo) { + var filename = (options && options.filename) || "input"; + var entryPath = filename.replace(/[^\/\\]*$/, ""); + if (options) { + options.filename = null; + } + this.currentFileInfo = { + filename: filename, + relativeUrls: this.relativeUrls, + rootpath: (options && options.rootpath) || "", + currentDirectory: entryPath, + entryPath: entryPath, + rootFilename: filename + }; + } +}; + +var evalCopyProperties = [ + 'silent', // whether to swallow errors and warnings + 'verbose', // whether to log more activity + 'compress', // whether to compress + 'yuicompress', // whether to compress with the outside tool yui compressor + 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) + 'strictMath', // whether math has to be within parenthesis + 'strictUnits', // whether units need to evaluate correctly + 'cleancss', // whether to compress with clean-css + 'sourceMap', // whether to output a source map + 'importMultiple', // whether we are currently importing multiple copies + 'urlArgs', // whether to add args into url tokens + 'javascriptEnabled'// option - whether JavaScript is enabled. if undefined, defaults to true + ]; + +contexts.evalEnv = function(options, frames) { + copyFromOriginal(options, this, evalCopyProperties); + + this.frames = frames || []; +}; + +contexts.evalEnv.prototype.inParenthesis = function () { + if (!this.parensStack) { + this.parensStack = []; + } + this.parensStack.push(true); +}; + +contexts.evalEnv.prototype.outOfParenthesis = function () { + this.parensStack.pop(); +}; + +contexts.evalEnv.prototype.isMathOn = function () { + return this.strictMath ? (this.parensStack && this.parensStack.length) : true; +}; + +contexts.evalEnv.prototype.isPathRelative = function (path) { + return !/^(?:[a-z-]+:|\/)/.test(path); +}; + +contexts.evalEnv.prototype.normalizePath = function( path ) { + var + segments = path.split("/").reverse(), + segment; + + path = []; + while (segments.length !== 0 ) { + segment = segments.pop(); + switch( segment ) { + case ".": + break; + case "..": + if ((path.length === 0) || (path[path.length - 1] === "..")) { + path.push( segment ); + } else { + path.pop(); + } + break; + default: + path.push( segment ); + break; + } + } + + return path.join("/"); +}; + +//todo - do the same for the toCSS env +//tree.toCSSEnv = function (options) { +//}; + + + +},{}],3:[function(require,module,exports){ +module.exports = { + 'aliceblue':'#f0f8ff', + 'antiquewhite':'#faebd7', + 'aqua':'#00ffff', + 'aquamarine':'#7fffd4', + 'azure':'#f0ffff', + 'beige':'#f5f5dc', + 'bisque':'#ffe4c4', + 'black':'#000000', + 'blanchedalmond':'#ffebcd', + 'blue':'#0000ff', + 'blueviolet':'#8a2be2', + 'brown':'#a52a2a', + 'burlywood':'#deb887', + 'cadetblue':'#5f9ea0', + 'chartreuse':'#7fff00', + 'chocolate':'#d2691e', + 'coral':'#ff7f50', + 'cornflowerblue':'#6495ed', + 'cornsilk':'#fff8dc', + 'crimson':'#dc143c', + 'cyan':'#00ffff', + 'darkblue':'#00008b', + 'darkcyan':'#008b8b', + 'darkgoldenrod':'#b8860b', + 'darkgray':'#a9a9a9', + 'darkgrey':'#a9a9a9', + 'darkgreen':'#006400', + 'darkkhaki':'#bdb76b', + 'darkmagenta':'#8b008b', + 'darkolivegreen':'#556b2f', + 'darkorange':'#ff8c00', + 'darkorchid':'#9932cc', + 'darkred':'#8b0000', + 'darksalmon':'#e9967a', + 'darkseagreen':'#8fbc8f', + 'darkslateblue':'#483d8b', + 'darkslategray':'#2f4f4f', + 'darkslategrey':'#2f4f4f', + 'darkturquoise':'#00ced1', + 'darkviolet':'#9400d3', + 'deeppink':'#ff1493', + 'deepskyblue':'#00bfff', + 'dimgray':'#696969', + 'dimgrey':'#696969', + 'dodgerblue':'#1e90ff', + 'firebrick':'#b22222', + 'floralwhite':'#fffaf0', + 'forestgreen':'#228b22', + 'fuchsia':'#ff00ff', + 'gainsboro':'#dcdcdc', + 'ghostwhite':'#f8f8ff', + 'gold':'#ffd700', + 'goldenrod':'#daa520', + 'gray':'#808080', + 'grey':'#808080', + 'green':'#008000', + 'greenyellow':'#adff2f', + 'honeydew':'#f0fff0', + 'hotpink':'#ff69b4', + 'indianred':'#cd5c5c', + 'indigo':'#4b0082', + 'ivory':'#fffff0', + 'khaki':'#f0e68c', + 'lavender':'#e6e6fa', + 'lavenderblush':'#fff0f5', + 'lawngreen':'#7cfc00', + 'lemonchiffon':'#fffacd', + 'lightblue':'#add8e6', + 'lightcoral':'#f08080', + 'lightcyan':'#e0ffff', + 'lightgoldenrodyellow':'#fafad2', + 'lightgray':'#d3d3d3', + 'lightgrey':'#d3d3d3', + 'lightgreen':'#90ee90', + 'lightpink':'#ffb6c1', + 'lightsalmon':'#ffa07a', + 'lightseagreen':'#20b2aa', + 'lightskyblue':'#87cefa', + 'lightslategray':'#778899', + 'lightslategrey':'#778899', + 'lightsteelblue':'#b0c4de', + 'lightyellow':'#ffffe0', + 'lime':'#00ff00', + 'limegreen':'#32cd32', + 'linen':'#faf0e6', + 'magenta':'#ff00ff', + 'maroon':'#800000', + 'mediumaquamarine':'#66cdaa', + 'mediumblue':'#0000cd', + 'mediumorchid':'#ba55d3', + 'mediumpurple':'#9370d8', + 'mediumseagreen':'#3cb371', + 'mediumslateblue':'#7b68ee', + 'mediumspringgreen':'#00fa9a', + 'mediumturquoise':'#48d1cc', + 'mediumvioletred':'#c71585', + 'midnightblue':'#191970', + 'mintcream':'#f5fffa', + 'mistyrose':'#ffe4e1', + 'moccasin':'#ffe4b5', + 'navajowhite':'#ffdead', + 'navy':'#000080', + 'oldlace':'#fdf5e6', + 'olive':'#808000', + 'olivedrab':'#6b8e23', + 'orange':'#ffa500', + 'orangered':'#ff4500', + 'orchid':'#da70d6', + 'palegoldenrod':'#eee8aa', + 'palegreen':'#98fb98', + 'paleturquoise':'#afeeee', + 'palevioletred':'#d87093', + 'papayawhip':'#ffefd5', + 'peachpuff':'#ffdab9', + 'peru':'#cd853f', + 'pink':'#ffc0cb', + 'plum':'#dda0dd', + 'powderblue':'#b0e0e6', + 'purple':'#800080', + 'red':'#ff0000', + 'rosybrown':'#bc8f8f', + 'royalblue':'#4169e1', + 'saddlebrown':'#8b4513', + 'salmon':'#fa8072', + 'sandybrown':'#f4a460', + 'seagreen':'#2e8b57', + 'seashell':'#fff5ee', + 'sienna':'#a0522d', + 'silver':'#c0c0c0', + 'skyblue':'#87ceeb', + 'slateblue':'#6a5acd', + 'slategray':'#708090', + 'slategrey':'#708090', + 'snow':'#fffafa', + 'springgreen':'#00ff7f', + 'steelblue':'#4682b4', + 'tan':'#d2b48c', + 'teal':'#008080', + 'thistle':'#d8bfd8', + 'tomato':'#ff6347', + 'turquoise':'#40e0d0', + 'violet':'#ee82ee', + 'wheat':'#f5deb3', + 'white':'#ffffff', + 'whitesmoke':'#f5f5f5', + 'yellow':'#ffff00', + 'yellowgreen':'#9acd32' +}; +},{}],4:[function(require,module,exports){ +module.exports = { + colors: require("./colors.js"), + unitConversions: require("./unit-conversions.js") +}; + +},{"./colors.js":3,"./unit-conversions.js":5}],5:[function(require,module,exports){ +module.exports = { + length: { + 'm': 1, + 'cm': 0.01, + 'mm': 0.001, + 'in': 0.0254, + 'px': 0.0254 / 96, + 'pt': 0.0254 / 72, + 'pc': 0.0254 / 72 * 12 + }, + duration: { + 's': 1, + 'ms': 0.001 + }, + angle: { + 'rad': 1/(2*Math.PI), + 'deg': 1/360, + 'grad': 1/400, + 'turn': 1 + } +}; +},{}],6:[function(require,module,exports){ +/*global window, XMLHttpRequest */ + +module.exports = function(options, isFileProtocol, log, logLevel) { + +var fileCache = {}; + +//TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load +// isFileProtocol is global + +function getXMLHttpRequest() { + if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !("ActiveXObject" in window))) { + return new XMLHttpRequest(); + } else { + try { + /*global ActiveXObject */ + return new ActiveXObject("Microsoft.XMLHTTP"); + } catch (e) { + log("browser doesn't support AJAX.", logLevel.errors); + return null; + } + } +} + +return { + // make generic but overriddable + warn: function warn(env, msg) { + console.warn(msg); + }, + // make generic but overriddable + getPath: function getPath(env, filename) { + var j = filename.lastIndexOf('/'); + if (j < 0) { + j = filename.lastIndexOf('\\'); + } + if (j < 0) { + return ""; + } + return filename.slice(0, j + 1); + }, + // make generic but overriddable + isPathAbsolute: function isPathAbsolute(env, filename) { + return /^(?:[a-z-]+:|\/|\\)/i.test(filename); + }, + alwaysMakePathsAbsolute: function alwaysMakePathsAbsolute() { + return true; + }, + getCleanCSS: function () { + }, + supportsDataURI: function() { + return false; + }, + pathDiff: function pathDiff(url, baseUrl) { + // diff between two paths to create a relative path + + var urlParts = this.extractUrlParts(url), + baseUrlParts = this.extractUrlParts(baseUrl), + i, max, urlDirectories, baseUrlDirectories, diff = ""; + if (urlParts.hostPart !== baseUrlParts.hostPart) { + return ""; + } + max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); + for(i = 0; i < max; i++) { + if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } + } + baseUrlDirectories = baseUrlParts.directories.slice(i); + urlDirectories = urlParts.directories.slice(i); + for(i = 0; i < baseUrlDirectories.length-1; i++) { + diff += "../"; + } + for(i = 0; i < urlDirectories.length-1; i++) { + diff += urlDirectories[i] + "/"; + } + return diff; + }, + join: function join(basePath, laterPath) { + if (!basePath) { + return laterPath; + } + return this.extractUrlParts(laterPath, basePath).path; + }, + // helper function, not part of API + extractUrlParts: function extractUrlParts(url, baseUrl) { + // urlParts[1] = protocol&hostname || / + // urlParts[2] = / if path relative to host base + // urlParts[3] = directories + // urlParts[4] = filename + // urlParts[5] = parameters + + var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, + urlParts = url.match(urlPartsRegex), + returner = {}, directories = [], i, baseUrlParts; + + if (!urlParts) { + throw new Error("Could not parse sheet href - '"+url+"'"); + } + + // Stylesheets in IE don't always return the full path + if (!urlParts[1] || urlParts[2]) { + baseUrlParts = baseUrl.match(urlPartsRegex); + if (!baseUrlParts) { + throw new Error("Could not parse page url - '"+baseUrl+"'"); + } + urlParts[1] = urlParts[1] || baseUrlParts[1] || ""; + if (!urlParts[2]) { + urlParts[3] = baseUrlParts[3] + urlParts[3]; + } + } + + if (urlParts[3]) { + directories = urlParts[3].replace(/\\/g, "/").split("/"); + + // extract out . before .. so .. doesn't absorb a non-directory + for(i = 0; i < directories.length; i++) { + if (directories[i] === ".") { + directories.splice(i, 1); + i -= 1; + } + } + + for(i = 0; i < directories.length; i++) { + if (directories[i] === ".." && i > 0) { + directories.splice(i-1, 2); + i -= 2; + } + } + } + + returner.hostPart = urlParts[1]; + returner.directories = directories; + returner.path = urlParts[1] + directories.join("/"); + returner.fileUrl = returner.path + (urlParts[4] || ""); + returner.url = returner.fileUrl + (urlParts[5] || ""); + return returner; + }, + doXHR: function doXHR(url, type, callback, errback) { + + var xhr = getXMLHttpRequest(); + var async = isFileProtocol ? options.fileAsync : options.async; + + if (typeof(xhr.overrideMimeType) === 'function') { + xhr.overrideMimeType('text/css'); + } + log("XHR: Getting '" + url + "'", logLevel.debug); + xhr.open('GET', url, async); + xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); + xhr.send(null); + + function handleResponse(xhr, callback, errback) { + if (xhr.status >= 200 && xhr.status < 300) { + callback(xhr.responseText, + xhr.getResponseHeader("Last-Modified")); + } else if (typeof(errback) === 'function') { + errback(xhr.status, url); + } + } + + if (isFileProtocol && !options.fileAsync) { + if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { + callback(xhr.responseText); + } else { + errback(xhr.status, url); + } + } else if (async) { + xhr.onreadystatechange = function () { + if (xhr.readyState == 4) { + handleResponse(xhr, callback, errback); + } + }; + } else { + handleResponse(xhr, callback, errback); + } + }, + loadFile: function loadFile(env, filename, currentDirectory, callback) { + if (currentDirectory && !this.isPathAbsolute(env, filename)) { + filename = currentDirectory + filename; + } + + // sheet may be set to the stylesheet for the initial load or a collection of properties including + // some env variables for imports + var hrefParts = this.extractUrlParts(filename, window.location.href); + var href = hrefParts.url; + + if (env.useFileCache && fileCache[href]) { + try { + var lessText = fileCache[href]; + callback(null, lessText, href, { lastModified: new Date() }); + } catch (e) { + callback(e, null, href); + } + return; + } + + this.doXHR(href, env.mime, function doXHRCallback(data, lastModified) { + // per file cache + fileCache[href] = data; + + // Use remote copy (re-parse) + callback(null, data, href, { lastModified: lastModified }); + }, function doXHRError(status, url) { + callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href); + }); + + } +}; + +}; + +},{}],7:[function(require,module,exports){ +var Color = require("../tree/color.js"), + functionRegistry = require("./function-registry.js"); + +// Color Blending +// ref: http://www.w3.org/TR/compositing-1 + +function colorBlend(mode, color1, color2) { + var ab = color1.alpha, cb, // backdrop + as = color2.alpha, cs, // source + ar, cr, r = []; // result + + ar = as + ab * (1 - as); + for (var i = 0; i < 3; i++) { + cb = color1.rgb[i] / 255; + cs = color2.rgb[i] / 255; + cr = mode(cb, cs); + if (ar) { + cr = (as * cs + ab * (cb - + as * (cb + cs - cr))) / ar; + } + r[i] = cr * 255; + } + + return new(Color)(r, ar); +} + +var colorBlendModeFunctions = { + multiply: function(cb, cs) { + return cb * cs; + }, + screen: function(cb, cs) { + return cb + cs - cb * cs; + }, + overlay: function(cb, cs) { + cb *= 2; + return (cb <= 1) + ? colorBlendModeFunctions.multiply(cb, cs) + : colorBlendModeFunctions.screen(cb - 1, cs); + }, + softlight: function(cb, cs) { + var d = 1, e = cb; + if (cs > 0.5) { + e = 1; + d = (cb > 0.25) ? Math.sqrt(cb) + : ((16 * cb - 12) * cb + 4) * cb; + } + return cb - (1 - 2 * cs) * e * (d - cb); + }, + hardlight: function(cb, cs) { + return colorBlendModeFunctions.overlay(cs, cb); + }, + difference: function(cb, cs) { + return Math.abs(cb - cs); + }, + exclusion: function(cb, cs) { + return cb + cs - 2 * cb * cs; + }, + + // non-w3c functions: + average: function(cb, cs) { + return (cb + cs) / 2; + }, + negation: function(cb, cs) { + return 1 - Math.abs(cb + cs - 1); + } +}; + +for (var f in colorBlendModeFunctions) { + if (colorBlendModeFunctions.hasOwnProperty(f)) { + colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]); + } +} + +functionRegistry.addMultiple(colorBlend); + +},{"../tree/color.js":31,"./function-registry.js":12}],8:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + functionRegistry = require("./function-registry.js"), + colorFunctions; + +function clamp(val) { + return Math.min(1, Math.max(0, val)); +} +function hsla(color) { + return colorFunctions.hsla(color.h, color.s, color.l, color.a); +} +function number(n) { + if (n instanceof Dimension) { + return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); + } else if (typeof(n) === 'number') { + return n; + } else { + throw { + error: "RuntimeError", + message: "color functions take numbers as parameters" + }; + } +} +function scaled(n, size) { + if (n instanceof Dimension && n.unit.is('%')) { + return parseFloat(n.value * size / 100); + } else { + return number(n); + } +} +colorFunctions = { + rgb: function (r, g, b) { + return colorFunctions.rgba(r, g, b, 1.0); + }, + rgba: function (r, g, b, a) { + var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); + a = number(a); + return new(Color)(rgb, a); + }, + hsl: function (h, s, l) { + return colorFunctions.hsla(h, s, l, 1.0); + }, + hsla: function (h, s, l, a) { + function hue(h) { + h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); + if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } + else if (h * 2 < 1) { return m2; } + else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } + else { return m1; } + } + + h = (number(h) % 360) / 360; + s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); + + var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + var m1 = l * 2 - m2; + + return colorFunctions.rgba(hue(h + 1/3) * 255, + hue(h) * 255, + hue(h - 1/3) * 255, + a); + }, + + hsv: function(h, s, v) { + return colorFunctions.hsva(h, s, v, 1.0); + }, + + hsva: function(h, s, v, a) { + h = ((number(h) % 360) / 360) * 360; + s = number(s); v = number(v); a = number(a); + + var i, f; + i = Math.floor((h / 60) % 6); + f = (h / 60) - i; + + var vs = [v, + v * (1 - s), + v * (1 - f * s), + v * (1 - (1 - f) * s)]; + var perm = [[0, 3, 1], + [2, 0, 1], + [1, 0, 3], + [1, 2, 0], + [3, 1, 0], + [0, 1, 2]]; + + return colorFunctions.rgba(vs[perm[i][0]] * 255, + vs[perm[i][1]] * 255, + vs[perm[i][2]] * 255, + a); + }, + + hue: function (color) { + return new(Dimension)(color.toHSL().h); + }, + saturation: function (color) { + return new(Dimension)(color.toHSL().s * 100, '%'); + }, + lightness: function (color) { + return new(Dimension)(color.toHSL().l * 100, '%'); + }, + hsvhue: function(color) { + return new(Dimension)(color.toHSV().h); + }, + hsvsaturation: function (color) { + return new(Dimension)(color.toHSV().s * 100, '%'); + }, + hsvvalue: function (color) { + return new(Dimension)(color.toHSV().v * 100, '%'); + }, + red: function (color) { + return new(Dimension)(color.rgb[0]); + }, + green: function (color) { + return new(Dimension)(color.rgb[1]); + }, + blue: function (color) { + return new(Dimension)(color.rgb[2]); + }, + alpha: function (color) { + return new(Dimension)(color.toHSL().a); + }, + luma: function (color) { + return new(Dimension)(color.luma() * color.alpha * 100, '%'); + }, + luminance: function (color) { + var luminance = + (0.2126 * color.rgb[0] / 255) + + (0.7152 * color.rgb[1] / 255) + + (0.0722 * color.rgb[2] / 255); + + return new(Dimension)(luminance * color.alpha * 100, '%'); + }, + saturate: function (color, amount) { + // filter: saturate(3.2); + // should be kept as is, so check for color + if (!color.rgb) { + return null; + } + var hsl = color.toHSL(); + + hsl.s += amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + desaturate: function (color, amount) { + var hsl = color.toHSL(); + + hsl.s -= amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + lighten: function (color, amount) { + var hsl = color.toHSL(); + + hsl.l += amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + darken: function (color, amount) { + var hsl = color.toHSL(); + + hsl.l -= amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + fadein: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a += amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + fadeout: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a -= amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + fade: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a = amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + spin: function (color, amount) { + var hsl = color.toHSL(); + var hue = (hsl.h + amount.value) % 360; + + hsl.h = hue < 0 ? 360 + hue : hue; + + return hsla(hsl); + }, + // + // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein + // http://sass-lang.com + // + mix: function (color1, color2, weight) { + if (!weight) { + weight = new(Dimension)(50); + } + var p = weight.value / 100.0; + var w = p * 2 - 1; + var a = color1.toHSL().a - color2.toHSL().a; + + var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, + color1.rgb[1] * w1 + color2.rgb[1] * w2, + color1.rgb[2] * w1 + color2.rgb[2] * w2]; + + var alpha = color1.alpha * p + color2.alpha * (1 - p); + + return new(Color)(rgb, alpha); + }, + greyscale: function (color) { + return colorFunctions.desaturate(color, new(Dimension)(100)); + }, + contrast: function (color, dark, light, threshold) { + // filter: contrast(3.2); + // should be kept as is, so check for color + if (!color.rgb) { + return null; + } + if (typeof light === 'undefined') { + light = colorFunctions.rgba(255, 255, 255, 1.0); + } + if (typeof dark === 'undefined') { + dark = colorFunctions.rgba(0, 0, 0, 1.0); + } + //Figure out which is actually light and dark! + if (dark.luma() > light.luma()) { + var t = light; + light = dark; + dark = t; + } + if (typeof threshold === 'undefined') { + threshold = 0.43; + } else { + threshold = number(threshold); + } + if (color.luma() < threshold) { + return light; + } else { + return dark; + } + }, + argb: function (color) { + return new(Anonymous)(color.toARGB()); + }, + color: function(c) { + if ((c instanceof Quoted) && + (/^#([a-f0-9]{6}|[a-f0-9]{3})$/i.test(c.value))) { + return new(Color)(c.value.slice(1)); + } + if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) { + c.keyword = undefined; + return c; + } + throw { + type: "Argument", + message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" + }; + }, + tint: function(color, amount) { + return colorFunctions.mix(colorFunctions.rgb(255,255,255), color, amount); + }, + shade: function(color, amount) { + return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount); + } +}; +functionRegistry.addMultiple(colorFunctions); + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/quoted.js":54,"./function-registry.js":12}],9:[function(require,module,exports){ +module.exports = function(environment) { + var Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + functionRegistry = require("./function-registry.js"); + + functionRegistry.add("data-uri", function(mimetypeNode, filePathNode) { + + if (!environment.supportsDataURI(this.env)) { + return new URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); + } + + var mimetype = mimetypeNode.value; + var filePath = (filePathNode && filePathNode.value); + + var useBase64 = false; + + if (arguments.length < 2) { + filePath = mimetype; + } + + var fragmentStart = filePath.indexOf('#'); + var fragment = ''; + if (fragmentStart!==-1) { + fragment = filePath.slice(fragmentStart); + filePath = filePath.slice(0, fragmentStart); + } + + if (this.env.isPathRelative(filePath)) { + if (this.currentFileInfo.relativeUrls) { + filePath = environment.join(this.currentFileInfo.currentDirectory, filePath); + } else { + filePath = environment.join(this.currentFileInfo.entryPath, filePath); + } + } + + // detect the mimetype if not given + if (arguments.length < 2) { + + mimetype = environment.mimeLookup(this.env, filePath); + + // use base 64 unless it's an ASCII or UTF-8 format + var charset = environment.charsetLookup(this.env, mimetype); + useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; + if (useBase64) { mimetype += ';base64'; } + } + else { + useBase64 = /;base64$/.test(mimetype); + } + + var buf = environment.readFileSync(filePath); + + // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded + // and the --ieCompat flag is enabled, return a normal url() instead. + var DATA_URI_MAX_KB = 32, + fileSizeInKB = parseInt((buf.length / 1024), 10); + if (fileSizeInKB >= DATA_URI_MAX_KB) { + + if (this.env.ieCompat !== false) { + if (!this.env.silent) { + console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB); + } + + return new URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); + } + } + + buf = useBase64 ? buf.toString('base64') + : encodeURIComponent(buf); + + var uri = "\"data:" + mimetype + ',' + buf + fragment + "\""; + return new(URL)(new(Anonymous)(uri)); + }); +}; + +},{"../tree/anonymous.js":27,"../tree/url.js":61,"./function-registry.js":12}],10:[function(require,module,exports){ +var Keyword = require("../tree/keyword.js"), + functionRegistry = require("./function-registry.js"); + +var defaultFunc = { + eval: function () { + var v = this.value_, e = this.error_; + if (e) { + throw e; + } + if (v != null) { + return v ? Keyword.True : Keyword.False; + } + }, + value: function (v) { + this.value_ = v; + }, + error: function (e) { + this.error_ = e; + }, + reset: function () { + this.value_ = this.error_ = null; + } +}; + +functionRegistry.add("default", defaultFunc.eval.bind(defaultFunc)); + +module.exports = defaultFunc; + +},{"../tree/keyword.js":46,"./function-registry.js":12}],11:[function(require,module,exports){ +var functionRegistry = require("./function-registry.js"); + +var functionCaller = function(name, env, currentFileInfo) { + this.name = name.toLowerCase(); + this.function = functionRegistry.get(this.name); + this.env = env; + this.currentFileInfo = currentFileInfo; +}; +functionCaller.prototype.isValid = function() { + return Boolean(this.function); +}; +functionCaller.prototype.call = function(args) { + return this.function.apply(this, args); +}; + +module.exports = functionCaller; + +},{"./function-registry.js":12}],12:[function(require,module,exports){ +module.exports = { + _data: {}, + add: function(name, func) { + if (this._data.hasOwnProperty(name)) { + //TODO warn + } + this._data[name] = func; + }, + addMultiple: function(functions) { + Object.keys(functions).forEach( + function(name) { + this.add(name, functions[name]); + }.bind(this)); + }, + get: function(name) { + return this._data[name]; + } +}; + +},{}],13:[function(require,module,exports){ +module.exports = function(environment) { + var functions = { + functionRegistry: require("./function-registry.js"), + functionCaller: require("./function-caller.js") + }; + + //register functions + require("./default.js"); + require("./color.js"); + require("./color-blending.js"); + require("./data-uri.js")(environment); + require("./math.js"); + require("./number.js"); + require("./string.js"); + require("./svg.js")(environment); + require("./types.js"); + + return functions; +}; + +},{"./color-blending.js":7,"./color.js":8,"./data-uri.js":9,"./default.js":10,"./function-caller.js":11,"./function-registry.js":12,"./math.js":14,"./number.js":15,"./string.js":16,"./svg.js":17,"./types.js":18}],14:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + functionRegistry = require("./function-registry.js"); + +var mathFunctions = { + // name, unit + ceil: null, + floor: null, + sqrt: null, + abs: null, + tan: "", + sin: "", + cos: "", + atan: "rad", + asin: "rad", + acos: "rad" +}; + +function _math(fn, unit, n) { + if (!(n instanceof Dimension)) { + throw { type: "Argument", message: "argument must be a number" }; + } + if (unit == null) { + unit = n.unit; + } else { + n = n.unify(); + } + return new(Dimension)(fn(parseFloat(n.value)), unit); +} + +for (var f in mathFunctions) { + if (mathFunctions.hasOwnProperty(f)) { + mathFunctions[f] = _math.bind(null, Math[f], mathFunctions[f]); + } +} + +mathFunctions.round = function (n, f) { + var fraction = typeof(f) === "undefined" ? 0 : f.value; + return _math(function(num) { return num.toFixed(fraction); }, null, n); +}; + +functionRegistry.addMultiple(mathFunctions); + +},{"../tree/dimension.js":37,"./function-registry.js":12}],15:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + Anonymous = require("../tree/anonymous.js"), + functionRegistry = require("./function-registry.js"); + +var minMax = function (isMin, args) { + args = Array.prototype.slice.call(args); + switch(args.length) { + case 0: throw { type: "Argument", message: "one or more arguments required" }; + } + var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, + order = [], // elems only contains original argument values. + values = {}; // key is the unit.toString() for unified Dimension values, + // value is the index into the order array. + for (i = 0; i < args.length; i++) { + current = args[i]; + if (!(current instanceof Dimension)) { + if(Array.isArray(args[i].value)) { + Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value)); + } + continue; + } + currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new(Dimension)(current.value, unitClone).unify() : current.unify(); + unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString(); + unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic; + unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone; + j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit]; + if (j === undefined) { + if(unitStatic !== undefined && unit !== unitStatic) { + throw{ type: "Argument", message: "incompatible types" }; + } + values[unit] = order.length; + order.push(current); + continue; + } + referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new(Dimension)(order[j].value, unitClone).unify() : order[j].unify(); + if ( isMin && currentUnified.value < referenceUnified.value || + !isMin && currentUnified.value > referenceUnified.value) { + order[j] = current; + } + } + if (order.length == 1) { + return order[0]; + } + args = order.map(function (a) { return a.toCSS(this.env); }).join(this.env.compress ? "," : ", "); + return new(Anonymous)((isMin ? "min" : "max") + "(" + args + ")"); +}; +functionRegistry.addMultiple({ + min: function () { + return minMax(true, arguments); + }, + max: function () { + return minMax(false, arguments); + }, + convert: function (val, unit) { + return val.convertTo(unit.value); + }, + pi: function () { + return new(Dimension)(Math.PI); + }, + mod: function(a, b) { + return new(Dimension)(a.value % b.value, a.unit); + }, + pow: function(x, y) { + if (typeof x === "number" && typeof y === "number") { + x = new(Dimension)(x); + y = new(Dimension)(y); + } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) { + throw { type: "Argument", message: "arguments must be numbers" }; + } + + return new(Dimension)(Math.pow(x.value, y.value), x.unit); + }, + percentage: function (n) { + return new(Dimension)(n.value * 100, '%'); + } +}); + +},{"../tree/anonymous.js":27,"../tree/dimension.js":37,"./function-registry.js":12}],16:[function(require,module,exports){ +var Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + JavaScript = require("../tree/javascript.js"), + functionRegistry = require("./function-registry.js"); + +functionRegistry.addMultiple({ + e: function (str) { + return new(Anonymous)(str instanceof JavaScript ? str.evaluated : str.value); + }, + escape: function (str) { + return new(Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); + }, + replace: function (string, pattern, replacement, flags) { + var result = string.value; + + result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement.value); + return new(Quoted)(string.quote || '', result, string.escaped); + }, + '%': function (string /* arg, arg, ...*/) { + var args = Array.prototype.slice.call(arguments, 1), + result = string.value; + + for (var i = 0; i < args.length; i++) { + /*jshint loopfunc:true */ + result = result.replace(/%[sda]/i, function(token) { + var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); + return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; + }); + } + result = result.replace(/%%/g, '%'); + return new(Quoted)(string.quote || '', result, string.escaped); + } +}); + +},{"../tree/anonymous.js":27,"../tree/javascript.js":44,"../tree/quoted.js":54,"./function-registry.js":12}],17:[function(require,module,exports){ +module.exports = function(environment) { + var Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + functionRegistry = require("./function-registry.js"); + + functionRegistry.add("svg-gradient", function(direction) { + + function throwArgumentDescriptor() { + throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" }; + } + + if (arguments.length < 3) { + throwArgumentDescriptor(); + } + var stops = Array.prototype.slice.call(arguments, 1), + gradientDirectionSvg, + gradientType = "linear", + rectangleDimension = 'x="0" y="0" width="1" height="1"', + useBase64 = true, + renderEnv = {compress: false}, + returner, + directionValue = direction.toCSS(renderEnv), + i, color, position, positionValue, alpha; + + switch (directionValue) { + case "to bottom": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; + break; + case "to right": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; + break; + case "to bottom right": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; + break; + case "to top right": + gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; + break; + case "ellipse": + case "ellipse at center": + gradientType = "radial"; + gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; + rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; + break; + default: + throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" }; + } + returner = '' + + '' + + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; + + for (i = 0; i < stops.length; i+= 1) { + if (stops[i].value) { + color = stops[i].value[0]; + position = stops[i].value[1]; + } else { + color = stops[i]; + position = undefined; + } + + if (!(color instanceof Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof Dimension))) { + throwArgumentDescriptor(); + } + positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%"; + alpha = color.alpha; + returner += ''; + } + returner += '' + + ''; + + if (useBase64) { + try { + returner = environment.encodeBase64(this.env, returner); + } catch(e) { + useBase64 = false; + } + } + + returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'"; + return new(URL)(new(Anonymous)(returner)); + }); +}; + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/url.js":61,"./function-registry.js":12}],18:[function(require,module,exports){ +var Keyword = require("../tree/keyword.js"), + Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + Operation = require("../tree/operation.js"), + functionRegistry = require("./function-registry.js"); + +var isa = function (n, Type) { + return (n instanceof Type) ? Keyword.True : Keyword.False; + }, + isunit = function (n, unit) { + return (n instanceof Dimension) && n.unit.is(unit.value || unit) ? Keyword.True : Keyword.False; + }; +functionRegistry.addMultiple({ + iscolor: function (n) { + return isa(n, Color); + }, + isnumber: function (n) { + return isa(n, Dimension); + }, + isstring: function (n) { + return isa(n, Quoted); + }, + iskeyword: function (n) { + return isa(n, Keyword); + }, + isurl: function (n) { + return isa(n, URL); + }, + ispixel: function (n) { + return isunit(n, 'px'); + }, + ispercentage: function (n) { + return isunit(n, '%'); + }, + isem: function (n) { + return isunit(n, 'em'); + }, + isunit: isunit, + unit: function (val, unit) { + if(!(val instanceof Dimension)) { + throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof Operation ? ". Have you forgotten parenthesis?" : "") }; + } + if (unit) { + if (unit instanceof Keyword) { + unit = unit.value; + } else { + unit = unit.toCSS(); + } + } else { + unit = ""; + } + return new(Dimension)(val.value, unit); + }, + "get-unit": function (n) { + return new(Anonymous)(n.unit); + }, + extract: function(values, index) { + index = index.value - 1; // (1-based index) + // handle non-array values as an array of length 1 + // return 'undefined' if index is invalid + return Array.isArray(values.value) ? + values.value[index] : Array(values)[index]; + }, + length: function(values) { + var n = Array.isArray(values.value) ? values.value.length : 1; + return new Dimension(n); + } +}); + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/keyword.js":46,"../tree/operation.js":52,"../tree/quoted.js":54,"../tree/url.js":61,"./function-registry.js":12}],19:[function(require,module,exports){ + +var LessError = module.exports = function LessError(parser, e, env) { + var input = parser.getInput(e, env), + loc = parser.getLocation(e.index, input), + line = loc.line, + col = loc.column, + callLine = e.call && parser.getLocation(e.call, input).line, + lines = input.split('\n'); + + this.type = e.type || 'Syntax'; + this.message = e.message; + this.filename = e.filename || env.currentFileInfo.filename; + this.index = e.index; + this.line = typeof(line) === 'number' ? line + 1 : null; + this.callLine = callLine + 1; + this.callExtract = lines[callLine]; + this.stack = e.stack; + this.column = col; + this.extract = [ + lines[line - 1], + lines[line], + lines[line + 1] + ]; +}; + +LessError.prototype = new Error(); +LessError.prototype.constructor = LessError; + +},{}],20:[function(require,module,exports){ +module.exports = function(environment) { + var less = { + version: [2, 0, 0], + data: require('./data/index.js'), + tree: require('./tree/index.js'), + visitor: require('./visitor/index.js'), + Parser: require('./parser/parser.js')(environment), + functions: require('./functions/index.js')(environment), + contexts: require("./contexts.js"), + environment: environment + }; + + return less; +}; + +},{"./contexts.js":2,"./data/index.js":4,"./functions/index.js":13,"./parser/parser.js":24,"./tree/index.js":43,"./visitor/index.js":66}],21:[function(require,module,exports){ +// Split the input into chunks. +module.exports = function (input, fail) { + var len = input.length, level = 0, parenLevel = 0, + lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, + chunks = [], emitFrom = 0, + chunkerCurrentIndex, currentChunkStartIndex, cc, cc2, matched; + + function emitChunk(force) { + var len = chunkerCurrentIndex - emitFrom; + if (((len < 512) && !force) || !len) { + return; + } + chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1)); + emitFrom = chunkerCurrentIndex + 1; + } + + for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc = input.charCodeAt(chunkerCurrentIndex); + if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { + // a-z or whitespace + continue; + } + + switch (cc) { + case 40: // ( + parenLevel++; + lastOpeningParen = chunkerCurrentIndex; + continue; + case 41: // ) + if (--parenLevel < 0) { + return fail("missing opening `(`", chunkerCurrentIndex); + } + continue; + case 59: // ; + if (!parenLevel) { emitChunk(); } + continue; + case 123: // { + level++; + lastOpening = chunkerCurrentIndex; + continue; + case 125: // } + if (--level < 0) { + return fail("missing opening `{`", chunkerCurrentIndex); + } + if (!level && !parenLevel) { emitChunk(); } + continue; + case 92: // \ + if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; } + return fail("unescaped `\\`", chunkerCurrentIndex); + case 34: + case 39: + case 96: // ", ' and ` + matched = 0; + currentChunkStartIndex = chunkerCurrentIndex; + for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if (cc2 > 96) { continue; } + if (cc2 == cc) { matched = 1; break; } + if (cc2 == 92) { // \ + if (chunkerCurrentIndex == len - 1) { + return fail("unescaped `\\`", chunkerCurrentIndex); + } + chunkerCurrentIndex++; + } + } + if (matched) { continue; } + return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); + case 47: // /, check for comment + if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; } + cc2 = input.charCodeAt(chunkerCurrentIndex + 1); + if (cc2 == 47) { + // //, find lnfeed + for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } + } + } else if (cc2 == 42) { + // /*, find */ + lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex; + for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; } + if (cc2 != 42) { continue; } + if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; } + } + if (chunkerCurrentIndex == len - 1) { + return fail("missing closing `*/`", currentChunkStartIndex); + } + chunkerCurrentIndex++; + } + continue; + case 42: // *, check for unmatched */ + if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) { + return fail("unmatched `/*`", chunkerCurrentIndex); + } + continue; + } + } + + if (level !== 0) { + if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { + return fail("missing closing `}` or `*/`", lastOpening); + } else { + return fail("missing closing `}`", lastOpening); + } + } else if (parenLevel !== 0) { + return fail("missing closing `)`", lastOpeningParen); + } + + emitChunk(true); + return chunks; +}; + +},{}],22:[function(require,module,exports){ +var contexts = require("../contexts.js"); +module.exports = function(environment, env, Parser) { + var rootFilename = env && env.filename; + return { + paths: env.paths || [], // Search paths, when importing + queue: [], // Files which haven't been imported yet + files: env.files, // Holds the imported parse trees + contents: env.contents, // Holds the imported file contents + contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less + mime: env.mime, // MIME type of .less files + error: null, // Error in parsing/evaluating an import + push: function (path, currentFileInfo, importOptions, callback) { + var parserImports = this; + this.queue.push(path); + + var fileParsedFunc = function (e, root, fullPath) { + parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue + + var importedPreviously = fullPath === rootFilename; + + parserImports.files[fullPath] = root; // Store the root + + if (e && !parserImports.error) { parserImports.error = e; } + + callback(e, root, importedPreviously, fullPath); + }; + + var newFileInfo = { + relativeUrls: env.relativeUrls, + entryPath: currentFileInfo.entryPath, + rootpath: currentFileInfo.rootpath, + rootFilename: currentFileInfo.rootFilename + }; + + environment.loadFile(env, path, currentFileInfo.currentDirectory, function loadFileCallback(e, contents, resolvedFilename) { + if (e) { + fileParsedFunc(e); + return; + } + + // Pass on an updated rootpath if path of imported file is relative and file + // is in a (sub|sup) directory + // + // Examples: + // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/', + // then rootpath should become 'less/module/nav/' + // - If path of imported file is '../mixins.less' and rootpath is 'less/', + // then rootpath should become 'less/../' + newFileInfo.currentDirectory = environment.getPath(env, resolvedFilename); + if(newFileInfo.relativeUrls) { + newFileInfo.rootpath = environment.join((env.rootpath || ""), environment.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath)); + if (!environment.isPathAbsolute(env, newFileInfo.rootpath) && environment.alwaysMakePathsAbsolute()) { + newFileInfo.rootpath = environment.join(newFileInfo.entryPath, newFileInfo.rootpath); + } + } + newFileInfo.filename = resolvedFilename; + + var newEnv = new contexts.parseEnv(env); + + newEnv.currentFileInfo = newFileInfo; + newEnv.processImports = false; + newEnv.contents[resolvedFilename] = contents; + + if (currentFileInfo.reference || importOptions.reference) { + newFileInfo.reference = true; + } + + if (importOptions.inline) { + fileParsedFunc(null, contents, resolvedFilename); + } else { + new(Parser)(newEnv).parse(contents, function (e, root) { + fileParsedFunc(e, root, resolvedFilename); + }); + } + }); + } + }; +}; + +},{"../contexts.js":2}],23:[function(require,module,exports){ +var chunker = require('./chunker.js'), + LessError = require('../less-error.js'); +module.exports = function() { + var input, // LeSS input string + j, // current chunk + saveStack = [], // holds state for backtracking + furthest, // furthest index the parser has gone to + furthestPossibleErrorMessage,// if this is furthest we got to, this is the probably cause + chunks, // chunkified input + current, // current chunk + currentPos, // index of current chunk, in `input` + parserInput = {}; + + parserInput.save = function() { + currentPos = parserInput.i; + saveStack.push( { current: current, i: parserInput.i, j: j }); + }; + parserInput.restore = function(possibleErrorMessage) { + if (parserInput.i > furthest) { + furthest = parserInput.i; + furthestPossibleErrorMessage = possibleErrorMessage; + } + var state = saveStack.pop(); + current = state.current; + currentPos = parserInput.i = state.i; + j = state.j; + }; + parserInput.forget = function() { + saveStack.pop(); + }; + function sync() { + if (parserInput.i > currentPos) { + current = current.slice(parserInput.i - currentPos); + currentPos = parserInput.i; + } + } + parserInput.isWhitespace = function (offset) { + var pos = parserInput.i + (offset || 0), + code = input.charCodeAt(pos); + return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF); + }; + // + // Parse from a token, regexp or string, and move forward if match + // + parserInput.$ = function(tok) { + var tokType = typeof tok, + match, length; + + // Either match a single character in the input, + // or match a regexp in the current chunk (`current`). + // + if (tokType === "string") { + if (input.charAt(parserInput.i) !== tok) { + return null; + } + skipWhitespace(1); + return tok; + } + + // regexp + sync(); + if (! (match = tok.exec(current))) { + return null; + } + + length = match[0].length; + + // The match is confirmed, add the match length to `i`, + // and consume any extra white-space characters (' ' || '\n') + // which come after that. The reason for this is that LeSS's + // grammar is mostly white-space insensitive. + // + skipWhitespace(length); + + if(typeof(match) === 'string') { + return match; + } else { + return match.length === 1 ? match[0] : match; + } + }; + + // Specialization of $(tok) + parserInput.$re = function(tok) { + if (parserInput.i > currentPos) { + current = current.slice(parserInput.i - currentPos); + currentPos = parserInput.i; + } + var m = tok.exec(current); + if (!m) { + return null; + } + + skipWhitespace(m[0].length); + if(typeof m === "string") { + return m; + } + + return m.length === 1 ? m[0] : m; + }; + + // Specialization of $(tok) + parserInput.$char = function(tok) { + if (input.charAt(parserInput.i) !== tok) { + return null; + } + skipWhitespace(1); + return tok; + }; + + var CHARCODE_SPACE = 32, + CHARCODE_TAB = 9, + CHARCODE_LF = 10, + CHARCODE_CR = 13, + CHARCODE_PLUS = 43, + CHARCODE_COMMA = 44, + CHARCODE_FORWARD_SLASH = 47, + CHARCODE_9 = 57; + + parserInput.autoCommentAbsorb = true; + parserInput.commentStore = []; + parserInput.finished = false; + + var skipWhitespace = function(length) { + var oldi = parserInput.i, oldj = j, + curr = parserInput.i - currentPos, + endIndex = parserInput.i + current.length - curr, + mem = (parserInput.i += length), + inp = input, + c, nextChar, comment; + + for (; parserInput.i < endIndex; parserInput.i++) { + c = inp.charCodeAt(parserInput.i); + + if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) { + nextChar = inp[parserInput.i + 1]; + if (nextChar === '/') { + comment = {index: parserInput.i, isLineComment: true}; + var nextNewLine = inp.indexOf("\n", parserInput.i + 1); + if (nextNewLine < 0) { + nextNewLine = endIndex; + } + parserInput.i = nextNewLine; + comment.text = inp.substr(comment.i, parserInput.i - comment.i); + parserInput.commentStore.push(comment); + continue; + } else if (nextChar === '*') { + var haystack = inp.substr(parserInput.i); + var comment_search_result = haystack.match(/^\/\*(?:[^*]|\*+[^\/*])*\*+\//); + if (comment_search_result) { + comment = { + index: parserInput.i, + text: comment_search_result[0], + isLineComment: false + }; + parserInput.i += comment.text.length - 1; + parserInput.commentStore.push(comment); + continue; + } + } + break; + } + + if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) { + break; + } + } + + current = current.slice(length + parserInput.i - mem + curr); + currentPos = parserInput.i; + + if (!current.length) { + if (j < chunks.length - 1) + { + current = chunks[++j]; + skipWhitespace(0); // skip space at the beginning of a chunk + return true; // things changed + } + parserInput.finished = true; + } + + return oldi !== parserInput.i || oldj !== j; + }; + + // Same as $(), but don't change the state of the parser, + // just return the match. + parserInput.peek = function(tok) { + if (typeof(tok) === 'string') { + return input.charAt(parserInput.i) === tok; + } else { + return tok.test(current); + } + }; + + // Specialization of peek() + // TODO remove or change some currentChar calls to peekChar + parserInput.peekChar = function(tok) { + return input.charAt(parserInput.i) === tok; + }; + + parserInput.currentChar = function() { + return input.charAt(parserInput.i); + }; + + parserInput.getInput = function() { + return input; + }; + + parserInput.peekNotNumeric = function() { + var c = input.charCodeAt(parserInput.i); + //Is the first char of the dimension 0-9, '.', '+' or '-' + return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA; + }; + + parserInput.getLocation = function(index, inputStream) { + inputStream = inputStream == null ? input : inputStream; + + var n = index + 1, + line = null, + column = -1; + + while (--n >= 0 && inputStream.charAt(n) !== '\n') { + column++; + } + + if (typeof index === 'number') { + line = (inputStream.slice(0, index).match(/\n/g) || "").length; + } + + return { + line: line, + column: column + }; + }; + + parserInput.start = function(str, chunkInput, parser, env) { + input = str; + parserInput.i = j = currentPos = furthest = 0; + + // chunking apparantly makes things quicker (but my tests indicate + // it might actually make things slower in node at least) + // and it is a non-perfect parse - it can't recognise + // unquoted urls, meaning it can't distinguish comments + // meaning comments with quotes or {}() in them get 'counted' + // and then lead to parse errors. + // In addition if the chunking chunks in the wrong place we might + // not be able to parse a parser statement in one go + // this is officially deprecated but can be switched on via an option + // in the case it causes too much performance issues. + if (chunkInput) { + chunks = chunker(str, function fail(msg, index) { + throw new(LessError)(parser, { + index: index, + type: 'Parse', + message: msg, + filename: env.currentFileInfo.filename + }, env); + }); + } else { + chunks = [str]; + } + + current = chunks[0]; + + skipWhitespace(0); + }; + + parserInput.end = function() { + var message, + isFinished = parserInput.i >= input.length - 1; + + if (parserInput.i < furthest) { + message = furthestPossibleErrorMessage; + parserInput.i = furthest; + } + return { + isFinished: isFinished, + furthest: parserInput.i, + furthestPossibleErrorMessage: message, + furthestReachedEnd: parserInput.i >= input.length - 1, + furthestChar: input[parserInput.i] + }; + }; + + return parserInput; +}; + +},{"../less-error.js":19,"./chunker.js":21}],24:[function(require,module,exports){ +var LessError = require('../less-error.js'), + tree = require("../tree/index.js"), + visitor = require("../visitor/index.js"), + contexts = require("../contexts.js"), + getImportManager = require("./imports.js"), + getParserInput = require("./parser-input.js"); + +module.exports = function(environment) { +var SourceMapOutput = require("../source-map-output")(environment); +// +// less.js - parser +// +// A relatively straight-forward predictive parser. +// There is no tokenization/lexing stage, the input is parsed +// in one sweep. +// +// To make the parser fast enough to run in the browser, several +// optimization had to be made: +// +// - Matching and slicing on a huge input is often cause of slowdowns. +// The solution is to chunkify the input into smaller strings. +// The chunks are stored in the `chunks` var, +// `j` holds the current chunk index, and `currentPos` holds +// the index of the current chunk in relation to `input`. +// This gives us an almost 4x speed-up. +// +// - In many cases, we don't need to match individual tokens; +// for example, if a value doesn't hold any variables, operations +// or dynamic references, the parser can effectively 'skip' it, +// treating it as a literal. +// An example would be '1px solid #000' - which evaluates to itself, +// we don't need to know what the individual components are. +// The drawback, of course is that you don't get the benefits of +// syntax-checking on the CSS. This gives us a 50% speed-up in the parser, +// and a smaller speed-up in the code-gen. +// +// +// Token matching is done with the `$` function, which either takes +// a terminal string or regexp, or a non-terminal function to call. +// It also takes care of moving all the indices forwards. +// +// +var Parser = function Parser(env) { + var parser, + parsers, + parserInput = getParserInput(); + + // Top parser on an import tree must be sure there is one "env" + // which will then be passed around by reference. + if (!(env instanceof contexts.parseEnv)) { + env = new contexts.parseEnv(env); + } + this.env = env; + + var imports = this.imports = getImportManager(environment, env, Parser); + + function expect(arg, msg, index) { + // some older browsers return typeof 'function' for RegExp + var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : parserInput.$(arg); + if (result) { + return result; + } + error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'" + : "unexpected token")); + } + + // Specialization of expect() + function expectChar(arg, msg) { + if (parserInput.$char(arg)) { + return arg; + } + error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'"); + } + + function error(msg, type) { + var e = new Error(msg); + e.index = parserInput.i; + e.type = type || 'Syntax'; + throw e; + } + + function getInput(e, env) { + if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) { + return parser.imports.contents[e.filename]; + } else { + return parserInput.getInput(); + } + } + + function getDebugInfo(index) { + var filename = env.currentFileInfo.filename; + filename = environment.getAbsolutePath(env, filename); + + return { + lineNumber: parserInput.getLocation(index).line + 1, + fileName: filename + }; + } + + // + // The Parser + // + parser = { + + imports: imports, + // + // Parse an input string into an abstract syntax tree, + // @param str A string containing 'less' markup + // @param callback call `callback` when done. + // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply + // + parse: function (str, callback, additionalData) { + var root, error = null, globalVars, modifyVars, preText = ""; + + globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : ''; + modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : ''; + + if (globalVars || (additionalData && additionalData.banner)) { + preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars; + parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length; + } + + str = str.replace(/\r\n/g, '\n'); + // Remove potential UTF Byte Order Mark + str = preText + str.replace(/^\uFEFF/, '') + modifyVars; + parser.imports.contents[env.currentFileInfo.filename] = str; + + // Start with the primary rule. + // The whole syntax tree is held under a Ruleset node, + // with the `root` property set to true, so no `{}` are + // output. The callback is called when the input is parsed. + try { + parserInput.start(str, env.chunkInput, parser, env); + + root = new(tree.Ruleset)(null, this.parsers.primary()); + root.root = true; + root.firstRoot = true; + } catch (e) { + return callback(new LessError(parser, e, env)); + } + + root.toCSS = (function (evaluate) { + return function (options, variables) { + options = options || {}; + var evaldRoot, + css, + evalEnv = new contexts.evalEnv(options); + + // + // Allows setting variables with a hash, so: + // + // `{ color: new(tree.Color)('#f01') }` will become: + // + // new(tree.Rule)('@color', + // new(tree.Value)([ + // new(tree.Expression)([ + // new(tree.Color)('#f01') + // ]) + // ]) + // ) + // + if (typeof(variables) === 'object' && !Array.isArray(variables)) { + variables = Object.keys(variables).map(function (k) { + var value = variables[k]; + + if (! (value instanceof tree.Value)) { + if (! (value instanceof tree.Expression)) { + value = new(tree.Expression)([value]); + } + value = new(tree.Value)([value]); + } + return new(tree.Rule)('@' + k, value, false, null, 0); + }); + evalEnv.frames = [new(tree.Ruleset)(null, variables)]; + } + + try { + var preEvalVisitors = [], + visitors = [ + new(visitor.JoinSelectorVisitor)(), + new(visitor.ExtendVisitor)(), + new(visitor.ToCSSVisitor)({compress: Boolean(options.compress)}) + ], i, root = this; + + if (options.plugins) { + for(i =0; i < options.plugins.length; i++) { + if (options.plugins[i].isPreEvalVisitor) { + preEvalVisitors.push(options.plugins[i]); + } else { + if (options.plugins[i].isPreVisitor) { + visitors.splice(0, 0, options.plugins[i]); + } else { + visitors.push(options.plugins[i]); + } + } + } + } + + for(i = 0; i < preEvalVisitors.length; i++) { + preEvalVisitors[i].run(root); + } + + evaldRoot = evaluate.call(root, evalEnv); + + for(i = 0; i < visitors.length; i++) { + visitors[i].run(evaldRoot); + } + + if (options.sourceMap) { + evaldRoot = new SourceMapOutput( + { + contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars, + writeSourceMap: options.writeSourceMap, + rootNode: evaldRoot, + contentsMap: parser.imports.contents, + sourceMapFilename: options.sourceMapFilename, + sourceMapURL: options.sourceMapURL, + outputFilename: options.sourceMapOutputFilename, + sourceMapBasepath: options.sourceMapBasepath, + sourceMapRootpath: options.sourceMapRootpath, + outputSourceFiles: options.outputSourceFiles, + sourceMapGenerator: options.sourceMapGenerator + }); + } + + css = evaldRoot.toCSS({ + compress: Boolean(options.compress), + dumpLineNumbers: env.dumpLineNumbers, + strictUnits: Boolean(options.strictUnits), + numPrecision: 8}); + } catch (e) { + throw new LessError(parser, e, env); + } + + var CleanCSS = environment.getCleanCSS(); + if (options.cleancss && CleanCSS) { + var cleancssOptions = options.cleancssOptions || {}; + + if (cleancssOptions.keepSpecialComments === undefined) { + cleancssOptions.keepSpecialComments = "*"; + } + cleancssOptions.processImport = false; + cleancssOptions.noRebase = true; + if (cleancssOptions.noAdvanced === undefined) { + cleancssOptions.noAdvanced = true; + } + + return new CleanCSS(cleancssOptions).minify(css); + } else if (options.compress) { + return css.replace(/(^(\s)+)|((\s)+$)/g, ""); + } else { + return css; + } + }; + })(root.eval); + + // If `i` is smaller than the `input.length - 1`, + // it means the parser wasn't able to parse the whole + // string, so we've got a parsing error. + // + // We try to extract a \n delimited string, + // showing the line where the parse error occurred. + // We split it up into two parts (the part which parsed, + // and the part which didn't), so we can color them differently. + var endInfo = parserInput.end(); + if (!endInfo.isFinished) { + + var message = endInfo.furthestPossibleErrorMessage; + + if (!message) { + message = "Unrecognised input"; + if (endInfo.furthestChar === '}') { + message += ". Possibly missing opening '{'"; + } else if (endInfo.furthestChar === ')') { + message += ". Possibly missing opening '('"; + } else if (endInfo.furthestReachedEnd) { + message += ". Possibly missing something"; + } + } + + error = new LessError(parser, { + type: "Parse", + message: message, + index: endInfo.furthest, + filename: env.currentFileInfo.filename + }, env); + } + + var finish = function (e) { + e = error || e || parser.imports.error; + + if (e) { + if (!(e instanceof LessError)) { + e = new LessError(parser, e, env); + } + + return callback(e); + } + else { + return callback(null, root); + } + }; + + if (env.processImports !== false) { + new visitor.ImportVisitor(this.imports, finish) + .run(root); + } else { + return finish(); + } + }, + + // + // Here in, the parsing rules/functions + // + // The basic structure of the syntax tree generated is as follows: + // + // Ruleset -> Rule -> Value -> Expression -> Entity + // + // Here's some Less code: + // + // .class { + // color: #fff; + // border: 1px solid #000; + // width: @w + 4px; + // > .child {...} + // } + // + // And here's what the parse tree might look like: + // + // Ruleset (Selector '.class', [ + // Rule ("color", Value ([Expression [Color #fff]])) + // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) + // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) + // Ruleset (Selector [Element '>', '.child'], [...]) + // ]) + // + // In general, most rules will try to parse a token with the `$()` function, and if the return + // value is truly, will return a new node, of the relevant type. Sometimes, we need to check + // first, before parsing, that's when we use `peek()`. + // + parsers: parsers = { + // + // The `primary` rule is the *entry* and *exit* point of the parser. + // The rules here can appear at any level of the parse tree. + // + // The recursive nature of the grammar is an interplay between the `block` + // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, + // as represented by this simplified grammar: + // + // primary → (ruleset | rule)+ + // ruleset → selector+ block + // block → '{' primary '}' + // + // Only at one point is the primary rule not called from the + // block rule: at the root level. + // + primary: function () { + var mixin = this.mixin, root = [], node; + + while (!parserInput.finished) + { + while(true) { + node = this.comment(); + if (!node) { break; } + root.push(node); + } + if (parserInput.peek('}')) { + break; + } + node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() || + mixin.call() || this.rulesetCall() || this.directive(); + if (node) { + root.push(node); + } else { + if (!(parserInput.$re(/^[\s\n]+/) || parserInput.$re(/^;+/))) { + break; + } + } + } + + return root; + }, + + // comments are collected by the main parsing mechanism and then assigned to nodes + // where the current structure allows it + comment: function () { + if (parserInput.commentStore.length) { + var comment = parserInput.commentStore.shift(); + return new(tree.Comment)(comment.text, comment.isLineComment, comment.index, env.currentFileInfo); + } + }, + + // + // Entities are tokens which can be found inside an Expression + // + entities: { + // + // A string, which supports escaping " and ' + // + // "milky way" 'he\'s the one!' + // + quoted: function () { + var str, index = parserInput.i; + + str = parserInput.$re(/^(~)?("((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)')/); + if (str) { + return new(tree.Quoted)(str[2], str[3] || str[4], Boolean(str[1]), index, env.currentFileInfo); + } + }, + + // + // A catch-all word, such as: + // + // black border-collapse + // + keyword: function () { + var k = parserInput.$re(/^%|^[_A-Za-z-][_A-Za-z0-9-]*/); + if (k) { + return tree.Color.fromKeyword(k) || new(tree.Keyword)(k); + } + }, + + // + // A function call + // + // rgb(255, 0, 255) + // + // We also try to catch IE's `alpha()`, but let the `alpha` parser + // deal with the details. + // + // The arguments are parsed with the `entities.arguments` parser. + // + call: function () { + var name, nameLC, args, alpha, index = parserInput.i; + + if (parserInput.peek(/^url\(/i)) { + return; + } + + parserInput.save(); + + name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/); + if (!name) { parserInput.forget(); return; } + + name = name[1]; + nameLC = name.toLowerCase(); + + if (nameLC === 'alpha') { + alpha = parsers.alpha(); + if(alpha) { + return alpha; + } + } + + args = this.arguments(); + + if (! parserInput.$char(')')) { + parserInput.restore("Could not parse call arguments or missing ')'"); + return; + } + + parserInput.forget(); + return new(tree.Call)(name, args, index, env.currentFileInfo); + }, + arguments: function () { + var args = [], arg; + + while (true) { + arg = this.assignment() || parsers.expression(); + if (!arg) { + break; + } + args.push(arg); + if (! parserInput.$char(',')) { + break; + } + } + return args; + }, + literal: function () { + return this.dimension() || + this.color() || + this.quoted() || + this.unicodeDescriptor(); + }, + + // Assignments are argument entities for calls. + // They are present in ie filter properties as shown below. + // + // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) + // + + assignment: function () { + var key, value; + key = parserInput.$re(/^\w+(?=\s?=)/i); + if (!key) { + return; + } + if (!parserInput.$char('=')) { + return; + } + value = parsers.entity(); + if (value) { + return new(tree.Assignment)(key, value); + } + }, + + // + // Parse url() tokens + // + // We use a specific rule for urls, because they don't really behave like + // standard function calls. The difference is that the argument doesn't have + // to be enclosed within a string, so it can't be parsed as an Expression. + // + url: function () { + var value; + + if (parserInput.currentChar() !== 'u' || !parserInput.$re(/^url\(/)) { + return; + } + + parserInput.autoCommentAbsorb = false; + + value = this.quoted() || this.variable() || + parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; + + parserInput.autoCommentAbsorb = true; + + expectChar(')'); + + return new(tree.URL)((value.value != null || value instanceof tree.Variable) + ? value : new(tree.Anonymous)(value), env.currentFileInfo); + }, + + // + // A Variable entity, such as `@fink`, in + // + // width: @fink + 2px + // + // We use a different parser for variable definitions, + // see `parsers.variable`. + // + variable: function () { + var name, index = parserInput.i; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) { + return new(tree.Variable)(name, index, env.currentFileInfo); + } + }, + + // A variable entity useing the protective {} e.g. @{var} + variableCurly: function () { + var curly, index = parserInput.i; + + if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) { + return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo); + } + }, + + // + // A Hexadecimal color + // + // #4F3C2F + // + // `rgb` and `hsl` colors are parsed through the `entities.call` parser. + // + color: function () { + var rgb; + + if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { + var colorCandidateString = rgb.input.match(/^#([\w]+).*/); // strip colons, brackets, whitespaces and other characters that should not definitely be part of color string + colorCandidateString = colorCandidateString[1]; + if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characters + error("Invalid HEX color code"); + } + return new(tree.Color)(rgb[1]); + } + }, + + // + // A Dimension, that is, a number and a unit + // + // 0.5em 95% + // + dimension: function () { + if (parserInput.peekNotNumeric()) { + return; + } + + var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/); + if (value) { + return new(tree.Dimension)(value[1], value[2]); + } + }, + + // + // A unicode descriptor, as is used in unicode-range + // + // U+0?? or U+00A1-00A9 + // + unicodeDescriptor: function () { + var ud; + + ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); + if (ud) { + return new(tree.UnicodeDescriptor)(ud[0]); + } + }, + + // + // JavaScript code to be evaluated + // + // `window.location.href` + // + javascript: function () { + var js, index = parserInput.i; + + js = parserInput.$re(/^(~)?`([^`]*)`/); + if (js) { + return new(tree.JavaScript)(js[2], index, Boolean(js[1])); + } + } + }, + + // + // The variable part of a variable definition. Used in the `rule` parser + // + // @fink: + // + variable: function () { + var name; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; } + }, + + // + // The variable part of a variable definition. Used in the `rule` parser + // + // @fink(); + // + rulesetCall: function () { + var name; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*\(\s*\)\s*;/))) { + return new tree.RulesetCall(name[1]); + } + }, + + // + // extend syntax - used to extend selectors + // + extend: function(isRule) { + var elements, e, index = parserInput.i, option, extendList, extend; + + if (!(isRule ? parserInput.$re(/^&:extend\(/) : parserInput.$re(/^:extend\(/))) { return; } + + do { + option = null; + elements = null; + while (! (option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) { + e = this.element(); + if (!e) { break; } + if (elements) { elements.push(e); } else { elements = [ e ]; } + } + + option = option && option[1]; + if (!elements) + error("Missing target selector for :extend()."); + extend = new(tree.Extend)(new(tree.Selector)(elements), option, index); + if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } + + } while(parserInput.$char(",")); + + expect(/^\)/); + + if (isRule) { + expect(/^;/); + } + + return extendList; + }, + + // + // extendRule - used in a rule to extend all the parent selectors + // + extendRule: function() { + return this.extend(true); + }, + + // + // Mixins + // + mixin: { + // + // A Mixin call, with an optional argument list + // + // #mixins > .square(#fff); + // .rounded(4px, black); + // .button; + // + // The `while` loop is there because mixins can be + // namespaced, but we only support the child and descendant + // selector for now. + // + call: function () { + var s = parserInput.currentChar(), important = false, index = parserInput.i, elemIndex, + elements, elem, e, c, args; + + if (s !== '.' && s !== '#') { return; } + + parserInput.save(); // stop us absorbing part of an invalid selector + + while (true) { + elemIndex = parserInput.i; + e = parserInput.$re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/); + if (!e) { + break; + } + elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo); + if (elements) { elements.push(elem); } else { elements = [ elem ]; } + c = parserInput.$char('>'); + } + + if (elements) { + if (parserInput.$char('(')) { + args = this.args(true).args; + expectChar(')'); + } + + if (parsers.important()) { + important = true; + } + + if (parsers.end()) { + parserInput.forget(); + return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important); + } + } + + parserInput.restore(); + }, + args: function (isCall) { + var parsers = parser.parsers, entities = parsers.entities, + returner = { args:null, variadic: false }, + expressions = [], argsSemiColon = [], argsComma = [], + isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg; + + parserInput.save(); + + while (true) { + if (isCall) { + arg = parsers.detachedRuleset() || parsers.expression(); + } else { + parserInput.commentStore.length = 0; + if (parserInput.currentChar() === '.' && parserInput.$re(/^\.{3}/)) { + returner.variadic = true; + if (parserInput.$char(";") && !isSemiColonSeperated) { + isSemiColonSeperated = true; + } + (isSemiColonSeperated ? argsSemiColon : argsComma) + .push({ variadic: true }); + break; + } + arg = entities.variable() || entities.literal() || entities.keyword(); + } + + if (!arg) { + break; + } + + nameLoop = null; + if (arg.throwAwayComments) { + arg.throwAwayComments(); + } + value = arg; + var val = null; + + if (isCall) { + // Variable + if (arg.value && arg.value.length == 1) { + val = arg.value[0]; + } + } else { + val = arg; + } + + if (val && val instanceof tree.Variable) { + if (parserInput.$char(':')) { + if (expressions.length > 0) { + if (isSemiColonSeperated) { + error("Cannot mix ; and , as delimiter types"); + } + expressionContainsNamed = true; + } + + // we do not support setting a ruleset as a default variable - it doesn't make sense + // However if we do want to add it, there is nothing blocking it, just don't error + // and remove isCall dependency below + value = (isCall && parsers.detachedRuleset()) || parsers.expression(); + + if (!value) { + if (isCall) { + error("could not understand value for named argument"); + } else { + parserInput.restore(); + returner.args = []; + return returner; + } + } + nameLoop = (name = val.name); + } else if (!isCall && parserInput.$re(/^\.{3}/)) { + returner.variadic = true; + if (parserInput.$char(";") && !isSemiColonSeperated) { + isSemiColonSeperated = true; + } + (isSemiColonSeperated ? argsSemiColon : argsComma) + .push({ name: arg.name, variadic: true }); + break; + } else if (!isCall) { + name = nameLoop = val.name; + value = null; + } + } + + if (value) { + expressions.push(value); + } + + argsComma.push({ name:nameLoop, value:value }); + + if (parserInput.$char(',')) { + continue; + } + + if (parserInput.$char(';') || isSemiColonSeperated) { + + if (expressionContainsNamed) { + error("Cannot mix ; and , as delimiter types"); + } + + isSemiColonSeperated = true; + + if (expressions.length > 1) { + value = new(tree.Value)(expressions); + } + argsSemiColon.push({ name:name, value:value }); + + name = null; + expressions = []; + expressionContainsNamed = false; + } + } + + parserInput.forget(); + returner.args = isSemiColonSeperated ? argsSemiColon : argsComma; + return returner; + }, + // + // A Mixin definition, with a list of parameters + // + // .rounded (@radius: 2px, @color) { + // ... + // } + // + // Until we have a finer grained state-machine, we have to + // do a look-ahead, to make sure we don't have a mixin call. + // See the `rule` function for more information. + // + // We start by matching `.rounded (`, and then proceed on to + // the argument list, which has optional default values. + // We store the parameters in `params`, with a `value` key, + // if there is a value, such as in the case of `@radius`. + // + // Once we've got our params list, and a closing `)`, we parse + // the `{...}` block. + // + definition: function () { + var name, params = [], match, ruleset, cond, variadic = false; + if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') || + parserInput.peek(/^[^{]*\}/)) { + return; + } + + parserInput.save(); + + match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); + if (match) { + name = match[1]; + + var argInfo = this.args(false); + params = argInfo.args; + variadic = argInfo.variadic; + + // .mixincall("@{a}"); + // looks a bit like a mixin definition.. + // also + // .mixincall(@a: {rule: set;}); + // so we have to be nice and restore + if (!parserInput.$char(')')) { + parserInput.restore("Missing closing ')'"); + return; + } + + parserInput.commentStore.length = 0; + + if (parserInput.$re(/^when/)) { // Guard + cond = expect(parsers.conditions, 'expected condition'); + } + + ruleset = parsers.block(); + + if (ruleset) { + parserInput.forget(); + return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); + } else { + parserInput.restore(); + } + } else { + parserInput.forget(); + } + } + }, + + // + // Entities are the smallest recognized token, + // and can be found inside a rule's value. + // + entity: function () { + var entities = this.entities; + + return this.comment() || entities.literal() || entities.variable() || entities.url() || + entities.call() || entities.keyword() || entities.javascript(); + }, + + // + // A Rule terminator. Note that we use `peek()` to check for '}', + // because the `block` rule will be expecting it, but we still need to make sure + // it's there, if ';' was ommitted. + // + end: function () { + return parserInput.$char(';') || parserInput.peek('}'); + }, + + // + // IE's alpha function + // + // alpha(opacity=88) + // + alpha: function () { + var value; + + if (! parserInput.$re(/^opacity=/i)) { return; } + value = parserInput.$re(/^\d+/); + if (!value) { + value = expect(this.entities.variable, "Could not parse alpha"); + } + expectChar(')'); + return new(tree.Alpha)(value); + }, + + // + // A Selector Element + // + // div + // + h1 + // #socks + // input[type="text"] + // + // Elements are the building blocks for Selectors, + // they are made out of a `Combinator` (see combinator rule), + // and an element name, such as a tag a class, or `*`. + // + element: function () { + var e, c, v, index = parserInput.i; + + c = this.combinator(); + + e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || + parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^()@]+\)/) || parserInput.$re(/^[\.#](?=@)/) || + this.entities.variableCurly(); + + if (! e) { + parserInput.save(); + if (parserInput.$char('(')) { + if ((v = this.selector()) && parserInput.$char(')')) { + e = new(tree.Paren)(v); + parserInput.forget(); + } else { + parserInput.restore("Missing closing ')'"); + } + } else { + parserInput.forget(); + } + } + + if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); } + }, + + // + // Combinators combine elements together, in a Selector. + // + // Because our parser isn't white-space sensitive, special care + // has to be taken, when parsing the descendant combinator, ` `, + // as it's an empty space. We have to check the previous character + // in the input, to see if it's a ` ` character. More info on how + // we deal with this in *combinator.js*. + // + combinator: function () { + var c = parserInput.currentChar(); + + if (c === '/') { + parserInput.save(); + var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i); + if (slashedCombinator) { + parserInput.forget(); + return new(tree.Combinator)(slashedCombinator); + } + parserInput.restore(); + } + + if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { + parserInput.i++; + if (c === '^' && parserInput.currentChar() === '^') { + c = '^^'; + parserInput.i++; + } + while (parserInput.isWhitespace()) { parserInput.i++; } + return new(tree.Combinator)(c); + } else if (parserInput.isWhitespace(-1)) { + return new(tree.Combinator)(" "); + } else { + return new(tree.Combinator)(null); + } + }, + // + // A CSS selector (see selector below) + // with less extensions e.g. the ability to extend and guard + // + lessSelector: function () { + return this.selector(true); + }, + // + // A CSS Selector + // + // .class > div + h1 + // li a:hover + // + // Selectors are made out of one or more Elements, see above. + // + selector: function (isLess) { + var index = parserInput.i, elements, extendList, c, e, extend, when, condition; + + while ((isLess && (extend = this.extend())) || (isLess && (when = parserInput.$re(/^when/))) || (e = this.element())) { + if (when) { + condition = expect(this.conditions, 'expected condition'); + } else if (condition) { + error("CSS guard can only be used at the end of selector"); + } else if (extend) { + if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } + } else { + if (extendList) { error("Extend can only be used at the end of selector"); } + c = parserInput.currentChar(); + if (elements) { elements.push(e); } else { elements = [ e ]; } + e = null; + } + if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { + break; + } + } + + if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); } + if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); } + }, + attribute: function () { + if (! parserInput.$char('[')) { return; } + + var entities = this.entities, + key, val, op; + + if (!(key = entities.variableCurly())) { + key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); + } + + op = parserInput.$re(/^[|~*$^]?=/); + if (op) { + val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly(); + } + + expectChar(']'); + + return new(tree.Attribute)(key, op, val); + }, + + // + // The `block` rule is used by `ruleset` and `mixin.definition`. + // It's a wrapper around the `primary` rule, with added `{}`. + // + block: function () { + var content; + if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) { + return content; + } + }, + + blockRuleset: function() { + var block = this.block(); + + if (block) { + block = new tree.Ruleset(null, block); + } + return block; + }, + + detachedRuleset: function() { + var blockRuleset = this.blockRuleset(); + if (blockRuleset) { + return new tree.DetachedRuleset(blockRuleset); + } + }, + + // + // div, .class, body > p {...} + // + ruleset: function () { + var selectors, s, rules, debugInfo; + + parserInput.save(); + + if (env.dumpLineNumbers) { + debugInfo = getDebugInfo(parserInput.i); + } + + while (true) { + s = this.lessSelector(); + if (!s) { + break; + } + if (selectors) { selectors.push(s); } else { selectors = [ s ]; } + parserInput.commentStore.length = 0; + if (s.condition && selectors.length > 1) { + error("Guards are only currently allowed on a single selector."); + } + if (! parserInput.$char(',')) { break; } + if (s.condition) { + error("Guards are only currently allowed on a single selector."); + } + parserInput.commentStore.length = 0; + } + + if (selectors && (rules = this.block())) { + parserInput.forget(); + var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); + if (env.dumpLineNumbers) { + ruleset.debugInfo = debugInfo; + } + return ruleset; + } else { + parserInput.restore(); + } + }, + rule: function (tryAnonymous) { + var name, value, startOfRule = parserInput.i, c = parserInput.currentChar(), important, merge, isVariable; + + if (c === '.' || c === '#' || c === '&') { return; } + + parserInput.save(); + + name = this.variable() || this.ruleProperty(); + if (name) { + isVariable = typeof name === "string"; + + if (isVariable) { + value = this.detachedRuleset(); + } + + parserInput.commentStore.length = 0; + if (!value) { + // a name returned by this.ruleProperty() is always an array of the form: + // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] + // where each item is a tree.Keyword or tree.Variable + merge = !isVariable && name.pop().value; + + // prefer to try to parse first if its a variable or we are compressing + // but always fallback on the other one + var tryValueFirst = !tryAnonymous && (env.compress || isVariable); + + if (tryValueFirst) { + value = this.value(); + } + if (!value) { + value = this.anonymousValue(); + if (value) { + parserInput.forget(); + // anonymous values absorb the end ';' which is reequired for them to work + return new (tree.Rule)(name, value, false, merge, startOfRule, env.currentFileInfo); + } + } + if (!tryValueFirst && !value) { + value = this.value(); + } + + important = this.important(); + } + + if (value && this.end()) { + parserInput.forget(); + return new (tree.Rule)(name, value, important, merge, startOfRule, env.currentFileInfo); + } else { + parserInput.restore(); + if (value && !tryAnonymous) { + return this.rule(true); + } + } + } else { + parserInput.forget(); + } + }, + anonymousValue: function () { + var match = parserInput.$re(/^([^@+\/'"*`(;{}-]*);/); + if (match) { + return new(tree.Anonymous)(match[1]); + } + }, + + // + // An @import directive + // + // @import "lib"; + // + // Depending on our environment, importing is done differently: + // In the browser, it's an XHR request, in Node, it would be a + // file-system operation. The function used for importing is + // stored in `import`, which we pass to the Import constructor. + // + "import": function () { + var path, features, index = parserInput.i; + + var dir = parserInput.$re(/^@import?\s+/); + + if (dir) { + var options = (dir ? this.importOptions() : null) || {}; + + if ((path = this.entities.quoted() || this.entities.url())) { + features = this.mediaFeatures(); + + if (!parserInput.$(';')) { + parserInput.i = index; + error("missing semi-colon or unrecognised media features on import"); + } + features = features && new(tree.Value)(features); + return new(tree.Import)(path, features, options, index, env.currentFileInfo); + } + else + { + parserInput.i = index; + error("malformed import statement"); + } + } + }, + + importOptions: function() { + var o, options = {}, optionName, value; + + // list of options, surrounded by parens + if (! parserInput.$char('(')) { return null; } + do { + o = this.importOption(); + if (o) { + optionName = o; + value = true; + switch(optionName) { + case "css": + optionName = "less"; + value = false; + break; + case "once": + optionName = "multiple"; + value = false; + break; + } + options[optionName] = value; + if (! parserInput.$char(',')) { break; } + } + } while (o); + expectChar(')'); + return options; + }, + + importOption: function() { + var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference)/); + if (opt) { + return opt[1]; + } + }, + + mediaFeature: function () { + var entities = this.entities, nodes = [], e, p; + parserInput.save(); + do { + e = entities.keyword() || entities.variable(); + if (e) { + nodes.push(e); + } else if (parserInput.$char('(')) { + p = this.property(); + e = this.value(); + if (parserInput.$char(')')) { + if (p && e) { + nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, parserInput.i, env.currentFileInfo, true))); + } else if (e) { + nodes.push(new(tree.Paren)(e)); + } else { + parserInput.restore("badly formed media feature definition"); + return null; + } + } else { + parserInput.restore("Missing closing ')'"); + return null; + } + } + } while (e); + + parserInput.forget(); + if (nodes.length > 0) { + return new(tree.Expression)(nodes); + } + }, + + mediaFeatures: function () { + var entities = this.entities, features = [], e; + do { + e = this.mediaFeature(); + if (e) { + features.push(e); + if (! parserInput.$char(',')) { break; } + } else { + e = entities.variable(); + if (e) { + features.push(e); + if (! parserInput.$char(',')) { break; } + } + } + } while (e); + + return features.length > 0 ? features : null; + }, + + media: function () { + var features, rules, media, debugInfo; + + if (env.dumpLineNumbers) { + debugInfo = getDebugInfo(parserInput.i); + } + + if (parserInput.$re(/^@media/)) { + features = this.mediaFeatures(); + + rules = this.block(); + if (rules) { + media = new(tree.Media)(rules, features, parserInput.i, env.currentFileInfo); + if (env.dumpLineNumbers) { + media.debugInfo = debugInfo; + } + return media; + } + } + }, + + // + // A CSS Directive + // + // @charset "utf-8"; + // + directive: function () { + var index = parserInput.i, name, value, rules, nonVendorSpecificName, + hasIdentifier, hasExpression, hasUnknown, hasBlock = true; + + if (parserInput.currentChar() !== '@') { return; } + + value = this['import']() || this.media(); + if (value) { + return value; + } + + parserInput.save(); + + name = parserInput.$re(/^@[a-z-]+/); + + if (!name) { return; } + + nonVendorSpecificName = name; + if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { + nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); + } + + switch(nonVendorSpecificName) { + /* + case "@font-face": + case "@viewport": + case "@top-left": + case "@top-left-corner": + case "@top-center": + case "@top-right": + case "@top-right-corner": + case "@bottom-left": + case "@bottom-left-corner": + case "@bottom-center": + case "@bottom-right": + case "@bottom-right-corner": + case "@left-top": + case "@left-middle": + case "@left-bottom": + case "@right-top": + case "@right-middle": + case "@right-bottom": + hasBlock = true; + break; + */ + case "@charset": + hasIdentifier = true; + hasBlock = false; + break; + case "@namespace": + hasExpression = true; + hasBlock = false; + break; + case "@keyframes": + hasIdentifier = true; + break; + case "@host": + case "@page": + case "@document": + case "@supports": + hasUnknown = true; + break; + } + + parserInput.commentStore.length = 0; + + if (hasIdentifier) { + value = this.entity(); + if (!value) { + error("expected " + name + " identifier"); + } + } else if (hasExpression) { + value = this.expression(); + if (!value) { + error("expected " + name + " expression"); + } + } else if (hasUnknown) { + value = (parserInput.$re(/^[^{;]+/) || '').trim(); + if (value) { + value = new(tree.Anonymous)(value); + } + } + + if (hasBlock) { + rules = this.blockRuleset(); + } + + if (rules || (!hasBlock && value && parserInput.$char(';'))) { + parserInput.forget(); + return new(tree.Directive)(name, value, rules, index, env.currentFileInfo, + env.dumpLineNumbers ? getDebugInfo(index) : null); + } + + parserInput.restore("directive options not recognised"); + }, + + // + // A Value is a comma-delimited list of Expressions + // + // font-family: Baskerville, Georgia, serif; + // + // In a Rule, a Value represents everything after the `:`, + // and before the `;`. + // + value: function () { + var e, expressions = []; + + do { + e = this.expression(); + if (e) { + expressions.push(e); + if (! parserInput.$char(',')) { break; } + } + } while(e); + + if (expressions.length > 0) { + return new(tree.Value)(expressions); + } + }, + important: function () { + if (parserInput.currentChar() === '!') { + return parserInput.$re(/^! *important/); + } + }, + sub: function () { + var a, e; + + if (parserInput.$char('(')) { + a = this.addition(); + if (a) { + e = new(tree.Expression)([a]); + expectChar(')'); + e.parens = true; + return e; + } + } + }, + multiplication: function () { + var m, a, op, operation, isSpaced; + m = this.operand(); + if (m) { + isSpaced = parserInput.isWhitespace(-1); + while (true) { + if (parserInput.peek(/^\/[*\/]/)) { + break; + } + + parserInput.save(); + + op = parserInput.$char('/') || parserInput.$char('*'); + + if (!op) { parserInput.forget(); break; } + + a = this.operand(); + + if (!a) { parserInput.restore(); break; } + parserInput.forget(); + + m.parensInOp = true; + a.parensInOp = true; + operation = new(tree.Operation)(op, [operation || m, a], isSpaced); + isSpaced = parserInput.isWhitespace(-1); + } + return operation || m; + } + }, + addition: function () { + var m, a, op, operation, isSpaced; + m = this.multiplication(); + if (m) { + isSpaced = parserInput.isWhitespace(-1); + while (true) { + op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-'))); + if (!op) { + break; + } + a = this.multiplication(); + if (!a) { + break; + } + + m.parensInOp = true; + a.parensInOp = true; + operation = new(tree.Operation)(op, [operation || m, a], isSpaced); + isSpaced = parserInput.isWhitespace(-1); + } + return operation || m; + } + }, + conditions: function () { + var a, b, index = parserInput.i, condition; + + a = this.condition(); + if (a) { + while (true) { + if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) { + break; + } + b = this.condition(); + if (!b) { + break; + } + condition = new(tree.Condition)('or', condition || a, b, index); + } + return condition || a; + } + }, + condition: function () { + var entities = this.entities, index = parserInput.i, negate = false, + a, b, c, op; + + if (parserInput.$re(/^not/)) { negate = true; } + expectChar('('); + a = this.addition() || entities.keyword() || entities.quoted(); + if (a) { + op = parserInput.$re(/^(?:>=|<=|=<|[<=>])/); + if (op) { + b = this.addition() || entities.keyword() || entities.quoted(); + if (b) { + c = new(tree.Condition)(op, a, b, index, negate); + } else { + error('expected expression'); + } + } else { + c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); + } + expectChar(')'); + return parserInput.$re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c; + } + }, + + // + // An operand is anything that can be part of an operation, + // such as a Color, or a Variable + // + operand: function () { + var entities = this.entities, negate; + + if (parserInput.peek(/^-[@\(]/)) { + negate = parserInput.$char('-'); + } + + var o = this.sub() || entities.dimension() || + entities.color() || entities.variable() || + entities.call(); + + if (negate) { + o.parensInOp = true; + o = new(tree.Negative)(o); + } + + return o; + }, + + // + // Expressions either represent mathematical operations, + // or white-space delimited Entities. + // + // 1px solid black + // @var * 2 + // + expression: function () { + var entities = [], e, delim; + + do { + e = this.comment(); + if (e) { + entities.push(e); + continue; + } + e = this.addition() || this.entity(); + if (e) { + entities.push(e); + // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here + if (!parserInput.peek(/^\/[\/*]/)) { + delim = parserInput.$char('/'); + if (delim) { + entities.push(new(tree.Anonymous)(delim)); + } + } + } + } while (e); + if (entities.length > 0) { + return new(tree.Expression)(entities); + } + }, + property: function () { + var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); + if (name) { + return name[1]; + } + }, + ruleProperty: function () { + var name = [], index = [], s, k; + + parserInput.save(); + + function match(re) { + var i = parserInput.i, + chunk = parserInput.$re(re); + if (chunk) { + index.push(i); + return name.push(chunk[1]); + } + } + + match(/^(\*?)/); + while (true) { + if (!match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)) { + break; + } + } + + if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) { + parserInput.forget(); + + // at last, we have the complete match now. move forward, + // convert name particles to tree objects and return: + if (name[0] === '') { + name.shift(); + index.shift(); + } + for (k = 0; k < name.length; k++) { + s = name[k]; + name[k] = (s.charAt(0) !== '@') ? + new(tree.Keyword)(s) : + new(tree.Variable)('@' + s.slice(2, -1), + index[k], env.currentFileInfo); + } + return name; + } + parserInput.restore(); + } + } + }; + + parser.getInput = getInput; + parser.getLocation = parserInput.getLocation; + + return parser; +}; +Parser.serializeVars = function(vars) { + var s = ''; + + for (var name in vars) { + if (Object.hasOwnProperty.call(vars, name)) { + var value = vars[name]; + s += ((name[0] === '@') ? '' : '@') + name +': '+ value + + ((('' + value).slice(-1) === ';') ? '' : ';'); + } + } + + return s; +}; + +return Parser; +}; + +},{"../contexts.js":2,"../less-error.js":19,"../source-map-output":25,"../tree/index.js":43,"../visitor/index.js":66,"./imports.js":22,"./parser-input.js":23}],25:[function(require,module,exports){ +module.exports = function (environment) { + + var SourceMapOutput = function (options) { + this._css = []; + this._rootNode = options.rootNode; + this._writeSourceMap = options.writeSourceMap; + this._contentsMap = options.contentsMap; + this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; + this._sourceMapFilename = options.sourceMapFilename; + this._outputFilename = options.outputFilename; + this._sourceMapURL = options.sourceMapURL; + if (options.sourceMapBasepath) { + this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); + } + this._sourceMapRootpath = options.sourceMapRootpath; + this._outputSourceFiles = options.outputSourceFiles; + this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator(); + + if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') { + this._sourceMapRootpath += '/'; + } + + this._lineNumber = 0; + this._column = 0; + }; + + SourceMapOutput.prototype.normalizeFilename = function(filename) { + filename = filename.replace(/\\/g, '/'); + + if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) { + filename = filename.substring(this._sourceMapBasepath.length); + if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') { + filename = filename.substring(1); + } + } + return (this._sourceMapRootpath || "") + filename; + }; + + SourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { + + //ignore adding empty strings + if (!chunk) { + return; + } + + var lines, + sourceLines, + columns, + sourceColumns, + i; + + if (fileInfo) { + var inputSource = this._contentsMap[fileInfo.filename]; + + // remove vars/banner added to the top of the file + if (this._contentsIgnoredCharsMap[fileInfo.filename]) { + // adjust the index + index -= this._contentsIgnoredCharsMap[fileInfo.filename]; + if (index < 0) { index = 0; } + // adjust the source + inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); + } + inputSource = inputSource.substring(0, index); + sourceLines = inputSource.split("\n"); + sourceColumns = sourceLines[sourceLines.length-1]; + } + + lines = chunk.split("\n"); + columns = lines[lines.length-1]; + + if (fileInfo) { + if (!mapLines) { + this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, + original: { line: sourceLines.length, column: sourceColumns.length}, + source: this.normalizeFilename(fileInfo.filename)}); + } else { + for(i = 0; i < lines.length; i++) { + this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, + original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, + source: this.normalizeFilename(fileInfo.filename)}); + } + } + } + + if (lines.length === 1) { + this._column += columns.length; + } else { + this._lineNumber += lines.length - 1; + this._column = columns.length; + } + + this._css.push(chunk); + }; + + SourceMapOutput.prototype.isEmpty = function() { + return this._css.length === 0; + }; + + SourceMapOutput.prototype.toCSS = function(env) { + this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); + + if (this._outputSourceFiles) { + for(var filename in this._contentsMap) { + if (this._contentsMap.hasOwnProperty(filename)) + { + var source = this._contentsMap[filename]; + if (this._contentsIgnoredCharsMap[filename]) { + source = source.slice(this._contentsIgnoredCharsMap[filename]); + } + this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); + } + } + } + + this._rootNode.genCSS(env, this); + + if (this._css.length > 0) { + var sourceMapURL, + sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); + + if (this._sourceMapURL) { + sourceMapURL = this._sourceMapURL; + } else if (this._sourceMapFilename) { + sourceMapURL = this.normalizeFilename(this._sourceMapFilename); + } + + if (this._writeSourceMap) { + this._writeSourceMap(sourceMapContent); + } else { + sourceMapURL = "data:application/json;base64," + environment.encodeBase64(sourceMapContent); + } + + if (sourceMapURL) { + this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */"); + } + } + + return this._css.join(''); + }; + + return SourceMapOutput; +}; + +},{}],26:[function(require,module,exports){ +var Node = require("./node.js"); + +var Alpha = function (val) { + this.value = val; +}; +Alpha.prototype = new Node(); +Alpha.prototype.type = "Alpha"; + +Alpha.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Alpha.prototype.eval = function (env) { + if (this.value.eval) { return new Alpha(this.value.eval(env)); } + return this; +}; +Alpha.prototype.genCSS = function (env, output) { + output.add("alpha(opacity="); + + if (this.value.genCSS) { + this.value.genCSS(env, output); + } else { + output.add(this.value); + } + + output.add(")"); +}; + +module.exports = Alpha; + +},{"./node.js":51}],27:[function(require,module,exports){ +var Node = require("./node.js"); + +var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike) { + this.value = value; + this.index = index; + this.mapLines = mapLines; + this.currentFileInfo = currentFileInfo; + this.rulesetLike = (typeof rulesetLike === 'undefined')? false : rulesetLike; +}; +Anonymous.prototype = new Node(); +Anonymous.prototype.type = "Anonymous"; +Anonymous.prototype.eval = function () { + return new Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines, this.rulesetLike); +}; +Anonymous.prototype.compare = function (x) { + if (!x.toCSS) { + return -1; + } + + var left = this.toCSS(), + right = x.toCSS(); + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; +}; +Anonymous.prototype.isRulesetLike = function() { + return this.rulesetLike; +}; +Anonymous.prototype.genCSS = function (env, output) { + output.add(this.value, this.currentFileInfo, this.index, this.mapLines); +}; +module.exports = Anonymous; + +},{"./node.js":51}],28:[function(require,module,exports){ +var Node = require("./node.js"); + +var Assignment = function (key, val) { + this.key = key; + this.value = val; +}; + +Assignment.prototype = new Node(); +Assignment.prototype.type = "Assignment"; +Assignment.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Assignment.prototype.eval = function (env) { + if (this.value.eval) { + return new(Assignment)(this.key, this.value.eval(env)); + } + return this; +}; +Assignment.prototype.genCSS = function (env, output) { + output.add(this.key + '='); + if (this.value.genCSS) { + this.value.genCSS(env, output); + } else { + output.add(this.value); + } +}; +module.exports = Assignment; + + +},{"./node.js":51}],29:[function(require,module,exports){ +var Node = require("./node.js"); + +var Attribute = function (key, op, value) { + this.key = key; + this.op = op; + this.value = value; +}; +Attribute.prototype = new Node(); +Attribute.prototype.type = "Attribute"; +Attribute.prototype.eval = function (env) { + return new(Attribute)(this.key.eval ? this.key.eval(env) : this.key, + this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value); +}; +Attribute.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env)); +}; +Attribute.prototype.toCSS = function (env) { + var value = this.key.toCSS ? this.key.toCSS(env) : this.key; + + if (this.op) { + value += this.op; + value += (this.value.toCSS ? this.value.toCSS(env) : this.value); + } + + return '[' + value + ']'; +}; +module.exports = Attribute; + +},{"./node.js":51}],30:[function(require,module,exports){ +var Node = require("./node.js"), + FunctionCaller = require("../functions/function-caller.js"); +// +// A function call node. +// +var Call = function (name, args, index, currentFileInfo) { + this.name = name; + this.args = args; + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Call.prototype = new Node(); +Call.prototype.type = "Call"; +Call.prototype.accept = function (visitor) { + if (this.args) { + this.args = visitor.visitArray(this.args); + } +}; +// +// When evaluating a function call, +// we either find the function in `less.functions` [1], +// in which case we call it, passing the evaluated arguments, +// if this returns null or we cannot find the function, we +// simply print it out as it appeared originally [2]. +// +// The *functions.js* file contains the built-in functions. +// +// The reason why we evaluate the arguments, is in the case where +// we try to pass a variable to a function, like: `saturate(@color)`. +// The function should receive the value, not the variable. +// +Call.prototype.eval = function (env) { + var args = this.args.map(function (a) { return a.eval(env); }), + result, funcCaller = new FunctionCaller(this.name, env, this.currentFileInfo); + + if (funcCaller.isValid()) { // 1. + try { + result = funcCaller.call(args); + if (result != null) { + return result; + } + } catch (e) { + throw { type: e.type || "Runtime", + message: "error evaluating function `" + this.name + "`" + + (e.message ? ': ' + e.message : ''), + index: this.index, filename: this.currentFileInfo.filename }; + } + } + + return new Call(this.name, args, this.index, this.currentFileInfo); +}; +Call.prototype.genCSS = function (env, output) { + output.add(this.name + "(", this.currentFileInfo, this.index); + + for(var i = 0; i < this.args.length; i++) { + this.args[i].genCSS(env, output); + if (i + 1 < this.args.length) { + output.add(", "); + } + } + + output.add(")"); +}; +module.exports = Call; + +},{"../functions/function-caller.js":11,"./node.js":51}],31:[function(require,module,exports){ +var Node = require("./node.js"), + colors = require("../data/colors.js"); + +// +// RGB Colors - #ff0014, #eee +// +var Color = function (rgb, a) { + // + // The end goal here, is to parse the arguments + // into an integer triplet, such as `128, 255, 0` + // + // This facilitates operations and conversions. + // + if (Array.isArray(rgb)) { + this.rgb = rgb; + } else if (rgb.length == 6) { + this.rgb = rgb.match(/.{2}/g).map(function (c) { + return parseInt(c, 16); + }); + } else { + this.rgb = rgb.split('').map(function (c) { + return parseInt(c + c, 16); + }); + } + this.alpha = typeof(a) === 'number' ? a : 1; +}; + +Color.prototype = new Node(); +Color.prototype.type = "Color"; + +function clamp(v, max) { + return Math.min(Math.max(v, 0), max); +} + +function toHex(v) { + return '#' + v.map(function (c) { + c = clamp(Math.round(c), 255); + return (c < 16 ? '0' : '') + c.toString(16); + }).join(''); +} + +Color.prototype.luma = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255; + + r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4); + g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4); + b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4); + + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +}; +Color.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env)); +}; +Color.prototype.toCSS = function (env, doNotCompress) { + var compress = env && env.compress && !doNotCompress, color, alpha; + + // `keyword` is set if this color was originally + // converted from a named color string so we need + // to respect this and try to output named color too. + if (this.keyword) { + return this.keyword; + } + + // If we have some transparency, the only way to represent it + // is via `rgba`. Otherwise, we use the hex representation, + // which has better compatibility with older browsers. + // Values are capped between `0` and `255`, rounded and zero-padded. + alpha = this.fround(env, this.alpha); + if (alpha < 1) { + return "rgba(" + this.rgb.map(function (c) { + return clamp(Math.round(c), 255); + }).concat(clamp(alpha, 1)) + .join(',' + (compress ? '' : ' ')) + ")"; + } + + color = this.toRGB(); + + if (compress) { + var splitcolor = color.split(''); + + // Convert color to short format + if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { + color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; + } + } + + return color; +}; + +// +// Operations have to be done per-channel, if not, +// channels will spill onto each other. Once we have +// our result, in the form of an integer triplet, +// we create a new Color node to hold the result. +// +Color.prototype.operate = function (env, op, other) { + var rgb = []; + var alpha = this.alpha * (1 - other.alpha) + other.alpha; + for (var c = 0; c < 3; c++) { + rgb[c] = this._operate(env, op, this.rgb[c], other.rgb[c]); + } + return new(Color)(rgb, alpha); +}; +Color.prototype.toRGB = function () { + return toHex(this.rgb); +}; +Color.prototype.toHSL = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255, + a = this.alpha; + + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, l = (max + min) / 2, d = max - min; + + if (max === min) { + h = s = 0; + } else { + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h * 360, s: s, l: l, a: a }; +}; +//Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript +Color.prototype.toHSV = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255, + a = this.alpha; + + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, v = max; + + var d = max - min; + if (max === 0) { + s = 0; + } else { + s = d / max; + } + + if (max === min) { + h = 0; + } else { + switch(max){ + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h * 360, s: s, v: v, a: a }; +}; +Color.prototype.toARGB = function () { + return toHex([this.alpha * 255].concat(this.rgb)); +}; +Color.prototype.compare = function (x) { + if (!x.rgb) { + return -1; + } + + return (x.rgb[0] === this.rgb[0] && + x.rgb[1] === this.rgb[1] && + x.rgb[2] === this.rgb[2] && + x.alpha === this.alpha) ? 0 : -1; +}; + +Color.fromKeyword = function(keyword) { + var c, key = keyword.toLowerCase(); + if (colors.hasOwnProperty(key)) { + c = new(Color)(colors[key].slice(1)); + } + else if (key === "transparent") { + c = new(Color)([0, 0, 0], 0); + } + + if (c) { + c.keyword = keyword; + return c; + } +}; +module.exports = Color; + +},{"../data/colors.js":3,"./node.js":51}],32:[function(require,module,exports){ +var Node = require("./node.js"); + +var Combinator = function (value) { + if (value === ' ') { + this.value = ' '; + } else { + this.value = value ? value.trim() : ""; + } +}; +Combinator.prototype = new Node(); +Combinator.prototype.type = "Combinator"; +var _noSpaceCombinators = { + '': true, + ' ': true, + '|': true +}; +Combinator.prototype.genCSS = function (env, output) { + var spaceOrEmpty = (env.compress || _noSpaceCombinators[this.value]) ? '' : ' '; + output.add(spaceOrEmpty + this.value + spaceOrEmpty); +}; +module.exports = Combinator; + +},{"./node.js":51}],33:[function(require,module,exports){ +var Node = require("./node.js"), + getDebugInfo = require("./debug-info.js"); + +var Comment = function (value, isLineComment, index, currentFileInfo) { + this.value = value; + this.isLineComment = isLineComment; + this.currentFileInfo = currentFileInfo; +}; +Comment.prototype = new Node(); +Comment.prototype.type = "Comment"; +Comment.prototype.genCSS = function (env, output) { + if (this.debugInfo) { + output.add(getDebugInfo(env, this), this.currentFileInfo, this.index); + } + output.add(this.value); +}; +Comment.prototype.isSilent = function(env) { + var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced), + isCompressed = env.compress && this.value[2] !== "!"; + return this.isLineComment || isReference || isCompressed; +}; +Comment.prototype.markReferenced = function () { + this.isReferenced = true; +}; +Comment.prototype.isRulesetLike = function(root) { + return Boolean(root); +}; +module.exports = Comment; + +},{"./debug-info.js":35,"./node.js":51}],34:[function(require,module,exports){ +var Node = require("./node.js"); + +var Condition = function (op, l, r, i, negate) { + this.op = op.trim(); + this.lvalue = l; + this.rvalue = r; + this.index = i; + this.negate = negate; +}; +Condition.prototype = new Node(); +Condition.prototype.type = "Condition"; +Condition.prototype.accept = function (visitor) { + this.lvalue = visitor.visit(this.lvalue); + this.rvalue = visitor.visit(this.rvalue); +}; +Condition.prototype.eval = function (env) { + var a = this.lvalue.eval(env), + b = this.rvalue.eval(env); + + var i = this.index, result; + + result = (function (op) { + switch (op) { + case 'and': + return a && b; + case 'or': + return a || b; + default: + if (a.compare) { + result = a.compare(b); + } else if (b.compare) { + result = b.compare(a); + } else { + throw { type: "Type", + message: "Unable to perform comparison", + index: i }; + } + switch (result) { + case -1: return op === '<' || op === '=<' || op === '<='; + case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; + case 1: return op === '>' || op === '>='; + } + } + })(this.op); + return this.negate ? !result : result; +}; +module.exports = Condition; + +},{"./node.js":51}],35:[function(require,module,exports){ +var debugInfo = function(env, ctx, lineSeperator) { + var result=""; + if (env.dumpLineNumbers && !env.compress) { + switch(env.dumpLineNumbers) { + case 'comments': + result = debugInfo.asComment(ctx); + break; + case 'mediaquery': + result = debugInfo.asMediaQuery(ctx); + break; + case 'all': + result = debugInfo.asComment(ctx) + (lineSeperator || "") + debugInfo.asMediaQuery(ctx); + break; + } + } + return result; +}; + +debugInfo.asComment = function(ctx) { + return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; +}; + +debugInfo.asMediaQuery = function(ctx) { + return '@media -sass-debug-info{filename{font-family:' + + ('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) { + if (a == '\\') { + a = '\/'; + } + return '\\' + a; + }) + + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; +}; + +module.exports = debugInfo; + +},{}],36:[function(require,module,exports){ +var Node = require("./node.js"), + contexts = require("../contexts.js"); + +var DetachedRuleset = function (ruleset, frames) { + this.ruleset = ruleset; + this.frames = frames; +}; +DetachedRuleset.prototype = new Node(); +DetachedRuleset.prototype.type = "DetachedRuleset"; +DetachedRuleset.prototype.evalFirst = true; +DetachedRuleset.prototype.accept = function (visitor) { + this.ruleset = visitor.visit(this.ruleset); +}; +DetachedRuleset.prototype.eval = function (env) { + var frames = this.frames || env.frames.slice(0); + return new DetachedRuleset(this.ruleset, frames); +}; +DetachedRuleset.prototype.callEval = function (env) { + return this.ruleset.eval(this.frames ? new(contexts.evalEnv)(env, this.frames.concat(env.frames)) : env); +}; +module.exports = DetachedRuleset; + +},{"../contexts.js":2,"./node.js":51}],37:[function(require,module,exports){ +var Node = require("./node.js"), + unitConversions = require("../data/unit-conversions.js"), + Unit = require("./unit.js"), + Color = require("./color.js"); + +// +// A number with a unit +// +var Dimension = function (value, unit) { + this.value = parseFloat(value); + this.unit = (unit && unit instanceof Unit) ? unit : + new(Unit)(unit ? [unit] : undefined); +}; + +Dimension.prototype = new Node(); +Dimension.prototype.type = "Dimension"; +Dimension.prototype.accept = function (visitor) { + this.unit = visitor.visit(this.unit); +}; +Dimension.prototype.eval = function (env) { + return this; +}; +Dimension.prototype.toColor = function () { + return new(Color)([this.value, this.value, this.value]); +}; +Dimension.prototype.genCSS = function (env, output) { + if ((env && env.strictUnits) && !this.unit.isSingular()) { + throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString()); + } + + var value = this.fround(env, this.value), + strValue = String(value); + + if (value !== 0 && value < 0.000001 && value > -0.000001) { + // would be output 1e-6 etc. + strValue = value.toFixed(20).replace(/0+$/, ""); + } + + if (env && env.compress) { + // Zero values doesn't need a unit + if (value === 0 && this.unit.isLength()) { + output.add(strValue); + return; + } + + // Float values doesn't need a leading zero + if (value > 0 && value < 1) { + strValue = (strValue).substr(1); + } + } + + output.add(strValue); + this.unit.genCSS(env, output); +}; + +// In an operation between two Dimensions, +// we default to the first Dimension's unit, +// so `1px + 2` will yield `3px`. +Dimension.prototype.operate = function (env, op, other) { + /*jshint noempty:false */ + var value = this._operate(env, op, this.value, other.value), + unit = this.unit.clone(); + + if (op === '+' || op === '-') { + if (unit.numerator.length === 0 && unit.denominator.length === 0) { + unit.numerator = other.unit.numerator.slice(0); + unit.denominator = other.unit.denominator.slice(0); + } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { + // do nothing + } else { + other = other.convertTo(this.unit.usedUnits()); + + if(env.strictUnits && other.unit.toString() !== unit.toString()) { + throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() + + "' and '" + other.unit.toString() + "'."); + } + + value = this._operate(env, op, this.value, other.value); + } + } else if (op === '*') { + unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); + unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); + unit.cancel(); + } else if (op === '/') { + unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); + unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); + unit.cancel(); + } + return new(Dimension)(value, unit); +}; +Dimension.prototype.compare = function (other) { + if (other instanceof Dimension) { + var a, b, + aValue, bValue; + + if (this.unit.isEmpty() || other.unit.isEmpty()) { + a = this; + b = other; + } else { + a = this.unify(); + b = other.unify(); + if (a.unit.compare(b.unit) !== 0) { + return -1; + } + } + aValue = a.value; + bValue = b.value; + + if (bValue > aValue) { + return -1; + } else if (bValue < aValue) { + return 1; + } else { + return 0; + } + } else { + return -1; + } +}; +Dimension.prototype.unify = function () { + return this.convertTo({ length: 'px', duration: 's', angle: 'rad' }); +}; +Dimension.prototype.convertTo = function (conversions) { + var value = this.value, unit = this.unit.clone(), + i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; + + if (typeof conversions === 'string') { + for(i in unitConversions) { + if (unitConversions[i].hasOwnProperty(conversions)) { + derivedConversions = {}; + derivedConversions[i] = conversions; + } + } + conversions = derivedConversions; + } + applyUnit = function (atomicUnit, denominator) { + /*jshint loopfunc:true */ + if (group.hasOwnProperty(atomicUnit)) { + if (denominator) { + value = value / (group[atomicUnit] / group[targetUnit]); + } else { + value = value * (group[atomicUnit] / group[targetUnit]); + } + + return targetUnit; + } + + return atomicUnit; + }; + + for (groupName in conversions) { + if (conversions.hasOwnProperty(groupName)) { + targetUnit = conversions[groupName]; + group = unitConversions[groupName]; + + unit.map(applyUnit); + } + } + + unit.cancel(); + + return new(Dimension)(value, unit); +}; +module.exports = Dimension; + +},{"../data/unit-conversions.js":5,"./color.js":31,"./node.js":51,"./unit.js":60}],38:[function(require,module,exports){ +var Node = require("./node.js"), + Ruleset = require("./ruleset.js"); + +var Directive = function (name, value, rules, index, currentFileInfo, debugInfo) { + this.name = name; + this.value = value; + if (rules) { + this.rules = rules; + this.rules.allowImports = true; + } + this.index = index; + this.currentFileInfo = currentFileInfo; + this.debugInfo = debugInfo; +}; + +Directive.prototype = new Node(); +Directive.prototype.type = "Directive"; +Directive.prototype.accept = function (visitor) { + var value = this.value, rules = this.rules; + if (rules) { + rules = visitor.visit(rules); + } + if (value) { + value = visitor.visit(value); + } +}; +Directive.prototype.isRulesetLike = function() { + return this.rules || !this.isCharset(); +}; +Directive.prototype.isCharset = function() { + return "@charset" === this.name; +}; +Directive.prototype.genCSS = function (env, output) { + var value = this.value, rules = this.rules; + output.add(this.name, this.currentFileInfo, this.index); + if (value) { + output.add(' '); + value.genCSS(env, output); + } + if (rules) { + this.outputRuleset(env, output, [rules]); + } else { + output.add(';'); + } +}; +Directive.prototype.eval = function (env) { + var value = this.value, rules = this.rules; + if (value) { + value = value.eval(env); + } + if (rules) { + rules = rules.eval(env); + rules.root = true; + } + return new(Directive)(this.name, value, rules, + this.index, this.currentFileInfo, this.debugInfo); +}; +Directive.prototype.variable = function (name) { if (this.rules) return Ruleset.prototype.variable.call(this.rules, name); }; +Directive.prototype.find = function () { if (this.rules) return Ruleset.prototype.find.apply(this.rules, arguments); }; +Directive.prototype.rulesets = function () { if (this.rules) return Ruleset.prototype.rulesets.apply(this.rules); }; +Directive.prototype.markReferenced = function () { + var i, rules; + this.isReferenced = true; + if (this.rules) { + rules = this.rules.rules; + for (i = 0; i < rules.length; i++) { + if (rules[i].markReferenced) { + rules[i].markReferenced(); + } + } + } +}; +Directive.prototype.outputRuleset = function (env, output, rules) { + var ruleCnt = rules.length, i; + env.tabLevel = (env.tabLevel | 0) + 1; + + // Compressed + if (env.compress) { + output.add('{'); + for (i = 0; i < ruleCnt; i++) { + rules[i].genCSS(env, output); + } + output.add('}'); + env.tabLevel--; + return; + } + + // Non-compressed + var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " "; + if (!ruleCnt) { + output.add(" {" + tabSetStr + '}'); + } else { + output.add(" {" + tabRuleStr); + rules[0].genCSS(env, output); + for (i = 1; i < ruleCnt; i++) { + output.add(tabRuleStr); + rules[i].genCSS(env, output); + } + output.add(tabSetStr + '}'); + } + + env.tabLevel--; +}; +module.exports = Directive; + +},{"./node.js":51,"./ruleset.js":57}],39:[function(require,module,exports){ +var Node = require("./node.js"), + Combinator = require("./combinator.js"); + +var Element = function (combinator, value, index, currentFileInfo) { + this.combinator = combinator instanceof Combinator ? + combinator : new(Combinator)(combinator); + + if (typeof(value) === 'string') { + this.value = value.trim(); + } else if (value) { + this.value = value; + } else { + this.value = ""; + } + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Element.prototype = new Node(); +Element.prototype.type = "Element"; +Element.prototype.accept = function (visitor) { + var value = this.value; + this.combinator = visitor.visit(this.combinator); + if (typeof value === "object") { + this.value = visitor.visit(value); + } +}; +Element.prototype.eval = function (env) { + return new(Element)(this.combinator, + this.value.eval ? this.value.eval(env) : this.value, + this.index, + this.currentFileInfo); +}; +Element.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env), this.currentFileInfo, this.index); +}; +Element.prototype.toCSS = function (env) { + var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); + if (value === '' && this.combinator.value.charAt(0) === '&') { + return ''; + } else { + return this.combinator.toCSS(env || {}) + value; + } +}; +module.exports = Element; + +},{"./combinator.js":32,"./node.js":51}],40:[function(require,module,exports){ +var Node = require("./node.js"), + Paren = require("./paren.js"), + Comment = require("./comment.js"); + +var Expression = function (value) { this.value = value; }; +Expression.prototype = new Node(); +Expression.prototype.type = "Expression"; +Expression.prototype.accept = function (visitor) { + if (this.value) { + this.value = visitor.visitArray(this.value); + } +}; +Expression.prototype.eval = function (env) { + var returnValue, + inParenthesis = this.parens && !this.parensInOp, + doubleParen = false; + if (inParenthesis) { + env.inParenthesis(); + } + if (this.value.length > 1) { + returnValue = new(Expression)(this.value.map(function (e) { + return e.eval(env); + })); + } else if (this.value.length === 1) { + if (this.value[0].parens && !this.value[0].parensInOp) { + doubleParen = true; + } + returnValue = this.value[0].eval(env); + } else { + returnValue = this; + } + if (inParenthesis) { + env.outOfParenthesis(); + } + if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) { + returnValue = new(Paren)(returnValue); + } + return returnValue; +}; +Expression.prototype.genCSS = function (env, output) { + for(var i = 0; i < this.value.length; i++) { + this.value[i].genCSS(env, output); + if (i + 1 < this.value.length) { + output.add(" "); + } + } +}; +Expression.prototype.throwAwayComments = function () { + this.value = this.value.filter(function(v) { + return !(v instanceof Comment); + }); +}; +module.exports = Expression; + +},{"./comment.js":33,"./node.js":51,"./paren.js":53}],41:[function(require,module,exports){ +var Node = require("./node.js"); + +var Extend = function Extend(selector, option, index) { + this.selector = selector; + this.option = option; + this.index = index; + this.object_id = Extend.next_id++; + this.parent_ids = [this.object_id]; + + switch(option) { + case "all": + this.allowBefore = true; + this.allowAfter = true; + break; + default: + this.allowBefore = false; + this.allowAfter = false; + break; + } +}; +Extend.next_id = 0; + +Extend.prototype = new Node(); +Extend.prototype.type = "Extend"; +Extend.prototype.accept = function (visitor) { + this.selector = visitor.visit(this.selector); +}; +Extend.prototype.eval = function (env) { + return new(Extend)(this.selector.eval(env), this.option, this.index); +}; +Extend.prototype.clone = function (env) { + return new(Extend)(this.selector, this.option, this.index); +}; +Extend.prototype.findSelfSelectors = function (selectors) { + var selfElements = [], + i, + selectorElements; + + for(i = 0; i < selectors.length; i++) { + selectorElements = selectors[i].elements; + // duplicate the logic in genCSS function inside the selector node. + // future TODO - move both logics into the selector joiner visitor + if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { + selectorElements[0].combinator.value = ' '; + } + selfElements = selfElements.concat(selectors[i].elements); + } + + this.selfSelectors = [{ elements: selfElements }]; +}; +module.exports = Extend; + +},{"./node.js":51}],42:[function(require,module,exports){ +var Node = require("./node.js"), + Media = require("./media.js"), + URL = require("./url.js"), + Quoted = require("./quoted.js"), + Ruleset = require("./ruleset.js"), + Anonymous = require("./anonymous.js"); + +// +// CSS @import node +// +// The general strategy here is that we don't want to wait +// for the parsing to be completed, before we start importing +// the file. That's because in the context of a browser, +// most of the time will be spent waiting for the server to respond. +// +// On creation, we push the import path to our import queue, though +// `import,push`, we also pass it a callback, which it'll call once +// the file has been fetched, and parsed. +// +var Import = function (path, features, options, index, currentFileInfo) { + this.options = options; + this.index = index; + this.path = path; + this.features = features; + this.currentFileInfo = currentFileInfo; + + if (this.options.less !== undefined || this.options.inline) { + this.css = !this.options.less || this.options.inline; + } else { + var pathValue = this.getPath(); + if (pathValue && /css([\?;].*)?$/.test(pathValue)) { + this.css = true; + } + } +}; + +// +// The actual import node doesn't return anything, when converted to CSS. +// The reason is that it's used at the evaluation stage, so that the rules +// it imports can be treated like any other rules. +// +// In `eval`, we make sure all Import nodes get evaluated, recursively, so +// we end up with a flat structure, which can easily be imported in the parent +// ruleset. +// +Import.prototype = new Node(); +Import.prototype.type = "Import"; +Import.prototype.accept = function (visitor) { + if (this.features) { + this.features = visitor.visit(this.features); + } + this.path = visitor.visit(this.path); + if (!this.options.inline && this.root) { + this.root = visitor.visit(this.root); + } +}; +Import.prototype.genCSS = function (env, output) { + if (this.css) { + output.add("@import ", this.currentFileInfo, this.index); + this.path.genCSS(env, output); + if (this.features) { + output.add(" "); + this.features.genCSS(env, output); + } + output.add(';'); + } +}; +Import.prototype.getPath = function () { + if (this.path instanceof Quoted) { + var path = this.path.value; + return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less'; + } else if (this.path instanceof URL) { + return this.path.value.value; + } + return null; +}; +Import.prototype.evalForImport = function (env) { + return new(Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo); +}; +Import.prototype.evalPath = function (env) { + var path = this.path.eval(env); + var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; + + if (!(path instanceof URL)) { + if (rootpath) { + var pathValue = path.value; + // Add the base path if the import is relative + if (pathValue && env.isPathRelative(pathValue)) { + path.value = rootpath +pathValue; + } + } + path.value = env.normalizePath(path.value); + } + + return path; +}; +Import.prototype.eval = function (env) { + var ruleset, features = this.features && this.features.eval(env); + + if (this.skip) { + if (typeof this.skip === "function") { + this.skip = this.skip(); + } + if (this.skip) { + return []; + } + } + + if (this.options.inline) { + //todo needs to reference css file not import + var contents = new(Anonymous)(this.root, 0, {filename: this.importedFilename}, true, true); + return this.features ? new(Media)([contents], this.features.value) : [contents]; + } else if (this.css) { + var newImport = new(Import)(this.evalPath(env), features, this.options, this.index); + if (!newImport.css && this.error) { + throw this.error; + } + return newImport; + } else { + ruleset = new(Ruleset)(null, this.root.rules.slice(0)); + + ruleset.evalImports(env); + + return this.features ? new(Media)(ruleset.rules, this.features.value) : ruleset.rules; + } +}; +module.exports = Import; + +},{"./anonymous.js":27,"./media.js":47,"./node.js":51,"./quoted.js":54,"./ruleset.js":57,"./url.js":61}],43:[function(require,module,exports){ +var tree = {}; + +tree.Alpha = require('./alpha'); +tree.Color = require('./color'); +tree.Directive = require('./directive'); +tree.DetachedRuleset = require('./detached-ruleset'); +tree.Operation = require('./operation'); +tree.Dimension = require('./dimension'); +tree.Unit = require('./unit'); +tree.Keyword = require('./keyword'); +tree.Variable = require('./variable'); +tree.Ruleset = require('./ruleset'); +tree.Element = require('./element'); +tree.Attribute = require('./attribute'); +tree.Combinator = require('./combinator'); +tree.Selector = require('./selector'); +tree.Quoted = require('./quoted'); +tree.Expression = require('./expression'); +tree.Rule = require('./rule'); +tree.Call = require('./call'); +tree.URL = require('./url'); +tree.Import = require('./import'); +tree.mixin = { + Call: require('./mixin-call'), + Definition: require('./mixin-definition') +}; +tree.Comment = require('./comment'); +tree.Anonymous = require('./anonymous'); +tree.Value = require('./value'); +tree.JavaScript = require('./javascript'); +tree.Assignment = require('./assignment'); +tree.Condition = require('./condition'); +tree.Paren = require('./paren'); +tree.Media = require('./media'); +tree.UnicodeDescriptor = require('./unicode-descriptor'); +tree.Negative = require('./negative'); +tree.Extend = require('./extend'); +tree.RulesetCall = require('./ruleset-call'); + +module.exports = tree; + +},{"./alpha":26,"./anonymous":27,"./assignment":28,"./attribute":29,"./call":30,"./color":31,"./combinator":32,"./comment":33,"./condition":34,"./detached-ruleset":36,"./dimension":37,"./directive":38,"./element":39,"./expression":40,"./extend":41,"./import":42,"./javascript":44,"./keyword":46,"./media":47,"./mixin-call":48,"./mixin-definition":49,"./negative":50,"./operation":52,"./paren":53,"./quoted":54,"./rule":55,"./ruleset":57,"./ruleset-call":56,"./selector":58,"./unicode-descriptor":59,"./unit":60,"./url":61,"./value":62,"./variable":63}],44:[function(require,module,exports){ +var JsEvalNode = require("./js-eval-node.js"), + Dimension = require("./dimension.js"), + Quoted = require("./quoted.js"), + Anonymous = require("./anonymous.js"); + +var JavaScript = function (string, index, escaped) { + this.escaped = escaped; + this.expression = string; + this.index = index; +}; +JavaScript.prototype = new JsEvalNode(); +JavaScript.prototype.type = "JavaScript"; +JavaScript.prototype.eval = function(env) { + var result = this.evaluateJavaScript(this.expression, env); + + if (typeof(result) === 'number') { + return new(Dimension)(result); + } else if (typeof(result) === 'string') { + return new(Quoted)('"' + result + '"', result, this.escaped, this.index); + } else if (Array.isArray(result)) { + return new(Anonymous)(result.join(', ')); + } else { + return new(Anonymous)(result); + } +}; + +module.exports = JavaScript; + +},{"./anonymous.js":27,"./dimension.js":37,"./js-eval-node.js":45,"./quoted.js":54}],45:[function(require,module,exports){ +var Node = require("./node.js"), + Variable = require("./variable.js"); + +var jsEvalNode = function() { +}; +jsEvalNode.prototype = new Node(); + +jsEvalNode.prototype.evaluateJavaScript = function (expression, env) { + var result, + that = this, + context = {}; + + if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) { + throw { message: "You are using JavaScript, which has been disabled." , + index: this.index }; + } + + expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { + return that.jsify(new(Variable)('@' + name, that.index).eval(env)); + }); + + try { + expression = new(Function)('return (' + expression + ')'); + } catch (e) { + throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" , + index: this.index }; + } + + var variables = env.frames[0].variables(); + for (var k in variables) { + if (variables.hasOwnProperty(k)) { + /*jshint loopfunc:true */ + context[k.slice(1)] = { + value: variables[k].value, + toJS: function () { + return this.value.eval(env).toCSS(); + } + }; + } + } + + try { + result = expression.call(context); + } catch (e) { + throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" , + index: this.index }; + } + return result; +}; +jsEvalNode.prototype.jsify = function (obj) { + if (Array.isArray(obj.value) && (obj.value.length > 1)) { + return '[' + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + ']'; + } else { + return obj.toCSS(); + } +}; + +module.exports = jsEvalNode; + +},{"./node.js":51,"./variable.js":63}],46:[function(require,module,exports){ +var Node = require("./node.js"); + +var Keyword = function (value) { this.value = value; }; +Keyword.prototype = new Node(); +Keyword.prototype.type = "Keyword"; +Keyword.prototype.genCSS = function (env, output) { + if (this.value === '%') { throw { type: "Syntax", message: "Invalid % without number" }; } + output.add(this.value); +}; +Keyword.prototype.compare = function (other) { + if (other instanceof Keyword) { + return other.value === this.value ? 0 : 1; + } else { + return -1; + } +}; + +Keyword.True = new(Keyword)('true'); +Keyword.False = new(Keyword)('false'); + +module.exports = Keyword; + +},{"./node.js":51}],47:[function(require,module,exports){ +var Ruleset = require("./ruleset.js"), + Value = require("./value.js"), + Element = require("./element.js"), + Selector = require("./selector.js"), + Anonymous = require("./anonymous.js"), + Expression = require("./expression.js"), + Directive = require("./directive.js"); + +var Media = function (value, features, index, currentFileInfo) { + this.index = index; + this.currentFileInfo = currentFileInfo; + + var selectors = this.emptySelectors(); + + this.features = new(Value)(features); + this.rules = [new(Ruleset)(selectors, value)]; + this.rules[0].allowImports = true; +}; +Media.prototype = new Directive(); +Media.prototype.type = "Media"; +Media.prototype.isRulesetLike = true; +Media.prototype.accept = function (visitor) { + if (this.features) { + this.features = visitor.visit(this.features); + } + if (this.rules) { + this.rules = visitor.visitArray(this.rules); + } +}; +Media.prototype.genCSS = function (env, output) { + output.add('@media ', this.currentFileInfo, this.index); + this.features.genCSS(env, output); + this.outputRuleset(env, output, this.rules); +}; +Media.prototype.eval = function (env) { + if (!env.mediaBlocks) { + env.mediaBlocks = []; + env.mediaPath = []; + } + + var media = new(Media)(null, [], this.index, this.currentFileInfo); + if(this.debugInfo) { + this.rules[0].debugInfo = this.debugInfo; + media.debugInfo = this.debugInfo; + } + var strictMathBypass = false; + if (!env.strictMath) { + strictMathBypass = true; + env.strictMath = true; + } + try { + media.features = this.features.eval(env); + } + finally { + if (strictMathBypass) { + env.strictMath = false; + } + } + + env.mediaPath.push(media); + env.mediaBlocks.push(media); + + env.frames.unshift(this.rules[0]); + media.rules = [this.rules[0].eval(env)]; + env.frames.shift(); + + env.mediaPath.pop(); + + return env.mediaPath.length === 0 ? media.evalTop(env) : + media.evalNested(env); +}; +//TODO merge with directive +Media.prototype.variable = function (name) { return Ruleset.prototype.variable.call(this.rules[0], name); }; +Media.prototype.find = function () { return Ruleset.prototype.find.apply(this.rules[0], arguments); }; +Media.prototype.rulesets = function () { return Ruleset.prototype.rulesets.apply(this.rules[0]); }; +Media.prototype.emptySelectors = function() { + var el = new(Element)('', '&', this.index, this.currentFileInfo), + sels = [new(Selector)([el], null, null, this.index, this.currentFileInfo)]; + sels[0].mediaEmpty = true; + return sels; +}; +Media.prototype.markReferenced = function () { + var i, rules = this.rules[0].rules; + this.rules[0].markReferenced(); + this.isReferenced = true; + for (i = 0; i < rules.length; i++) { + if (rules[i].markReferenced) { + rules[i].markReferenced(); + } + } +}; +Media.prototype.evalTop = function (env) { + var result = this; + + // Render all dependent Media blocks. + if (env.mediaBlocks.length > 1) { + var selectors = this.emptySelectors(); + result = new(Ruleset)(selectors, env.mediaBlocks); + result.multiMedia = true; + } + + delete env.mediaBlocks; + delete env.mediaPath; + + return result; +}; +Media.prototype.evalNested = function (env) { + var i, value, + path = env.mediaPath.concat([this]); + + // Extract the media-query conditions separated with `,` (OR). + for (i = 0; i < path.length; i++) { + value = path[i].features instanceof Value ? + path[i].features.value : path[i].features; + path[i] = Array.isArray(value) ? value : [value]; + } + + // Trace all permutations to generate the resulting media-query. + // + // (a, b and c) with nested (d, e) -> + // a and d + // a and e + // b and c and d + // b and c and e + this.features = new(Value)(this.permute(path).map(function (path) { + path = path.map(function (fragment) { + return fragment.toCSS ? fragment : new(Anonymous)(fragment); + }); + + for(i = path.length - 1; i > 0; i--) { + path.splice(i, 0, new(Anonymous)("and")); + } + + return new(Expression)(path); + })); + + // Fake a tree-node that doesn't output anything. + return new(Ruleset)([], []); +}; +Media.prototype.permute = function (arr) { + if (arr.length === 0) { + return []; + } else if (arr.length === 1) { + return arr[0]; + } else { + var result = []; + var rest = this.permute(arr.slice(1)); + for (var i = 0; i < rest.length; i++) { + for (var j = 0; j < arr[0].length; j++) { + result.push([arr[0][j]].concat(rest[i])); + } + } + return result; + } +}; +Media.prototype.bubbleSelectors = function (selectors) { + if (!selectors) + return; + this.rules = [new(Ruleset)(selectors.slice(0), [this.rules[0]])]; +}; +module.exports = Media; + +},{"./anonymous.js":27,"./directive.js":38,"./element.js":39,"./expression.js":40,"./ruleset.js":57,"./selector.js":58,"./value.js":62}],48:[function(require,module,exports){ +var Node = require("./node.js"), + Selector = require("./selector.js"), + MixinDefinition = require("./mixin-definition.js"), + defaultFunc = require("../functions/default.js"); + +var MixinCall = function (elements, args, index, currentFileInfo, important) { + this.selector = new(Selector)(elements); + this.arguments = (args && args.length) ? args : null; + this.index = index; + this.currentFileInfo = currentFileInfo; + this.important = important; +}; +MixinCall.prototype = new Node(); +MixinCall.prototype.type = "MixinCall"; +MixinCall.prototype.accept = function (visitor) { + if (this.selector) { + this.selector = visitor.visit(this.selector); + } + if (this.arguments) { + this.arguments = visitor.visitArray(this.arguments); + } +}; +MixinCall.prototype.eval = function (env) { + var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule, + candidates = [], candidate, conditionResult = [], + defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count, originalRuleset; + + args = this.arguments && this.arguments.map(function (a) { + return { name: a.name, value: a.value.eval(env) }; + }); + + for (i = 0; i < env.frames.length; i++) { + if ((mixins = env.frames[i].find(this.selector)).length > 0) { + isOneFound = true; + + // To make `default()` function independent of definition order we have two "subpasses" here. + // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), + // and build candidate list with corresponding flags. Then, when we know all possible matches, + // we make a final decision. + + for (m = 0; m < mixins.length; m++) { + mixin = mixins[m]; + isRecursive = false; + for(f = 0; f < env.frames.length; f++) { + if ((!(mixin instanceof MixinDefinition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { + isRecursive = true; + break; + } + } + if (isRecursive) { + continue; + } + + if (mixin.matchArgs(args, env)) { + candidate = {mixin: mixin, group: defNone}; + + if (mixin.matchCondition) { + for (f = 0; f < 2; f++) { + defaultFunc.value(f); + conditionResult[f] = mixin.matchCondition(args, env); + } + if (conditionResult[0] || conditionResult[1]) { + if (conditionResult[0] != conditionResult[1]) { + candidate.group = conditionResult[1] ? + defTrue : defFalse; + } + + candidates.push(candidate); + } + } + else { + candidates.push(candidate); + } + + match = true; + } + } + + defaultFunc.reset(); + + count = [0, 0, 0]; + for (m = 0; m < candidates.length; m++) { + count[candidates[m].group]++; + } + + if (count[defNone] > 0) { + defaultResult = defFalse; + } else { + defaultResult = defTrue; + if ((count[defTrue] + count[defFalse]) > 1) { + throw { type: 'Runtime', + message: 'Ambiguous use of `default()` found when matching for `' + + this.format(args) + '`', + index: this.index, filename: this.currentFileInfo.filename }; + } + } + + for (m = 0; m < candidates.length; m++) { + candidate = candidates[m].group; + if ((candidate === defNone) || (candidate === defaultResult)) { + try { + mixin = candidates[m].mixin; + if (!(mixin instanceof MixinDefinition)) { + originalRuleset = mixin.originalRuleset || mixin; + mixin = new MixinDefinition("", [], mixin.rules, null, false); + mixin.originalRuleset = originalRuleset; + } + Array.prototype.push.apply( + rules, mixin.evalCall(env, args, this.important).rules); + } catch (e) { + throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack }; + } + } + } + + if (match) { + if (!this.currentFileInfo || !this.currentFileInfo.reference) { + for (i = 0; i < rules.length; i++) { + rule = rules[i]; + if (rule.markReferenced) { + rule.markReferenced(); + } + } + } + return rules; + } + } + } + if (isOneFound) { + throw { type: 'Runtime', + message: 'No matching definition was found for `' + this.format(args) + '`', + index: this.index, filename: this.currentFileInfo.filename }; + } else { + throw { type: 'Name', + message: this.selector.toCSS().trim() + " is undefined", + index: this.index, filename: this.currentFileInfo.filename }; + } +}; +MixinCall.prototype.format = function (args) { + return this.selector.toCSS().trim() + '(' + + (args ? args.map(function (a) { + var argValue = ""; + if (a.name) { + argValue += a.name + ":"; + } + if (a.value.toCSS) { + argValue += a.value.toCSS(); + } else { + argValue += "???"; + } + return argValue; + }).join(', ') : "") + ")"; +}; +module.exports = MixinCall; + +},{"../functions/default.js":10,"./mixin-definition.js":49,"./node.js":51,"./selector.js":58}],49:[function(require,module,exports){ +var Selector = require("./selector.js"), + Element = require("./element.js"), + Ruleset = require("./ruleset.js"), + Rule = require("./rule.js"), + Expression = require("./expression.js"), + contexts = require("../contexts.js"); + +var Definition = function (name, params, rules, condition, variadic, frames) { + this.name = name; + this.selectors = [new(Selector)([new(Element)(null, name, this.index, this.currentFileInfo)])]; + this.params = params; + this.condition = condition; + this.variadic = variadic; + this.arity = params.length; + this.rules = rules; + this._lookups = {}; + this.required = params.reduce(function (count, p) { + if (!p.name || (p.name && !p.value)) { return count + 1; } + else { return count; } + }, 0); + this.frames = frames; +}; +Definition.prototype = new Ruleset(); +Definition.prototype.type = "MixinDefinition"; +Definition.prototype.evalFirst = true; +Definition.prototype.accept = function (visitor) { + if (this.params && this.params.length) { + this.params = visitor.visitArray(this.params); + } + this.rules = visitor.visitArray(this.rules); + if (this.condition) { + this.condition = visitor.visit(this.condition); + } +}; +Definition.prototype.evalParams = function (env, mixinEnv, args, evaldArguments) { + /*jshint boss:true */ + var frame = new(Ruleset)(null, null), + varargs, arg, + params = this.params.slice(0), + i, j, val, name, isNamedFound, argIndex, argsLength = 0; + + mixinEnv = new contexts.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames)); + + if (args) { + args = args.slice(0); + argsLength = args.length; + + for(i = 0; i < argsLength; i++) { + arg = args[i]; + if (name = (arg && arg.name)) { + isNamedFound = false; + for(j = 0; j < params.length; j++) { + if (!evaldArguments[j] && name === params[j].name) { + evaldArguments[j] = arg.value.eval(env); + frame.prependRule(new(Rule)(name, arg.value.eval(env))); + isNamedFound = true; + break; + } + } + if (isNamedFound) { + args.splice(i, 1); + i--; + continue; + } else { + throw { type: 'Runtime', message: "Named argument for " + this.name + + ' ' + args[i].name + ' not found' }; + } + } + } + } + argIndex = 0; + for (i = 0; i < params.length; i++) { + if (evaldArguments[i]) { continue; } + + arg = args && args[argIndex]; + + if (name = params[i].name) { + if (params[i].variadic) { + varargs = []; + for (j = argIndex; j < argsLength; j++) { + varargs.push(args[j].value.eval(env)); + } + frame.prependRule(new(Rule)(name, new(Expression)(varargs).eval(env))); + } else { + val = arg && arg.value; + if (val) { + val = val.eval(env); + } else if (params[i].value) { + val = params[i].value.eval(mixinEnv); + frame.resetCache(); + } else { + throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + + ' (' + argsLength + ' for ' + this.arity + ')' }; + } + + frame.prependRule(new(Rule)(name, val)); + evaldArguments[i] = val; + } + } + + if (params[i].variadic && args) { + for (j = argIndex; j < argsLength; j++) { + evaldArguments[j] = args[j].value.eval(env); + } + } + argIndex++; + } + + return frame; +}; +Definition.prototype.eval = function (env) { + return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || env.frames.slice(0)); +}; +Definition.prototype.evalCall = function (env, args, important) { + var _arguments = [], + mixinFrames = this.frames ? this.frames.concat(env.frames) : env.frames, + frame = this.evalParams(env, new(contexts.evalEnv)(env, mixinFrames), args, _arguments), + rules, ruleset; + + frame.prependRule(new(Rule)('@arguments', new(Expression)(_arguments).eval(env))); + + rules = this.rules.slice(0); + + ruleset = new(Ruleset)(null, rules); + ruleset.originalRuleset = this; + ruleset = ruleset.eval(new(contexts.evalEnv)(env, [this, frame].concat(mixinFrames))); + if (important) { + ruleset = this.makeImportant.apply(ruleset); + } + return ruleset; +}; +Definition.prototype.matchCondition = function (args, env) { + if (this.condition && !this.condition.eval( + new(contexts.evalEnv)(env, + [this.evalParams(env, new(contexts.evalEnv)(env, this.frames ? this.frames.concat(env.frames) : env.frames), args, [])] // the parameter variables + .concat(this.frames) // the parent namespace/mixin frames + .concat(env.frames)))) { // the current environment frames + return false; + } + return true; +}; +Definition.prototype.matchArgs = function (args, env) { + var argsLength = (args && args.length) || 0, len; + + if (! this.variadic) { + if (argsLength < this.required) { return false; } + if (argsLength > this.params.length) { return false; } + } else { + if (argsLength < (this.required - 1)) { return false; } + } + + len = Math.min(argsLength, this.arity); + + for (var i = 0; i < len; i++) { + if (!this.params[i].name && !this.params[i].variadic) { + if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { + return false; + } + } + } + return true; +}; +module.exports = Definition; + +},{"../contexts.js":2,"./element.js":39,"./expression.js":40,"./rule.js":55,"./ruleset.js":57,"./selector.js":58}],50:[function(require,module,exports){ +var Node = require("./node.js"), + Operation = require("./operation.js"), + Dimension = require("./dimension.js"); + +var Negative = function (node) { + this.value = node; +}; +Negative.prototype = new Node(); +Negative.prototype.type = "Negative"; +Negative.prototype.genCSS = function (env, output) { + output.add('-'); + this.value.genCSS(env, output); +}; +Negative.prototype.eval = function (env) { + if (env.isMathOn()) { + return (new(Operation)('*', [new(Dimension)(-1), this.value])).eval(env); + } + return new(Negative)(this.value.eval(env)); +}; +module.exports = Negative; + +},{"./dimension.js":37,"./node.js":51,"./operation.js":52}],51:[function(require,module,exports){ +var Node = function() { +}; +Node.prototype.toCSS = function (env) { + var strs = []; + this.genCSS(env, { + add: function(chunk, fileInfo, index) { + strs.push(chunk); + }, + isEmpty: function () { + return strs.length === 0; + } + }); + return strs.join(''); +}; +Node.prototype.genCSS = function (env, output) { + output.add(this.value); +}; +Node.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Node.prototype.eval = function () { return this; }; +Node.prototype._operate = function (env, op, a, b) { + switch (op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': return a / b; + } +}; +Node.prototype.fround = function(env, value) { + var precision = env && env.numPrecision; + //add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999....) are properly rounded... + return (precision == null) ? value : Number((value + 2e-16).toFixed(precision)); +}; +module.exports = Node; + +},{}],52:[function(require,module,exports){ +var Node = require("./node.js"), + Color = require("./color.js"), + Dimension = require("./dimension.js"); + +var Operation = function (op, operands, isSpaced) { + this.op = op.trim(); + this.operands = operands; + this.isSpaced = isSpaced; +}; +Operation.prototype = new Node(); +Operation.prototype.type = "Operation"; +Operation.prototype.accept = function (visitor) { + this.operands = visitor.visit(this.operands); +}; +Operation.prototype.eval = function (env) { + var a = this.operands[0].eval(env), + b = this.operands[1].eval(env); + + if (env.isMathOn()) { + if (a instanceof Dimension && b instanceof Color) { + a = a.toColor(); + } + if (b instanceof Dimension && a instanceof Color) { + b = b.toColor(); + } + if (!a.operate) { + throw { type: "Operation", + message: "Operation on an invalid type" }; + } + + return a.operate(env, this.op, b); + } else { + return new(Operation)(this.op, [a, b], this.isSpaced); + } +}; +Operation.prototype.genCSS = function (env, output) { + this.operands[0].genCSS(env, output); + if (this.isSpaced) { + output.add(" "); + } + output.add(this.op); + if (this.isSpaced) { + output.add(" "); + } + this.operands[1].genCSS(env, output); +}; + +module.exports = Operation; + +},{"./color.js":31,"./dimension.js":37,"./node.js":51}],53:[function(require,module,exports){ +var Node = require("./node.js"); + +var Paren = function (node) { + this.value = node; +}; +Paren.prototype = new Node(); +Paren.prototype.type = "Paren"; +Paren.prototype.genCSS = function (env, output) { + output.add('('); + this.value.genCSS(env, output); + output.add(')'); +}; +Paren.prototype.eval = function (env) { + return new(Paren)(this.value.eval(env)); +}; +module.exports = Paren; + +},{"./node.js":51}],54:[function(require,module,exports){ +var JsEvalNode = require("./js-eval-node.js"), + Variable = require("./variable.js"); + +var Quoted = function (str, content, escaped, index, currentFileInfo) { + this.escaped = escaped; + this.value = content || ''; + this.quote = str.charAt(0); + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Quoted.prototype = new JsEvalNode(); +Quoted.prototype.type = "Quoted"; +Quoted.prototype.genCSS = function (env, output) { + if (!this.escaped) { + output.add(this.quote, this.currentFileInfo, this.index); + } + output.add(this.value); + if (!this.escaped) { + output.add(this.quote); + } +}; +Quoted.prototype.eval = function (env) { + var that = this; + var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { + return String(that.evaluateJavaScript(exp, env)); + }).replace(/@\{([\w-]+)\}/g, function (_, name) { + var v = new(Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true); + return (v instanceof Quoted) ? v.value : v.toCSS(); + }); + return new(Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo); +}; +Quoted.prototype.compare = function (x) { + if (!x.toCSS) { + return -1; + } + + var left, right; + + // when comparing quoted strings allow the quote to differ + if (x.type === "Quoted" && !this.escaped && !x.escaped) { + left = x.value; + right = this.value; + } else { + left = this.toCSS(); + right = x.toCSS(); + } + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; +}; +module.exports = Quoted; + +},{"./js-eval-node.js":45,"./variable.js":63}],55:[function(require,module,exports){ +var Node = require("./node.js"), + Value = require("./value.js"), + Keyword = require("./keyword.js"); + +var Rule = function (name, value, important, merge, index, currentFileInfo, inline, variable) { + this.name = name; + this.value = (value instanceof Node) ? value : new(Value)([value]); //value instanceof tree.Value || value instanceof tree.Ruleset ?? + this.important = important ? ' ' + important.trim() : ''; + this.merge = merge; + this.index = index; + this.currentFileInfo = currentFileInfo; + this.inline = inline || false; + this.variable = (variable !== undefined) ? variable + : (name.charAt && (name.charAt(0) === '@')); +}; + +function evalName(env, name) { + var value = "", i, n = name.length, + output = {add: function (s) {value += s;}}; + for (i = 0; i < n; i++) { + name[i].eval(env).genCSS(env, output); + } + return value; +} + +Rule.prototype = new Node(); +Rule.prototype.type = "Rule"; +Rule.prototype.genCSS = function (env, output) { + output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index); + try { + this.value.genCSS(env, output); + } + catch(e) { + e.index = this.index; + e.filename = this.currentFileInfo.filename; + throw e; + } + output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index); +}; +Rule.prototype.eval = function (env) { + var strictMathBypass = false, name = this.name, evaldValue, variable = this.variable; + if (typeof name !== "string") { + // expand 'primitive' name directly to get + // things faster (~10% for benchmark.less): + name = (name.length === 1) + && (name[0] instanceof Keyword) + ? name[0].value : evalName(env, name); + variable = false; // never treat expanded interpolation as new variable name + } + if (name === "font" && !env.strictMath) { + strictMathBypass = true; + env.strictMath = true; + } + try { + evaldValue = this.value.eval(env); + + if (!this.variable && evaldValue.type === "DetachedRuleset") { + throw { message: "Rulesets cannot be evaluated on a property.", + index: this.index, filename: this.currentFileInfo.filename }; + } + + return new(Rule)(name, + evaldValue, + this.important, + this.merge, + this.index, this.currentFileInfo, this.inline, + variable); + } + catch(e) { + if (typeof e.index !== 'number') { + e.index = this.index; + e.filename = this.currentFileInfo.filename; + } + throw e; + } + finally { + if (strictMathBypass) { + env.strictMath = false; + } + } +}; +Rule.prototype.makeImportant = function () { + return new(Rule)(this.name, + this.value, + "!important", + this.merge, + this.index, this.currentFileInfo, this.inline); +}; + +module.exports = Rule; + +},{"./keyword.js":46,"./node.js":51,"./value.js":62}],56:[function(require,module,exports){ +var Node = require("./node.js"), + Variable = require("./variable.js"); + +var RulesetCall = function (variable) { + this.variable = variable; +}; +RulesetCall.prototype = new Node(); +RulesetCall.prototype.type = "RulesetCall"; +RulesetCall.prototype.eval = function (env) { + var detachedRuleset = new(Variable)(this.variable).eval(env); + return detachedRuleset.callEval(env); +}; +module.exports = RulesetCall; + +},{"./node.js":51,"./variable.js":63}],57:[function(require,module,exports){ +var Node = require("./node.js"), + Rule = require("./rule.js"), + Selector = require("./selector.js"), + Element = require("./element.js"), + contexts = require("../contexts.js"), + defaultFunc = require("../functions/default.js"), + getDebugInfo = require("./debug-info.js"); + +var Ruleset = function (selectors, rules, strictImports) { + this.selectors = selectors; + this.rules = rules; + this._lookups = {}; + this.strictImports = strictImports; +}; +Ruleset.prototype = new Node(); +Ruleset.prototype.type = "Ruleset"; +Ruleset.prototype.isRuleset = true; +Ruleset.prototype.isRulesetLike = true; +Ruleset.prototype.accept = function (visitor) { + if (this.paths) { + visitor.visitArray(this.paths, true); + } else if (this.selectors) { + this.selectors = visitor.visitArray(this.selectors); + } + if (this.rules && this.rules.length) { + this.rules = visitor.visitArray(this.rules); + } +}; +Ruleset.prototype.eval = function (env) { + var thisSelectors = this.selectors, selectors, + selCnt, selector, i, hasOnePassingSelector = false; + + if (thisSelectors && (selCnt = thisSelectors.length)) { + selectors = []; + defaultFunc.error({ + type: "Syntax", + message: "it is currently only allowed in parametric mixin guards," + }); + for (i = 0; i < selCnt; i++) { + selector = thisSelectors[i].eval(env); + selectors.push(selector); + if (selector.evaldCondition) { + hasOnePassingSelector = true; + } + } + defaultFunc.reset(); + } else { + hasOnePassingSelector = true; + } + + var rules = this.rules ? this.rules.slice(0) : null, + ruleset = new(Ruleset)(selectors, rules, this.strictImports), + rule, subRule; + + ruleset.originalRuleset = this; + ruleset.root = this.root; + ruleset.firstRoot = this.firstRoot; + ruleset.allowImports = this.allowImports; + + if(this.debugInfo) { + ruleset.debugInfo = this.debugInfo; + } + + if (!hasOnePassingSelector) { + rules.length = 0; + } + + // push the current ruleset to the frames stack + var envFrames = env.frames; + envFrames.unshift(ruleset); + + // currrent selectors + var envSelectors = env.selectors; + if (!envSelectors) { + env.selectors = envSelectors = []; + } + envSelectors.unshift(this.selectors); + + // Evaluate imports + if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { + ruleset.evalImports(env); + } + + // Store the frames around mixin definitions, + // so they can be evaluated like closures when the time comes. + var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0; + for (i = 0; i < rsRuleCnt; i++) { + if (rsRules[i].evalFirst) { + rsRules[i] = rsRules[i].eval(env); + } + } + + var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; + + // Evaluate mixin calls. + for (i = 0; i < rsRuleCnt; i++) { + if (rsRules[i].type === "MixinCall") { + /*jshint loopfunc:true */ + rules = rsRules[i].eval(env).filter(function(r) { + if ((r instanceof Rule) && r.variable) { + // do not pollute the scope if the variable is + // already there. consider returning false here + // but we need a way to "return" variable from mixins + return !(ruleset.variable(r.name)); + } + return true; + }); + rsRules.splice.apply(rsRules, [i, 1].concat(rules)); + rsRuleCnt += rules.length - 1; + i += rules.length-1; + ruleset.resetCache(); + } else if (rsRules[i].type === "RulesetCall") { + /*jshint loopfunc:true */ + rules = rsRules[i].eval(env).rules.filter(function(r) { + if ((r instanceof Rule) && r.variable) { + // do not pollute the scope at all + return false; + } + return true; + }); + rsRules.splice.apply(rsRules, [i, 1].concat(rules)); + rsRuleCnt += rules.length - 1; + i += rules.length-1; + ruleset.resetCache(); + } + } + + // Evaluate everything else + for (i = 0; i < rsRules.length; i++) { + rule = rsRules[i]; + if (!rule.evalFirst) { + rsRules[i] = rule = rule.eval ? rule.eval(env) : rule; + } + } + + // Evaluate everything else + for (i = 0; i < rsRules.length; i++) { + rule = rsRules[i]; + // for rulesets, check if it is a css guard and can be removed + if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) { + // check if it can be folded in (e.g. & where) + if (rule.selectors[0].isJustParentSelector()) { + rsRules.splice(i--, 1); + + for(var j = 0; j < rule.rules.length; j++) { + subRule = rule.rules[j]; + if (!(subRule instanceof Rule) || !subRule.variable) { + rsRules.splice(++i, 0, subRule); + } + } + } + } + } + + // Pop the stack + envFrames.shift(); + envSelectors.shift(); + + if (env.mediaBlocks) { + for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) { + env.mediaBlocks[i].bubbleSelectors(selectors); + } + } + + return ruleset; +}; +Ruleset.prototype.evalImports = function(env) { + var rules = this.rules, i, importRules; + if (!rules) { return; } + + for (i = 0; i < rules.length; i++) { + if (rules[i].type === "Import") { + importRules = rules[i].eval(env); + if (importRules && importRules.length) { + rules.splice.apply(rules, [i, 1].concat(importRules)); + i+= importRules.length-1; + } else { + rules.splice(i, 1, importRules); + } + this.resetCache(); + } + } +}; +Ruleset.prototype.makeImportant = function() { + return new Ruleset(this.selectors, this.rules.map(function (r) { + if (r.makeImportant) { + return r.makeImportant(); + } else { + return r; + } + }), this.strictImports); +}; +Ruleset.prototype.matchArgs = function (args) { + return !args || args.length === 0; +}; +// lets you call a css selector with a guard +Ruleset.prototype.matchCondition = function (args, env) { + var lastSelector = this.selectors[this.selectors.length-1]; + if (!lastSelector.evaldCondition) { + return false; + } + if (lastSelector.condition && + !lastSelector.condition.eval( + new(contexts.evalEnv)(env, + env.frames))) { + return false; + } + return true; +}; +Ruleset.prototype.resetCache = function () { + this._rulesets = null; + this._variables = null; + this._lookups = {}; +}; +Ruleset.prototype.variables = function () { + if (!this._variables) { + this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { + if (r instanceof Rule && r.variable === true) { + hash[r.name] = r; + } + return hash; + }, {}); + } + return this._variables; +}; +Ruleset.prototype.variable = function (name) { + return this.variables()[name]; +}; +Ruleset.prototype.rulesets = function () { + if (!this.rules) { return null; } + + var filtRules = [], rules = this.rules, cnt = rules.length, + i, rule; + + for (i = 0; i < cnt; i++) { + rule = rules[i]; + if (rule.isRuleset) { + filtRules.push(rule); + } + } + + return filtRules; +}; +Ruleset.prototype.prependRule = function (rule) { + var rules = this.rules; + if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } +}; +Ruleset.prototype.find = function (selector, self) { + self = self || this; + var rules = [], match, + key = selector.toCSS(); + + if (key in this._lookups) { return this._lookups[key]; } + + this.rulesets().forEach(function (rule) { + if (rule !== self) { + for (var j = 0; j < rule.selectors.length; j++) { + match = selector.match(rule.selectors[j]); + if (match) { + if (selector.elements.length > match) { + Array.prototype.push.apply(rules, rule.find( + new(Selector)(selector.elements.slice(match)), self)); + } else { + rules.push(rule); + } + break; + } + } + } + }); + this._lookups[key] = rules; + return rules; +}; +Ruleset.prototype.genCSS = function (env, output) { + var i, j, + charsetRuleNodes = [], + ruleNodes = [], + rulesetNodes = [], + rulesetNodeCnt, + debugInfo, // Line number debugging + rule, + path; + + env.tabLevel = (env.tabLevel || 0); + + if (!this.root) { + env.tabLevel++; + } + + var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "), + tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "), + sep; + + function isRulesetLikeNode(rule, root) { + // if it has nested rules, then it should be treated like a ruleset + // medias and comments do not have nested rules, but should be treated like rulesets anyway + // some directives and anonymous nodes are ruleset like, others are not + if (typeof rule.isRulesetLike === "boolean") + { + return rule.isRulesetLike; + } else if (typeof rule.isRulesetLike === "function") + { + return rule.isRulesetLike(root); + } + + //anything else is assumed to be a rule + return false; + } + + for (i = 0; i < this.rules.length; i++) { + rule = this.rules[i]; + if (isRulesetLikeNode(rule, this.root)) { + rulesetNodes.push(rule); + } else { + //charsets should float on top of everything + if (rule.isCharset && rule.isCharset()) { + charsetRuleNodes.push(rule); + } else { + ruleNodes.push(rule); + } + } + } + ruleNodes = charsetRuleNodes.concat(ruleNodes); + + // If this is the root node, we don't render + // a selector, or {}. + if (!this.root) { + debugInfo = getDebugInfo(env, this, tabSetStr); + + if (debugInfo) { + output.add(debugInfo); + output.add(tabSetStr); + } + + var paths = this.paths, pathCnt = paths.length, + pathSubCnt; + + sep = env.compress ? ',' : (',\n' + tabSetStr); + + for (i = 0; i < pathCnt; i++) { + path = paths[i]; + if (!(pathSubCnt = path.length)) { continue; } + if (i > 0) { output.add(sep); } + + env.firstSelector = true; + path[0].genCSS(env, output); + + env.firstSelector = false; + for (j = 1; j < pathSubCnt; j++) { + path[j].genCSS(env, output); + } + } + + output.add((env.compress ? '{' : ' {\n') + tabRuleStr); + } + + // Compile rules and rulesets + for (i = 0; i < ruleNodes.length; i++) { + rule = ruleNodes[i]; + + // @page{ directive ends up with root elements inside it, a mix of rules and rulesets + // In this instance we do not know whether it is the last property + if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) { + env.lastRule = true; + } + + if (rule.genCSS) { + rule.genCSS(env, output); + } else if (rule.value) { + output.add(rule.value.toString()); + } + + if (!env.lastRule) { + output.add(env.compress ? '' : ('\n' + tabRuleStr)); + } else { + env.lastRule = false; + } + } + + if (!this.root) { + output.add((env.compress ? '}' : '\n' + tabSetStr + '}')); + env.tabLevel--; + } + + sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr); + rulesetNodeCnt = rulesetNodes.length; + if (rulesetNodeCnt) { + if (ruleNodes.length && sep) { output.add(sep); } + rulesetNodes[0].genCSS(env, output); + for (i = 1; i < rulesetNodeCnt; i++) { + if (sep) { output.add(sep); } + rulesetNodes[i].genCSS(env, output); + } + } + + if (!output.isEmpty() && !env.compress && this.firstRoot) { + output.add('\n'); + } +}; +Ruleset.prototype.markReferenced = function () { + if (!this.selectors) { + return; + } + for (var s = 0; s < this.selectors.length; s++) { + this.selectors[s].markReferenced(); + } +}; +Ruleset.prototype.joinSelectors = function (paths, context, selectors) { + for (var s = 0; s < selectors.length; s++) { + this.joinSelector(paths, context, selectors[s]); + } +}; +Ruleset.prototype.joinSelector = function (paths, context, selector) { + + var i, j, k, + hasParentSelector, newSelectors, el, sel, parentSel, + newSelectorPath, afterParentJoin, newJoinedSelector, + newJoinedSelectorEmpty, lastSelector, currentElements, + selectorsMultiplied; + + for (i = 0; i < selector.elements.length; i++) { + el = selector.elements[i]; + if (el.value === '&') { + hasParentSelector = true; + } + } + + if (!hasParentSelector) { + if (context.length > 0) { + for (i = 0; i < context.length; i++) { + paths.push(context[i].concat(selector)); + } + } + else { + paths.push([selector]); + } + return; + } + + // The paths are [[Selector]] + // The first list is a list of comma seperated selectors + // The inner list is a list of inheritance seperated selectors + // e.g. + // .a, .b { + // .c { + // } + // } + // == [[.a] [.c]] [[.b] [.c]] + // + + // the elements from the current selector so far + currentElements = []; + // the current list of new selectors to add to the path. + // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors + // by the parents + newSelectors = [[]]; + + for (i = 0; i < selector.elements.length; i++) { + el = selector.elements[i]; + // non parent reference elements just get added + if (el.value !== "&") { + currentElements.push(el); + } else { + // the new list of selectors to add + selectorsMultiplied = []; + + // merge the current list of non parent selector elements + // on to the current list of selectors to add + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); + } + + // loop through our current selectors + for (j = 0; j < newSelectors.length; j++) { + sel = newSelectors[j]; + // if we don't have any parent paths, the & might be in a mixin so that it can be used + // whether there are parents or not + if (context.length === 0) { + // the combinator used on el should now be applied to the next element instead so that + // it is not lost + if (sel.length > 0) { + sel[0].elements = sel[0].elements.slice(0); + sel[0].elements.push(new(Element)(el.combinator, '', el.index, el.currentFileInfo)); + } + selectorsMultiplied.push(sel); + } + else { + // and the parent selectors + for (k = 0; k < context.length; k++) { + parentSel = context[k]; + // We need to put the current selectors + // then join the last selector's elements on to the parents selectors + + // our new selector path + newSelectorPath = []; + // selectors from the parent after the join + afterParentJoin = []; + newJoinedSelectorEmpty = true; + + //construct the joined selector - if & is the first thing this will be empty, + // if not newJoinedSelector will be the last set of elements in the selector + if (sel.length > 0) { + newSelectorPath = sel.slice(0); + lastSelector = newSelectorPath.pop(); + newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0)); + newJoinedSelectorEmpty = false; + } + else { + newJoinedSelector = selector.createDerived([]); + } + + //put together the parent selectors after the join + if (parentSel.length > 1) { + afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); + } + + if (parentSel.length > 0) { + newJoinedSelectorEmpty = false; + + // join the elements so far with the first part of the parent + newJoinedSelector.elements.push(new(Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo)); + newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); + } + + if (!newJoinedSelectorEmpty) { + // now add the joined selector + newSelectorPath.push(newJoinedSelector); + } + + // and the rest of the parent + newSelectorPath = newSelectorPath.concat(afterParentJoin); + + // add that to our new set of selectors + selectorsMultiplied.push(newSelectorPath); + } + } + } + + // our new selectors has been multiplied, so reset the state + newSelectors = selectorsMultiplied; + currentElements = []; + } + } + + // if we have any elements left over (e.g. .a& .b == .b) + // add them on to all the current selectors + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); + } + + for (i = 0; i < newSelectors.length; i++) { + if (newSelectors[i].length > 0) { + paths.push(newSelectors[i]); + } + } +}; +Ruleset.prototype.mergeElementsOnToSelectors = function(elements, selectors) { + var i, sel; + + if (selectors.length === 0) { + selectors.push([ new(Selector)(elements) ]); + return; + } + + for (i = 0; i < selectors.length; i++) { + sel = selectors[i]; + + // if the previous thing in sel is a parent this needs to join on to it + if (sel.length > 0) { + sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); + } + else { + sel.push(new(Selector)(elements)); + } + } +}; +module.exports = Ruleset; + +},{"../contexts.js":2,"../functions/default.js":10,"./debug-info.js":35,"./element.js":39,"./node.js":51,"./rule.js":55,"./selector.js":58}],58:[function(require,module,exports){ +var Node = require("./node.js"); + +var Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) { + this.elements = elements; + this.extendList = extendList; + this.condition = condition; + this.currentFileInfo = currentFileInfo || {}; + this.isReferenced = isReferenced; + if (!condition) { + this.evaldCondition = true; + } +}; +Selector.prototype = new Node(); +Selector.prototype.type = "Selector"; +Selector.prototype.accept = function (visitor) { + if (this.elements) { + this.elements = visitor.visitArray(this.elements); + } + if (this.extendList) { + this.extendList = visitor.visitArray(this.extendList); + } + if (this.condition) { + this.condition = visitor.visit(this.condition); + } +}; +Selector.prototype.createDerived = function(elements, extendList, evaldCondition) { + evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; + var newSelector = new(Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced); + newSelector.evaldCondition = evaldCondition; + newSelector.mediaEmpty = this.mediaEmpty; + return newSelector; +}; +Selector.prototype.match = function (other) { + var elements = this.elements, + len = elements.length, + olen, i; + + other.CacheElements(); + + olen = other._elements.length; + if (olen === 0 || len < olen) { + return 0; + } else { + for (i = 0; i < olen; i++) { + if (elements[i].value !== other._elements[i]) { + return 0; + } + } + } + + return olen; // return number of matched elements +}; +Selector.prototype.CacheElements = function(){ + var css = '', len, v, i; + + if( !this._elements ){ + + len = this.elements.length; + for(i = 0; i < len; i++){ + + v = this.elements[i]; + css += v.combinator.value; + + if( !v.value.value ){ + css += v.value; + continue; + } + + if( typeof v.value.value !== "string" ){ + css = ''; + break; + } + css += v.value.value; + } + + this._elements = css.match(/[,&#\*\.\w-]([\w-]|(\\.))*/g); + + if (this._elements) { + if (this._elements[0] === "&") { + this._elements.shift(); + } + + } else { + this._elements = []; + } + + } +}; +Selector.prototype.isJustParentSelector = function() { + return !this.mediaEmpty && + this.elements.length === 1 && + this.elements[0].value === '&' && + (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); +}; +Selector.prototype.eval = function (env) { + var evaldCondition = this.condition && this.condition.eval(env), + elements = this.elements, extendList = this.extendList; + + elements = elements && elements.map(function (e) { return e.eval(env); }); + extendList = extendList && extendList.map(function(extend) { return extend.eval(env); }); + + return this.createDerived(elements, extendList, evaldCondition); +}; +Selector.prototype.genCSS = function (env, output) { + var i, element; + if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") { + output.add(' ', this.currentFileInfo, this.index); + } + if (!this._css) { + //TODO caching? speed comparison? + for(i = 0; i < this.elements.length; i++) { + element = this.elements[i]; + element.genCSS(env, output); + } + } +}; +Selector.prototype.markReferenced = function () { + this.isReferenced = true; +}; +Selector.prototype.getIsReferenced = function() { + return !this.currentFileInfo.reference || this.isReferenced; +}; +Selector.prototype.getIsOutput = function() { + return this.evaldCondition; +}; +module.exports = Selector; + +},{"./node.js":51}],59:[function(require,module,exports){ +var Node = require("./node.js"); + +var UnicodeDescriptor = function (value) { + this.value = value; +}; +UnicodeDescriptor.prototype = new Node(); +UnicodeDescriptor.prototype.type = "UnicodeDescriptor"; + +module.exports = UnicodeDescriptor; + +},{"./node.js":51}],60:[function(require,module,exports){ +var Node = require("./node.js"), + unitConversions = require("../data/unit-conversions.js"); + +var Unit = function (numerator, denominator, backupUnit) { + this.numerator = numerator ? numerator.slice(0).sort() : []; + this.denominator = denominator ? denominator.slice(0).sort() : []; + this.backupUnit = backupUnit; +}; + +Unit.prototype = new Node(); +Unit.prototype.type = "Unit"; +Unit.prototype.clone = function () { + return new Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit); +}; +Unit.prototype.genCSS = function (env, output) { + if (this.numerator.length >= 1) { + output.add(this.numerator[0]); + } else + if (this.denominator.length >= 1) { + output.add(this.denominator[0]); + } else + if ((!env || !env.strictUnits) && this.backupUnit) { + output.add(this.backupUnit); + } +}; +Unit.prototype.toString = function () { + var i, returnStr = this.numerator.join("*"); + for (i = 0; i < this.denominator.length; i++) { + returnStr += "/" + this.denominator[i]; + } + return returnStr; +}; +Unit.prototype.compare = function (other) { + return this.is(other.toString()) ? 0 : -1; +}; +Unit.prototype.is = function (unitString) { + return this.toString() === unitString; +}; +Unit.prototype.isLength = function () { + return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/)); +}; +Unit.prototype.isEmpty = function () { + return this.numerator.length === 0 && this.denominator.length === 0; +}; +Unit.prototype.isSingular = function() { + return this.numerator.length <= 1 && this.denominator.length === 0; +}; +Unit.prototype.map = function(callback) { + var i; + + for (i = 0; i < this.numerator.length; i++) { + this.numerator[i] = callback(this.numerator[i], false); + } + + for (i = 0; i < this.denominator.length; i++) { + this.denominator[i] = callback(this.denominator[i], true); + } +}; +Unit.prototype.usedUnits = function() { + var group, result = {}, mapUnit; + + mapUnit = function (atomicUnit) { + /*jshint loopfunc:true */ + if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { + result[groupName] = atomicUnit; + } + + return atomicUnit; + }; + + for (var groupName in unitConversions) { + if (unitConversions.hasOwnProperty(groupName)) { + group = unitConversions[groupName]; + + this.map(mapUnit); + } + } + + return result; +}; +Unit.prototype.cancel = function () { + var counter = {}, atomicUnit, i, backup; + + for (i = 0; i < this.numerator.length; i++) { + atomicUnit = this.numerator[i]; + if (!backup) { + backup = atomicUnit; + } + counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; + } + + for (i = 0; i < this.denominator.length; i++) { + atomicUnit = this.denominator[i]; + if (!backup) { + backup = atomicUnit; + } + counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; + } + + this.numerator = []; + this.denominator = []; + + for (atomicUnit in counter) { + if (counter.hasOwnProperty(atomicUnit)) { + var count = counter[atomicUnit]; + + if (count > 0) { + for (i = 0; i < count; i++) { + this.numerator.push(atomicUnit); + } + } else if (count < 0) { + for (i = 0; i < -count; i++) { + this.denominator.push(atomicUnit); + } + } + } + } + + if (this.numerator.length === 0 && this.denominator.length === 0 && backup) { + this.backupUnit = backup; + } + + this.numerator.sort(); + this.denominator.sort(); +}; +module.exports = Unit; + +},{"../data/unit-conversions.js":5,"./node.js":51}],61:[function(require,module,exports){ +var Node = require("./node.js"); + +var URL = function (val, currentFileInfo, isEvald) { + this.value = val; + this.currentFileInfo = currentFileInfo; + this.isEvald = isEvald; +}; +URL.prototype = new Node(); +URL.prototype.type = "Url"; +URL.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +URL.prototype.genCSS = function (env, output) { + output.add("url("); + this.value.genCSS(env, output); + output.add(")"); +}; +URL.prototype.eval = function (ctx) { + var val = this.value.eval(ctx), + rootpath; + + if (!this.isEvald) { + // Add the base path if the URL is relative + rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; + if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) { + if (!val.quote) { + rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); + } + val.value = rootpath + val.value; + } + + val.value = ctx.normalizePath(val.value); + + // Add url args if enabled + if (ctx.urlArgs) { + if (!val.value.match(/^\s*data:/)) { + var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; + var urlArgs = delimiter + ctx.urlArgs; + if (val.value.indexOf('#') !== -1) { + val.value = val.value.replace('#', urlArgs + '#'); + } else { + val.value += urlArgs; + } + } + } + } + + return new(URL)(val, this.currentFileInfo, true); +}; +module.exports = URL; + +},{"./node.js":51}],62:[function(require,module,exports){ +var Node = require("./node.js"); + +var Value = function (value) { + this.value = value; +}; +Value.prototype = new Node(); +Value.prototype.type = "Value"; +Value.prototype.accept = function (visitor) { + if (this.value) { + this.value = visitor.visitArray(this.value); + } +}; +Value.prototype.eval = function (env) { + if (this.value.length === 1) { + return this.value[0].eval(env); + } else { + return new(Value)(this.value.map(function (v) { + return v.eval(env); + })); + } +}; +Value.prototype.genCSS = function (env, output) { + var i; + for(i = 0; i < this.value.length; i++) { + this.value[i].genCSS(env, output); + if (i+1 < this.value.length) { + output.add((env && env.compress) ? ',' : ', '); + } + } +}; +module.exports = Value; + +},{"./node.js":51}],63:[function(require,module,exports){ +var Node = require("./node.js"); + +var Variable = function (name, index, currentFileInfo) { + this.name = name; + this.index = index; + this.currentFileInfo = currentFileInfo || {}; +}; +Variable.prototype = new Node(); +Variable.prototype.type = "Variable"; +Variable.prototype.eval = function (env) { + var variable, name = this.name; + + if (name.indexOf('@@') === 0) { + name = '@' + new(Variable)(name.slice(1)).eval(env).value; + } + + if (this.evaluating) { + throw { type: 'Name', + message: "Recursive variable definition for " + name, + filename: this.currentFileInfo.file, + index: this.index }; + } + + this.evaluating = true; + + variable = this.find(env.frames, function (frame) { + var v = frame.variable(name); + if (v) { + return v.value.eval(env); + } + }); + if (variable) { + this.evaluating = false; + return variable; + } else { + throw { type: 'Name', + message: "variable " + name + " is undefined", + filename: this.currentFileInfo.filename, + index: this.index }; + } +}; +Variable.prototype.find = function (obj, fun) { + for (var i = 0, r; i < obj.length; i++) { + r = fun.call(obj, obj[i]); + if (r) { return r; } + } + return null; +}; +module.exports = Variable; + +},{"./node.js":51}],64:[function(require,module,exports){ +var tree = require("../tree/index.js"), + Visitor = require("./visitor.js"); + +/*jshint loopfunc:true */ + +var ExtendFinderVisitor = function() { + this._visitor = new Visitor(this); + this.contexts = []; + this.allExtendsStack = [[]]; +}; + +ExtendFinderVisitor.prototype = { + run: function (root) { + root = this._visitor.visit(root); + root.allExtends = this.allExtendsStack[0]; + return root; + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitRuleset: function (rulesetNode, visitArgs) { + if (rulesetNode.root) { + return; + } + + var i, j, extend, allSelectorsExtendList = [], extendList; + + // get &:extend(.a); rules which apply to all selectors in this ruleset + var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; + for(i = 0; i < ruleCnt; i++) { + if (rulesetNode.rules[i] instanceof tree.Extend) { + allSelectorsExtendList.push(rules[i]); + rulesetNode.extendOnEveryPath = true; + } + } + + // now find every selector and apply the extends that apply to all extends + // and the ones which apply to an individual extend + var paths = rulesetNode.paths; + for(i = 0; i < paths.length; i++) { + var selectorPath = paths[i], + selector = selectorPath[selectorPath.length - 1], + selExtendList = selector.extendList; + + extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList) + : allSelectorsExtendList; + + if (extendList) { + extendList = extendList.map(function(allSelectorsExtend) { + return allSelectorsExtend.clone(); + }); + } + + for(j = 0; j < extendList.length; j++) { + this.foundExtends = true; + extend = extendList[j]; + extend.findSelfSelectors(selectorPath); + extend.ruleset = rulesetNode; + if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } + this.allExtendsStack[this.allExtendsStack.length-1].push(extend); + } + } + + this.contexts.push(rulesetNode.selectors); + }, + visitRulesetOut: function (rulesetNode) { + if (!rulesetNode.root) { + this.contexts.length = this.contexts.length - 1; + } + }, + visitMedia: function (mediaNode, visitArgs) { + mediaNode.allExtends = []; + this.allExtendsStack.push(mediaNode.allExtends); + }, + visitMediaOut: function (mediaNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + }, + visitDirective: function (directiveNode, visitArgs) { + directiveNode.allExtends = []; + this.allExtendsStack.push(directiveNode.allExtends); + }, + visitDirectiveOut: function (directiveNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + } +}; + +var ProcessExtendsVisitor = function() { + this._visitor = new Visitor(this); +}; + +ProcessExtendsVisitor.prototype = { + run: function(root) { + var extendFinder = new ExtendFinderVisitor(); + extendFinder.run(root); + if (!extendFinder.foundExtends) { return root; } + root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); + this.allExtendsStack = [root.allExtends]; + return this._visitor.visit(root); + }, + doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { + // + // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting + // the selector we would do normally, but we are also adding an extend with the same target selector + // this means this new extend can then go and alter other extends + // + // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors + // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if + // we look at each selector at a time, as is done in visitRuleset + + var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; + + iterationCount = iterationCount || 0; + + //loop through comparing every extend with every target extend. + // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place + // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one + // and the second is the target. + // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the + // case when processing media queries + for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){ + for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){ + + extend = extendsList[extendIndex]; + targetExtend = extendsListTarget[targetExtendIndex]; + + // look for circular references + if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; } + + // find a match in the target extends self selector (the bit before :extend) + selectorPath = [targetExtend.selfSelectors[0]]; + matches = extendVisitor.findMatch(extend, selectorPath); + + if (matches.length) { + + // we found a match, so for each self selector.. + extend.selfSelectors.forEach(function(selfSelector) { + + // process the extend as usual + newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector); + + // but now we create a new extend from it + newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0); + newExtend.selfSelectors = newSelector; + + // add the extend onto the list of extends for that selector + newSelector[newSelector.length-1].extendList = [newExtend]; + + // record that we need to add it. + extendsToAdd.push(newExtend); + newExtend.ruleset = targetExtend.ruleset; + + //remember its parents for circular references + newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); + + // only process the selector once.. if we have :extend(.a,.b) then multiple + // extends will look at the same selector path, so when extending + // we know that any others will be duplicates in terms of what is added to the css + if (targetExtend.firstExtendOnThisSelectorPath) { + newExtend.firstExtendOnThisSelectorPath = true; + targetExtend.ruleset.paths.push(newSelector); + } + }); + } + } + } + + if (extendsToAdd.length) { + // try to detect circular references to stop a stack overflow. + // may no longer be needed. + this.extendChainCount++; + if (iterationCount > 100) { + var selectorOne = "{unable to calculate}"; + var selectorTwo = "{unable to calculate}"; + try + { + selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); + selectorTwo = extendsToAdd[0].selector.toCSS(); + } + catch(e) {} + throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"}; + } + + // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... + return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1)); + } else { + return extendsToAdd; + } + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitSelector: function (selectorNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitRuleset: function (rulesetNode, visitArgs) { + if (rulesetNode.root) { + return; + } + var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath; + + // look at each selector path in the ruleset, find any extend matches and then copy, find and replace + + for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { + for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { + selectorPath = rulesetNode.paths[pathIndex]; + + // extending extends happens initially, before the main pass + if (rulesetNode.extendOnEveryPath) { continue; } + var extendList = selectorPath[selectorPath.length-1].extendList; + if (extendList && extendList.length) { continue; } + + matches = this.findMatch(allExtends[extendIndex], selectorPath); + + if (matches.length) { + + allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { + selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector)); + }); + } + } + } + rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); + }, + findMatch: function (extend, haystackSelectorPath) { + // + // look through the haystack selector path to try and find the needle - extend.selector + // returns an array of selector matches that can then be replaced + // + var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, + targetCombinator, i, + extendVisitor = this, + needleElements = extend.selector.elements, + potentialMatches = [], potentialMatch, matches = []; + + // loop through the haystack elements + for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { + hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; + + for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { + + haystackElement = hackstackSelector.elements[hackstackElementIndex]; + + // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. + if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { + potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); + } + + for(i = 0; i < potentialMatches.length; i++) { + potentialMatch = potentialMatches[i]; + + // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't + // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out + // what the resulting combinator will be + targetCombinator = haystackElement.combinator.value; + if (targetCombinator === '' && hackstackElementIndex === 0) { + targetCombinator = ' '; + } + + // if we don't match, null our match to indicate failure + if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || + (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { + potentialMatch = null; + } else { + potentialMatch.matched++; + } + + // if we are still valid and have finished, test whether we have elements after and whether these are allowed + if (potentialMatch) { + potentialMatch.finished = potentialMatch.matched === needleElements.length; + if (potentialMatch.finished && + (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) { + potentialMatch = null; + } + } + // if null we remove, if not, we are still valid, so either push as a valid match or continue + if (potentialMatch) { + if (potentialMatch.finished) { + potentialMatch.length = needleElements.length; + potentialMatch.endPathIndex = haystackSelectorIndex; + potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match + potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again + matches.push(potentialMatch); + } + } else { + potentialMatches.splice(i, 1); + i--; + } + } + } + } + return matches; + }, + isElementValuesEqual: function(elementValue1, elementValue2) { + if (typeof elementValue1 === "string" || typeof elementValue2 === "string") { + return elementValue1 === elementValue2; + } + if (elementValue1 instanceof tree.Attribute) { + if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { + return false; + } + if (!elementValue1.value || !elementValue2.value) { + if (elementValue1.value || elementValue2.value) { + return false; + } + return true; + } + elementValue1 = elementValue1.value.value || elementValue1.value; + elementValue2 = elementValue2.value.value || elementValue2.value; + return elementValue1 === elementValue2; + } + elementValue1 = elementValue1.value; + elementValue2 = elementValue2.value; + if (elementValue1 instanceof tree.Selector) { + if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { + return false; + } + for(var i = 0; i currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { + path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); + currentSelectorPathElementIndex = 0; + currentSelectorPathIndex++; + } + + newElements = selector.elements + .slice(currentSelectorPathElementIndex, match.index) + .concat([firstElement]) + .concat(replacementSelector.elements.slice(1)); + + if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { + path[path.length - 1].elements = + path[path.length - 1].elements.concat(newElements); + } else { + path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); + + path.push(new tree.Selector( + newElements + )); + } + currentSelectorPathIndex = match.endPathIndex; + currentSelectorPathElementIndex = match.endPathElementIndex; + if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { + currentSelectorPathElementIndex = 0; + currentSelectorPathIndex++; + } + } + + if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { + path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); + currentSelectorPathIndex++; + } + + path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); + + return path; + }, + visitRulesetOut: function (rulesetNode) { + }, + visitMedia: function (mediaNode, visitArgs) { + var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); + newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); + this.allExtendsStack.push(newAllExtends); + }, + visitMediaOut: function (mediaNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + }, + visitDirective: function (directiveNode, visitArgs) { + var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); + newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends)); + this.allExtendsStack.push(newAllExtends); + }, + visitDirectiveOut: function (directiveNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + } +}; + +module.exports = ProcessExtendsVisitor; + +},{"../tree/index.js":43,"./visitor.js":69}],65:[function(require,module,exports){ +var contexts = require("../contexts.js"), + Visitor = require("./visitor.js"); + +var ImportVisitor = function(importer, finish, evalEnv, onceFileDetectionMap, recursionDetector) { + this._visitor = new Visitor(this); + this._importer = importer; + this._finish = finish; + this.env = evalEnv || new contexts.evalEnv(); + this.importCount = 0; + this.onceFileDetectionMap = onceFileDetectionMap || {}; + this.recursionDetector = {}; + if (recursionDetector) { + for(var fullFilename in recursionDetector) { + if (recursionDetector.hasOwnProperty(fullFilename)) { + this.recursionDetector[fullFilename] = true; + } + } + } +}; + +ImportVisitor.prototype = { + isReplacing: true, + run: function (root) { + var error; + try { + // process the contents + this._visitor.visit(root); + } + catch(e) { + error = e; + } + + this.isFinished = true; + + if (this.importCount === 0) { + this._finish(error); + } + }, + visitImport: function (importNode, visitArgs) { + var importVisitor = this, + evaldImportNode, + inlineCSS = importNode.options.inline; + + if (!importNode.css || inlineCSS) { + + try { + evaldImportNode = importNode.evalForImport(this.env); + } catch(e){ + if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } + // attempt to eval properly and treat as css + importNode.css = true; + // if that fails, this error will be thrown + importNode.error = e; + } + + if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { + importNode = evaldImportNode; + this.importCount++; + var env = new contexts.evalEnv(this.env, this.env.frames.slice(0)); + + if (importNode.options.multiple) { + env.importMultiple = true; + } + + this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, importedAtRoot, fullPath) { + if (e && !e.filename) { + e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; + } + + var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector; + if (!env.importMultiple) { + if (duplicateImport) { + importNode.skip = true; + } else { + importNode.skip = function() { + if (fullPath in importVisitor.onceFileDetectionMap) { + return true; + } + importVisitor.onceFileDetectionMap[fullPath] = true; + return false; + }; + } + } + + var subFinish = function(e) { + importVisitor.importCount--; + + if (importVisitor.importCount === 0 && importVisitor.isFinished) { + importVisitor._finish(e); + } + }; + + if (root) { + importNode.root = root; + importNode.importedFilename = fullPath; + + if (!inlineCSS && (env.importMultiple || !duplicateImport)) { + importVisitor.recursionDetector[fullPath] = true; + new(ImportVisitor)(importVisitor._importer, subFinish, env, importVisitor.onceFileDetectionMap, importVisitor.recursionDetector) + .run(root); + return; + } + } + + subFinish(); + }); + } + } + visitArgs.visitDeeper = false; + return importNode; + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + return ruleNode; + }, + visitDirective: function (directiveNode, visitArgs) { + this.env.frames.unshift(directiveNode); + return directiveNode; + }, + visitDirectiveOut: function (directiveNode) { + this.env.frames.shift(); + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + this.env.frames.unshift(mixinDefinitionNode); + return mixinDefinitionNode; + }, + visitMixinDefinitionOut: function (mixinDefinitionNode) { + this.env.frames.shift(); + }, + visitRuleset: function (rulesetNode, visitArgs) { + this.env.frames.unshift(rulesetNode); + return rulesetNode; + }, + visitRulesetOut: function (rulesetNode) { + this.env.frames.shift(); + }, + visitMedia: function (mediaNode, visitArgs) { + this.env.frames.unshift(mediaNode.rules[0]); + return mediaNode; + }, + visitMediaOut: function (mediaNode) { + this.env.frames.shift(); + } +}; +module.exports = ImportVisitor; + +},{"../contexts.js":2,"./visitor.js":69}],66:[function(require,module,exports){ +var visitors = { + Visitor: require("./visitor"), + ImportVisitor: require('./import-visitor.js'), + ExtendVisitor: require('./extend-visitor.js'), + JoinSelectorVisitor: require('./join-selector-visitor.js'), + ToCSSVisitor: require('./to-css-visitor.js') +}; + +module.exports = visitors; + +},{"./extend-visitor.js":64,"./import-visitor.js":65,"./join-selector-visitor.js":67,"./to-css-visitor.js":68,"./visitor":69}],67:[function(require,module,exports){ +var Visitor = require("./visitor.js"); + +var JoinSelectorVisitor = function() { + this.contexts = [[]]; + this._visitor = new Visitor(this); +}; + +JoinSelectorVisitor.prototype = { + run: function (root) { + return this._visitor.visit(root); + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + + visitRuleset: function (rulesetNode, visitArgs) { + var context = this.contexts[this.contexts.length - 1], + paths = [], selectors; + + this.contexts.push(paths); + + if (! rulesetNode.root) { + selectors = rulesetNode.selectors; + if (selectors) { + selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); + rulesetNode.selectors = selectors.length ? selectors : (selectors = null); + if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } + } + if (!selectors) { rulesetNode.rules = null; } + rulesetNode.paths = paths; + } + }, + visitRulesetOut: function (rulesetNode) { + this.contexts.length = this.contexts.length - 1; + }, + visitMedia: function (mediaNode, visitArgs) { + var context = this.contexts[this.contexts.length - 1]; + mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); + } +}; + +module.exports = JoinSelectorVisitor; + +},{"./visitor.js":69}],68:[function(require,module,exports){ +var tree = require("../tree/index.js"), + Visitor = require("./visitor.js"); + +var ToCSSVisitor = function(env) { + this._visitor = new Visitor(this); + this._env = env; +}; + +ToCSSVisitor.prototype = { + isReplacing: true, + run: function (root) { + return this._visitor.visit(root); + }, + + visitRule: function (ruleNode, visitArgs) { + if (ruleNode.variable) { + return []; + } + return ruleNode; + }, + + visitMixinDefinition: function (mixinNode, visitArgs) { + // mixin definitions do not get eval'd - this means they keep state + // so we have to clear that state here so it isn't used if toCSS is called twice + mixinNode.frames = []; + return []; + }, + + visitExtend: function (extendNode, visitArgs) { + return []; + }, + + visitComment: function (commentNode, visitArgs) { + if (commentNode.isSilent(this._env)) { + return []; + } + return commentNode; + }, + + visitMedia: function(mediaNode, visitArgs) { + mediaNode.accept(this._visitor); + visitArgs.visitDeeper = false; + + if (!mediaNode.rules.length) { + return []; + } + return mediaNode; + }, + + visitDirective: function(directiveNode, visitArgs) { + if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) { + return []; + } + if (directiveNode.name === "@charset") { + // Only output the debug info together with subsequent @charset definitions + // a comment (or @media statement) before the actual @charset directive would + // be considered illegal css as it has to be on the first line + if (this.charset) { + if (directiveNode.debugInfo) { + var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n"); + comment.debugInfo = directiveNode.debugInfo; + return this._visitor.visit(comment); + } + return []; + } + this.charset = true; + } + if (directiveNode.rules && directiveNode.rules.rules) { + this._mergeRules(directiveNode.rules.rules); + } + return directiveNode; + }, + + checkPropertiesInRoot: function(rules) { + var ruleNode; + for(var i = 0; i < rules.length; i++) { + ruleNode = rules[i]; + if (ruleNode instanceof tree.Rule && !ruleNode.variable) { + throw { message: "properties must be inside selector blocks, they cannot be in the root.", + index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null}; + } + } + }, + + visitRuleset: function (rulesetNode, visitArgs) { + var rule, rulesets = []; + if (rulesetNode.firstRoot) { + this.checkPropertiesInRoot(rulesetNode.rules); + } + if (! rulesetNode.root) { + if (rulesetNode.paths) { + rulesetNode.paths = rulesetNode.paths + .filter(function(p) { + var i; + if (p[0].elements[0].combinator.value === ' ') { + p[0].elements[0].combinator = new(tree.Combinator)(''); + } + for(i = 0; i < p.length; i++) { + if (p[i].getIsReferenced() && p[i].getIsOutput()) { + return true; + } + } + return false; + }); + } + + // Compile rules and rulesets + var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; + for (var i = 0; i < nodeRuleCnt; ) { + rule = nodeRules[i]; + if (rule && rule.rules) { + // visit because we are moving them out from being a child + rulesets.push(this._visitor.visit(rule)); + nodeRules.splice(i, 1); + nodeRuleCnt--; + continue; + } + i++; + } + // accept the visitor to remove rules and refactor itself + // then we can decide now whether we want it or not + if (nodeRuleCnt > 0) { + rulesetNode.accept(this._visitor); + } else { + rulesetNode.rules = null; + } + visitArgs.visitDeeper = false; + + nodeRules = rulesetNode.rules; + if (nodeRules) { + this._mergeRules(nodeRules); + nodeRules = rulesetNode.rules; + } + if (nodeRules) { + this._removeDuplicateRules(nodeRules); + nodeRules = rulesetNode.rules; + } + + // now decide whether we keep the ruleset + if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) { + rulesets.splice(0, 0, rulesetNode); + } + } else { + rulesetNode.accept(this._visitor); + visitArgs.visitDeeper = false; + if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) { + rulesets.splice(0, 0, rulesetNode); + } + } + if (rulesets.length === 1) { + return rulesets[0]; + } + return rulesets; + }, + + _removeDuplicateRules: function(rules) { + if (!rules) { return; } + + // remove duplicates + var ruleCache = {}, + ruleList, rule, i; + + for(i = rules.length - 1; i >= 0 ; i--) { + rule = rules[i]; + if (rule instanceof tree.Rule) { + if (!ruleCache[rule.name]) { + ruleCache[rule.name] = rule; + } else { + ruleList = ruleCache[rule.name]; + if (ruleList instanceof tree.Rule) { + ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)]; + } + var ruleCSS = rule.toCSS(this._env); + if (ruleList.indexOf(ruleCSS) !== -1) { + rules.splice(i, 1); + } else { + ruleList.push(ruleCSS); + } + } + } + } + }, + + _mergeRules: function (rules) { + if (!rules) { return; } + + var groups = {}, + parts, + rule, + key; + + for (var i = 0; i < rules.length; i++) { + rule = rules[i]; + + if ((rule instanceof tree.Rule) && rule.merge) { + key = [rule.name, + rule.important ? "!" : ""].join(","); + + if (!groups[key]) { + groups[key] = []; + } else { + rules.splice(i--, 1); + } + + groups[key].push(rule); + } + } + + Object.keys(groups).map(function (k) { + + function toExpression(values) { + return new (tree.Expression)(values.map(function (p) { + return p.value; + })); + } + + function toValue(values) { + return new (tree.Value)(values.map(function (p) { + return p; + })); + } + + parts = groups[k]; + + if (parts.length > 1) { + rule = parts[0]; + var spacedGroups = []; + var lastSpacedGroup = []; + parts.map(function (p) { + if (p.merge==="+") { + if (lastSpacedGroup.length > 0) { + spacedGroups.push(toExpression(lastSpacedGroup)); + } + lastSpacedGroup = []; + } + lastSpacedGroup.push(p); + }); + spacedGroups.push(toExpression(lastSpacedGroup)); + rule.value = toValue(spacedGroups); + } + }); + } +}; + +module.exports = ToCSSVisitor; + +},{"../tree/index.js":43,"./visitor.js":69}],69:[function(require,module,exports){ +var tree = require("../tree/index.js"); + +var _visitArgs = { visitDeeper: true }, + _hasIndexed = false; + +function _noop(node) { + return node; +} + +function indexNodeTypes(parent, ticker) { + // add .typeIndex to tree node types for lookup table + var key, child; + for (key in parent) { + if (parent.hasOwnProperty(key)) { + child = parent[key]; + switch (typeof child) { + case "function": + // ignore bound functions directly on tree which do not have a prototype + // or aren't nodes + if (child.prototype && child.prototype.type) { + child.prototype.typeIndex = ticker++; + } + break; + case "object": + ticker = indexNodeTypes(child, ticker); + break; + } + } + } + return ticker; +} + +var Visitor = function(implementation) { + this._implementation = implementation; + this._visitFnCache = []; + + if (!_hasIndexed) { + indexNodeTypes(tree, 1); + _hasIndexed = true; + } +}; + +Visitor.prototype = { + visit: function(node) { + if (!node) { + return node; + } + + var nodeTypeIndex = node.typeIndex; + if (!nodeTypeIndex) { + return node; + } + + var visitFnCache = this._visitFnCache, + impl = this._implementation, + aryIndx = nodeTypeIndex << 1, + outAryIndex = aryIndx | 1, + func = visitFnCache[aryIndx], + funcOut = visitFnCache[outAryIndex], + visitArgs = _visitArgs, + fnName; + + visitArgs.visitDeeper = true; + + if (!func) { + fnName = "visit" + node.type; + func = impl[fnName] || _noop; + funcOut = impl[fnName + "Out"] || _noop; + visitFnCache[aryIndx] = func; + visitFnCache[outAryIndex] = funcOut; + } + + if (func !== _noop) { + var newNode = func.call(impl, node, visitArgs); + if (impl.isReplacing) { + node = newNode; + } + } + + if (visitArgs.visitDeeper && node && node.accept) { + node.accept(this); + } + + if (funcOut != _noop) { + funcOut.call(impl, node); + } + + return node; + }, + visitArray: function(nodes, nonReplacing) { + if (!nodes) { + return nodes; + } + + var cnt = nodes.length, i; + + // Non-replacing + if (nonReplacing || !this._implementation.isReplacing) { + for (i = 0; i < cnt; i++) { + this.visit(nodes[i]); + } + return nodes; + } + + // Replacing + var out = []; + for (i = 0; i < cnt; i++) { + var evald = this.visit(nodes[i]); + if (!evald.splice) { + out.push(evald); + } else if (evald.length) { + this.flatten(evald, out); + } + } + return out; + }, + flatten: function(arr, out) { + if (!out) { + out = []; + } + + var cnt, i, item, + nestedCnt, j, nestedItem; + + for (i = 0, cnt = arr.length; i < cnt; i++) { + item = arr[i]; + if (!item.splice) { + out.push(item); + continue; + } + + for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { + nestedItem = item[j]; + if (!nestedItem.splice) { + out.push(nestedItem); + } else if (nestedItem.length) { + this.flatten(nestedItem, out); + } + } + } + + return out; + } +}; +module.exports = Visitor; + +},{"../tree/index.js":43}]},{},[1]) \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.less b/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.less new file mode 100644 index 000000000..7c60c0047 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.less @@ -0,0 +1,3 @@ +.a { + prop: (3 / #fff); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.txt b/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.txt new file mode 100644 index 000000000..643bd593e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/console-errors/test-error.txt @@ -0,0 +1,2 @@ +less: OperationError: Can't substract or divide a color from a number in {pathhref}console-errors/test-error.less on line null, column 0: +1 prop: (3 / #fff); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/global-vars/simple.less b/node_modules/less-middleware/node_modules/less/test/browser/less/global-vars/simple.less new file mode 100644 index 000000000..00545b164 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/global-vars/simple.less @@ -0,0 +1,3 @@ +.test { + color: @global-var; +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls.less b/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls.less new file mode 100644 index 000000000..290e6b412 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls.less @@ -0,0 +1,4 @@ +@import "modify-this.css"; +.modify { + my-url: url("a.png"); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls2.less b/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls2.less new file mode 100644 index 000000000..b834bb9e1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/imports/urls2.less @@ -0,0 +1,4 @@ +@import "modify-again.css"; +.modify { + my-url: url("b.png"); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/imports/simple2.less b/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/imports/simple2.less new file mode 100644 index 000000000..49fcf875f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/imports/simple2.less @@ -0,0 +1,4 @@ +@var2: blue; +.testisimported { + color: gainsboro; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/simple.less b/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/simple.less new file mode 100644 index 000000000..ad998c5be --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/modify-vars/simple.less @@ -0,0 +1,8 @@ +@import "imports/simple2"; +@var1: red; +@scale: 10; +.test { + color1: @var1; + color2: @var2; + scalar: @scale +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/postProcessor/postProcessor.less b/node_modules/less-middleware/node_modules/less/test/browser/less/postProcessor/postProcessor.less new file mode 100644 index 000000000..0d4c0304d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/postProcessor/postProcessor.less @@ -0,0 +1,4 @@ +@color: white; +.test { + color: @color; +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/relative-urls/urls.less b/node_modules/less-middleware/node_modules/less/test/browser/less/relative-urls/urls.less new file mode 100644 index 000000000..b33fdfa60 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/relative-urls/urls.less @@ -0,0 +1,33 @@ +@import ".././imports/urls.less"; +@import "http://localhost:8081/test/browser/less/imports/urls2.less"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath-relative/urls.less b/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath-relative/urls.less new file mode 100644 index 000000000..1843fb224 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath-relative/urls.less @@ -0,0 +1,33 @@ +@import "../imports/urls.less"; +@import "http://localhost:8081/test/browser/less/imports/urls2.less"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath/urls.less b/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath/urls.less new file mode 100644 index 000000000..1843fb224 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/rootpath/urls.less @@ -0,0 +1,33 @@ +@import "../imports/urls.less"; +@import "http://localhost:8081/test/browser/less/imports/urls2.less"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/less/urls.less b/node_modules/less-middleware/node_modules/less/test/browser/less/urls.less new file mode 100644 index 000000000..596e5e7b8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/less/urls.less @@ -0,0 +1,57 @@ +@import "imports/urls.less"; +@import "http://localhost:8081/test/browser/less/imports/urls2.less"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} +#data-uri { + uri: data-uri('image/jpeg;base64', '../../data/image.jpg'); +} + +#data-uri-guess { + uri: data-uri('../../data/image.jpg'); +} + +#data-uri-ascii { + uri-1: data-uri('text/html', '../../data/page.html'); + uri-2: data-uri('../../data/page.html'); +} + +#data-uri-toobig { + uri: data-uri('../../data/data-uri-fail.png'); +} +#svg-functions { + background-image: svg-gradient(to bottom, black, white); + background-image: svg-gradient(to bottom, black, orange 3%, white); + @green_5: green 5%; + @orange_percentage: 3%; + @orange_color: orange; + background-image: svg-gradient(to bottom, (mix(black, white) + #444) 1%, @orange_color @orange_percentage, ((@green_5)), white 95%); +} diff --git a/node_modules/less-middleware/node_modules/less/test/browser/phantom-runner.js b/node_modules/less-middleware/node_modules/less/test/browser/phantom-runner.js new file mode 100644 index 000000000..8233deb80 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/phantom-runner.js @@ -0,0 +1,150 @@ +var webpage = require('webpage'); +var server = require('webserver').create(); +var system = require('system'); +var fs = require('fs'); +var host; +var port = 8081; + +var listening = server.listen(port, function(request, response) { + //console.log("Requested " + request.url); + + var filename = ("test/" + request.url.slice(1)).replace(/[\\\/]/g, fs.separator); + + if (!fs.exists(filename) || !fs.isFile(filename)) { + response.statusCode = 404; + response.write("

    File Not Found

    File:" + filename + "

    "); + response.close(); + return; + } + + // we set the headers here + response.statusCode = 200; + response.headers = { + "Cache": "no-cache", + "Content-Type": "text/html" + }; + + response.write(fs.read(filename)); + + response.close(); +}); +if (!listening) { + console.log("could not create web server listening on port " + port); + phantom.exit(); +} + +/** + * Wait until the test condition is true or a timeout occurs. Useful for waiting + * on a server response or for a ui change (fadeIn, etc.) to occur. + * + * @param testFx javascript condition that evaluates to a boolean, + * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or + * as a callback function. + * @param onReady what to do when testFx condition is fulfilled, + * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or + * as a callback function. + * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. + * @param timeOutErrorMessage the error message if time out occurs + */ + +function waitFor(testFx, onReady, timeOutMillis, timeOutErrorMessage) { + var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 10001, //< Default Max Timeout is 10s + start = new Date().getTime(), + condition = false, + interval = setInterval(function() { + if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) { + // If not time-out yet and condition not yet fulfilled + condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code + } else { + if (!condition) { + // If condition still not fulfilled (timeout but condition is 'false') + console.log(timeOutErrorMessage || "'waitFor()' timeout"); + phantom.exit(1); + } else { + // Condition fulfilled (timeout and/or condition is 'true') + typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled + clearInterval(interval); //< Stop this interval + } + } + }, 100); //< repeat check every 100ms +} + +function testPage(url) { + var page = webpage.create(); + page.open(url, function(status) { + if (status !== "success") { + console.log("Unable to access network - " + status); + phantom.exit(); + } else { + waitFor(function() { + return page.evaluate(function() { + return document.body && document.body.querySelector && + document.body.querySelector('.symbolSummary .pending') === null && + document.body.querySelector('.results') !== null; + }); + }, function() { + page.onConsoleMessage = function(msg) { + console.log(msg); + }; + var exitCode = page.evaluate(function() { + console.log(''); + console.log(document.body.querySelector('.description').innerText); + var list = document.body.querySelectorAll('.results > #details > .specDetail.failed'); + if (list && list.length > 0) { + console.log(''); + console.log(list.length + ' test(s) FAILED:'); + for (var i = 0; i < list.length; ++i) { + var el = list[i], + desc = el.querySelector('.description'), + msg = el.querySelector('.resultMessage.fail'); + console.log(''); + console.log(desc.innerText); + console.log(msg.innerText); + console.log(''); + } + return 1; + } else { + console.log(document.body.querySelector('.alert > .passingAlert.bar').innerText); + return 0; + } + }); + testFinished(exitCode); + }, + 10000, // 10 second timeout + "Test failed waiting for jasmine results on page: " + url); + } + }); +} + +function scanDirectory(path, regex) { + var files = []; + fs.list(path).forEach(function(file) { + if (file.match(regex)) { + files.push(file); + } + }); + return files; +} + +var totalTests = 0, + totalFailed = 0, + totalDone = 0; + +function testFinished(failed) { + if (failed) { + totalFailed++; + } + totalDone++; + if (totalDone === totalTests) { + phantom.exit(totalFailed > 0 ? 1 : 0); + } +} + +if (system.args.length != 2 && system.args[1] != "--no-tests") { + var files = scanDirectory("test/browser/", /^test-runner-.+\.htm$/); + totalTests = files.length; + console.log("found " + files.length + " tests"); + files.forEach(function(file) { + testPage("http://localhost:8081/browser/" + file); + }); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-options.js new file mode 100644 index 000000000..3d73323e7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-options.js @@ -0,0 +1,42 @@ +var less = {}; + +// There originally run inside describe method. However, since they have not +// been inside it, they run at jasmine compile time (not runtime). It all +// worked cause less.js was in async mode and custom phantom runner had +// different setup then grunt-contrib-jasmine. They have been created before +// less.js run, even as they have been defined in spec. + +// test inline less in style tags by grabbing an assortment of less files and doing `@import`s +var testFiles = ['charsets', 'colors', 'comments', 'css-3', 'strings', 'media', 'mixins'], + testSheets = []; + +// setup style tags with less and link tags pointing to expected css output +for (var i = 0; i < testFiles.length; i++) { + var file = testFiles[i], + lessPath = '/test/less/' + file + '.less', + cssPath = '/test/css/' + file + '.css', + lessStyle = document.createElement('style'), + cssLink = document.createElement('link'), + lessText = '@import "' + lessPath + '";'; + + lessStyle.type = 'text/less'; + lessStyle.id = file; + lessStyle.href = file; + + if (lessStyle.styleSheet) { + lessStyle.styleSheet.cssText = lessText; + } else { + lessStyle.innerHTML = lessText; + } + + cssLink.rel = 'stylesheet'; + cssLink.type = 'text/css'; + cssLink.href = cssPath; + cssLink.id = 'expected-' + file; + + var head = document.getElementsByTagName('head')[0]; + + head.appendChild(lessStyle); + head.appendChild(cssLink); + testSheets[i] = lessStyle; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-spec.js new file mode 100644 index 000000000..ead27b4a0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-browser-spec.js @@ -0,0 +1,12 @@ +describe("less.js browser behaviour", function() { + testLessEqualsInDocument(); + + it("has some log messages", function() { + expect(logMessages.length).toBeGreaterThan(0); + }); + + for (var i = 0; i < testFiles.length; i++) { + var sheet = testSheets[i]; + testSheet(sheet); + } +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-console-errors.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-console-errors.js new file mode 100644 index 000000000..7af7bdb19 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-console-errors.js @@ -0,0 +1,5 @@ +less.errorReporting = 'console'; + +describe("less.js error reporting console test", function() { + testLessErrorsInDocument(true); +}); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-options.js new file mode 100644 index 000000000..840ba5d63 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-options.js @@ -0,0 +1,5 @@ +var less = { + strictUnits: true, + strictMath: true +}; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-spec.js new file mode 100644 index 000000000..0b7206769 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-errors-spec.js @@ -0,0 +1,4 @@ +describe("less.js error tests", function() { + testLessErrorsInDocument(); +}); + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-options.js new file mode 100644 index 000000000..f313b2f77 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-options.js @@ -0,0 +1,4 @@ +var less = {}; +less.globalVars = { + "@global-var": "red" +}; diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-spec.js new file mode 100644 index 000000000..6dba89170 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-global-vars-spec.js @@ -0,0 +1,3 @@ +describe("less.js global vars", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-options.js new file mode 100644 index 000000000..9e4b95921 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-options.js @@ -0,0 +1,4 @@ +var less = {}; +less.strictMath = false; +less.strictUnits = false; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-spec.js new file mode 100644 index 000000000..6ba7bfae7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-legacy-spec.js @@ -0,0 +1,3 @@ +describe("less.js legacy tests", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-main-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-main-options.js new file mode 100644 index 000000000..df51782a8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-main-options.js @@ -0,0 +1,15 @@ +var less = {}; +less.strictMath = true; +less.functions = { + add: function(a, b) { + return new(less.tree.Dimension)(a.value + b.value); + }, + increment: function(a) { + return new(less.tree.Dimension)(a.value + 1); + }, + _color: function(str) { + if (str.value === "evil red") { + return new(less.tree.Color)("600"); + } + } +}; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-main-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-main-spec.js new file mode 100644 index 000000000..b5261e754 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-main-spec.js @@ -0,0 +1,3 @@ +describe("less.js main tests", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-options.js new file mode 100644 index 000000000..2799ad55d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-options.js @@ -0,0 +1,2 @@ +/* exported less */ +var less = {}; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-spec.js new file mode 100644 index 000000000..0ce49986f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-modify-vars-spec.js @@ -0,0 +1,43 @@ +var alreadyRun = false; + +describe("less.js modify vars", function() { + beforeEach(function() { + // simulating "setUp" or "beforeAll" method + var lessOutputObj; + if (alreadyRun) + return; + + alreadyRun = true; + + // wait until the sheet is compiled first time + waitsFor(function() { + lessOutputObj = document.getElementById("less:test-less-simple"); + return lessOutputObj !== null; + }, "first generation of less:test-less-simple", 7000); + + // modify variables + runs(function() { + lessOutputObj.type = "not compiled yet"; + less.modifyVars({ + var1: "green", + var2: "purple", + scale: 20 + }); + }); + + // wait until variables are modified + waitsFor(function() { + lessOutputObj = document.getElementById("less:test-less-simple"); + return lessOutputObj !== null && lessOutputObj.type === "text/css"; + }, "second generation of less:test-less-simple", 7000); + + }); + + testLessEqualsInDocument(); + it("Should log only 2 XHR requests", function() { + var xhrLogMessages = logMessages.filter(function(item) { + return (/XHR: Getting '/).test(item); + }); + expect(xhrLogMessages.length).toEqual(2); + }); +}); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-options.js new file mode 100644 index 000000000..2a4649447 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-options.js @@ -0,0 +1,4 @@ +var less = {}; + +less.strictUnits = true; +less.javascriptEnabled = false; diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-spec.js new file mode 100644 index 000000000..38aefe292 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-no-js-errors-spec.js @@ -0,0 +1,4 @@ +describe("less.js javascript disabled error tests", function() { + testLessErrorsInDocument(); +}); + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor-options.js new file mode 100644 index 000000000..94044da21 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor-options.js @@ -0,0 +1,4 @@ +var less = {}; +less.postProcessor = function(styles) { + return 'hr {height:50px;}\n' + styles; +}; diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor.js new file mode 100644 index 000000000..be9eb24bb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-postProcessor.js @@ -0,0 +1,3 @@ +describe("less.js postProcessor", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-production-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-production-options.js new file mode 100644 index 000000000..f8189d6a8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-production-options.js @@ -0,0 +1,3 @@ +var less = {}; +less.env = "production"; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-production-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-production-spec.js new file mode 100644 index 000000000..8c8d8f42f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-production-spec.js @@ -0,0 +1,5 @@ +describe("less.js production behaviour", function() { + it("doesn't log any messages", function() { + expect(logMessages.length).toEqual(0); + }); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-options.js new file mode 100644 index 000000000..a20eb591e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-options.js @@ -0,0 +1,3 @@ +var less = {}; +less.relativeUrls = true; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-spec.js new file mode 100644 index 000000000..b13911ee8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-relative-urls-spec.js @@ -0,0 +1,3 @@ +describe("less.js browser test - relative url's", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-options.js new file mode 100644 index 000000000..5e475bb40 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-options.js @@ -0,0 +1,3 @@ +var less = {}; +less.rootpath = "https://www.github.com/"; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-options.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-options.js new file mode 100644 index 000000000..f97baa4b8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-options.js @@ -0,0 +1,4 @@ +var less = {}; +less.rootpath = "https://www.github.com/cloudhead/less.js/"; +less.relativeUrls = true; + diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-spec.js new file mode 100644 index 000000000..cd905739a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-relative-spec.js @@ -0,0 +1,3 @@ +describe("less.js browser test - rootpath and relative url's", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-spec.js b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-spec.js new file mode 100644 index 000000000..b7b9ba1d6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/runner-rootpath-spec.js @@ -0,0 +1,3 @@ +describe("less.js browser test - rootpath url's", function() { + testLessEqualsInDocument(); +}); diff --git a/node_modules/less-middleware/node_modules/less/test/browser/test-runner-template.tmpl b/node_modules/less-middleware/node_modules/less/test/browser/test-runner-template.tmpl new file mode 100644 index 000000000..17f644f5f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/browser/test-runner-template.tmpl @@ -0,0 +1,47 @@ + + + + + Jasmine Spec Runner + + + <% var generateScriptTags = function(allScripts) { allScripts.forEach(function(script){ %> + + <% }); }; %> + + + <% scripts.src.forEach(function(fullLessName) { + var pathParts = fullLessName.split('/'); + var fullCssName = fullLessName.replace(/less/g, 'css'); + var lessName = pathParts[pathParts.length - 1]; + var name = lessName.split('.')[0]; %> + + + + <% }); %> + + + <% css.forEach(function(style){ %> + + <% }) %> + + + <% generateScriptTags([].concat(scripts.polyfills, scripts.jasmine)); %> + + + <% generateScriptTags(scripts.helpers); %> + + + <% generateScriptTags(scripts.vendor); %> + + + <% generateScriptTags(scripts.specs); %> + + + <% generateScriptTags([].concat(scripts.reporters, scripts.start)); %> + + + + + + diff --git a/node_modules/less-middleware/node_modules/less/test/css/charsets.css b/node_modules/less-middleware/node_modules/less/test/css/charsets.css new file mode 100644 index 000000000..9f44090c9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/charsets.css @@ -0,0 +1 @@ +@charset "UTF-8"; diff --git a/node_modules/less-middleware/node_modules/less/test/css/colors.css b/node_modules/less-middleware/node_modules/less/test/css/colors.css new file mode 100644 index 000000000..08a22abb8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/colors.css @@ -0,0 +1,87 @@ +#yelow #short { + color: #fea; +} +#yelow #long { + color: #ffeeaa; +} +#yelow #rgba { + color: rgba(255, 238, 170, 0.1); +} +#yelow #argb { + color: #1affeeaa; +} +#blue #short { + color: #00f; +} +#blue #long { + color: #0000ff; +} +#blue #rgba { + color: rgba(0, 0, 255, 0.1); +} +#blue #argb { + color: #1a0000ff; +} +#alpha #hsla { + color: rgba(61, 45, 41, 0.6); +} +#overflow .a { + color: #000000; +} +#overflow .b { + color: #ffffff; +} +#overflow .c { + color: #ffffff; +} +#overflow .d { + color: #00ff00; +} +#overflow .e { + color: rgba(0, 31, 255, 0.42); +} +#grey { + color: #c8c8c8; +} +#333333 { + color: #333333; +} +#808080 { + color: #808080; +} +#00ff00 { + color: #00ff00; +} +.lightenblue { + color: #3333ff; +} +.darkenblue { + color: #0000cc; +} +.unknowncolors { + color: blue2; + border: 2px solid superred; +} +.transparent { + color: transparent; + background-color: rgba(0, 0, 0, 0); +} +#alpha #fromvar { + opacity: 0.7; +} +#alpha #short { + opacity: 1; +} +#alpha #long { + opacity: 1; +} +#alpha #rgba { + opacity: 0.2; +} +#alpha #hsl { + opacity: 1; +} +#percentage { + color: 255; + border-color: rgba(255, 0, 0, 0.5); +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/comments.css b/node_modules/less-middleware/node_modules/less/test/css/comments.css new file mode 100644 index 000000000..d3c57b4d6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/comments.css @@ -0,0 +1,77 @@ +/******************\ +* * +* Comment Header * +* * +\******************/ +/* + + Comment + +*/ +/* + * Comment Test + * + * - cloudhead (http://cloudhead.net) + * + */ +/* Colors + * ------ + * #EDF8FC (background blue) + * #166C89 (darkest blue) + * + * Text: + * #333 (standard text) // A comment within a comment! + * #1F9EC9 (standard link) + * + */ +/* @group Variables +------------------- */ +#comments, +.comments { + /**/ + color: red; + /* A C-style comment */ + /* A C-style comment */ + background-color: orange; + font-size: 12px; + /* lost comment */ + content: "content"; + border: 1px solid black; + padding: 0; + margin: 2em; +} +/* commented out + #more-comments { + color: grey; + } +*/ +.selector, +.lots, +.comments { + color: #808080, /* blue */ #ffa500; + -webkit-border-radius: 2px /* webkit only */; + -moz-border-radius: 8px /* moz only with operation */; +} +.test { + color: 1px; +} +.sr-only-focusable { + clip: auto; +} +@-webkit-keyframes hover { + 0% { + color: red; + } +} +#last { + color: #0000ff; +} +/* */ +/* { */ +/* */ +/* */ +/* */ +#div { + color: #A33; +} +/* } */ diff --git a/node_modules/less-middleware/node_modules/less/test/css/compression/compression.css b/node_modules/less-middleware/node_modules/less/test/css/compression/compression.css new file mode 100644 index 000000000..f9cc90a3e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/compression/compression.css @@ -0,0 +1,3 @@ +#colours{color1:#fea;color2:#fea;color3:rgba(255,238,170,0.1);string:"#ffeeaa";/*! but not this type + Note preserved whitespace + */}dimensions{val:.1px;val:0;val:4cm;val:.2;val:5;angles-must-have-unit:0deg;durations-must-have-unit:0s;length-doesnt-have-unit:0;width:auto\9}@page{marks:none;@top-left-corner{vertical-align:top}@top-left{vertical-align:top}}.shadow^.dom,body^^.shadow{display:done} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/css/css-3.css b/node_modules/less-middleware/node_modules/less/test/css/css-3.css new file mode 100644 index 000000000..c6f4c629c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/css-3.css @@ -0,0 +1,138 @@ +.comma-delimited { + text-shadow: -1px -1px 1px #ff0000, 6px 5px 5px #ffff00; + -moz-box-shadow: 0pt 0pt 2px rgba(255, 255, 255, 0.4) inset, 0pt 4px 6px rgba(255, 255, 255, 0.4) inset; + -webkit-transform: rotate(0deg); +} +@font-face { + font-family: Headline; + unicode-range: U+??????, U+0???, U+0-7F, U+A5; +} +.other { + -moz-transform: translate(0, 11em) rotate(-90deg); + transform: rotateX(45deg); +} +.item[data-cra_zy-attr1b-ut3=bold] { + font-weight: bold; +} +p:not([class*="lead"]) { + color: black; +} +input[type="text"].class#id[attr=32]:not(1) { + color: white; +} +div#id.class[a=1][b=2].class:not(1) { + color: white; +} +ul.comma > li:not(:only-child)::after { + color: white; +} +ol.comma > li:nth-last-child(2)::after { + color: white; +} +li:nth-child(4n+1), +li:nth-child(-5n), +li:nth-child(-n+2) { + color: white; +} +a[href^="http://"] { + color: black; +} +a[href$="http://"] { + color: black; +} +form[data-disabled] { + color: black; +} +p::before { + color: black; +} +#issue322 { + -webkit-animation: anim2 7s infinite ease-in-out; +} +@-webkit-keyframes frames { + 0% { + border: 1px; + } + 5.5% { + border: 2px; + } + 100% { + border: 3px; + } +} +@keyframes fontbulger1 { + to { + font-size: 15px; + } + from, + to { + font-size: 12px; + } + 0%, + 100% { + font-size: 12px; + } +} +.units { + font: 1.2rem/2rem; + font: 8vw/9vw; + font: 10vh/12vh; + font: 12vm/15vm; + font: 12vmin/15vmin; + font: 1.2ch/1.5ch; +} +@supports ( box-shadow: 2px 2px 2px black ) or + ( -moz-box-shadow: 2px 2px 2px black ) { + .outline { + box-shadow: 2px 2px 2px black; + -moz-box-shadow: 2px 2px 2px black; + } +} +@-x-document url-prefix(""github.com"") { + h1 { + color: red; + } +} +@viewport { + font-size: 10px; +} +@namespace foo url(http://www.example.com); +foo|h1 { + color: blue; +} +foo|* { + color: yellow; +} +|h1 { + color: red; +} +*|h1 { + color: green; +} +h1 { + color: green; +} +.upper-test { + UpperCaseProperties: allowed; +} +@host { + div { + display: block; + } +} +::distributed(input::placeholder) { + color: #b3b3b3; +} +.shadow ^ .dom, +body ^^ .shadow { + display: done; +} +:host(.sel .a), +:host-context(.sel .b), +.sel /deep/ .b, +::content .sel { + type: shadow-dom; +} +#issue2066 { + background: url('/images/icon-team.svg') 0 0 / contain; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/css-escapes.css b/node_modules/less-middleware/node_modules/less/test/css/css-escapes.css new file mode 100644 index 000000000..4d343aa62 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/css-escapes.css @@ -0,0 +1,24 @@ +.escape\|random\|char { + color: red; +} +.mixin\!tUp { + font-weight: bold; +} +.\34 04 { + background: red; +} +.\34 04 strong { + color: #ff00ff; + font-weight: bold; +} +.trailingTest\+ { + color: red; +} +/* This hideous test of hideousness checks for the selector "blockquote" with various permutations of hex escapes */ +\62\6c\6f \63 \6B \0071 \000075o\74 e { + color: silver; +} +[ng\:cloak], +ng\:form { + display: none; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/css-guards.css b/node_modules/less-middleware/node_modules/less/test/css/css-guards.css new file mode 100644 index 000000000..f4b8a1087 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/css-guards.css @@ -0,0 +1,37 @@ +.light { + color: green; +} +.see-the { + color: green; +} +.hide-the { + color: green; +} +.multiple-conditions-1 { + color: red; +} +.inheritance .test { + color: black; +} +.inheritance:hover { + color: pink; +} +.clsWithGuard { + dispaly: none; +} +.dont-split-me-up { + width: 1px; + color: red; + height: 1px; +} + + .dont-split-me-up { + sibling: true; +} +.scope-check { + sub-prop: 2px; + prop: 1px; +} +.scope-check-2 { + sub-prop: 2px; + prop: 1px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/css.css b/node_modules/less-middleware/node_modules/less/test/css/css.css new file mode 100644 index 000000000..b011a7e38 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/css.css @@ -0,0 +1,95 @@ +@charset "utf-8"; +div { + color: black; +} +div { + width: 99%; +} +* { + min-width: 45em; +} +h1, +h2 > a > p, +h3 { + color: none; +} +div.class { + color: blue; +} +div#id { + color: green; +} +.class#id { + color: purple; +} +.one.two.three { + color: grey; +} +@media print { + * { + font-size: 3em; + } +} +@media screen { + * { + font-size: 10px; + } +} +@font-face { + font-family: 'Garamond Pro'; +} +a:hover, +a:link { + color: #999; +} +p, +p:first-child { + text-transform: none; +} +q:lang(no) { + quotes: none; +} +p + h1 { + font-size: 2.2em; +} +#shorthands { + border: 1px solid #000; + font: 12px/16px Arial; + font: 100%/16px Arial; + margin: 1px 0; + padding: 0 auto; +} +#more-shorthands { + margin: 0; + padding: 1px 0 2px 0; + font: normal small / 20px 'Trebuchet MS', Verdana, sans-serif; + font: 0/0 a; + border-radius: 5px / 10px; +} +.misc { + -moz-border-radius: 2px; + display: -moz-inline-stack; + width: .1em; + background-color: #009998; + background: -webkit-gradient(linear, left top, left bottom, from(#ff0000), to(#0000ff)); + margin: ; + filter: alpha(opacity=100); + width: auto\9; +} +.misc .nested-multiple { + multiple-semi-colons: yes; +} +#important { + color: red !important; + width: 100%!important; + height: 20px ! important; +} +@font-face { + font-family: font-a; +} +@font-face { + font-family: font-b; +} +.æøå { + margin: 0; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-all.css b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-all.css new file mode 100644 index 000000000..87022aecc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-all.css @@ -0,0 +1,49 @@ +@charset "UTF-8"; +/* line 1, {pathimport}test.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000031}} +/* @charset "ISO-8859-1"; */ +/* line 23, {pathimport}test.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\0000323}} +.tst3 { + color: grey; +} +/* line 15, {path}linenumbers.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\0000315}} +.test1 { + color: black; +} +/* line 6, {path}linenumbers.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\000036}} +.test2 { + color: red; +} +@media all { + /* line 5, {pathimport}test.less */ + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000035}} + .tst { + color: black; + } +} +@media all and screen { + /* line 7, {pathimport}test.less */ + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000037}} + .tst { + color: red; + } + /* line 9, {pathimport}test.less */ + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000039}} + .tst .tst3 { + color: white; + } +} +/* line 18, {pathimport}test.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\0000318}} +.tst2 { + color: white; +} +/* line 27, {path}linenumbers.less */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\0000327}} +.test { + color: red; + width: 2; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-comments.css b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-comments.css new file mode 100644 index 000000000..e5d6bb385 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-comments.css @@ -0,0 +1,40 @@ +@charset "UTF-8"; +/* line 1, {pathimport}test.less */ +/* @charset "ISO-8859-1"; */ +/* line 23, {pathimport}test.less */ +.tst3 { + color: grey; +} +/* line 15, {path}linenumbers.less */ +.test1 { + color: black; +} +/* line 6, {path}linenumbers.less */ +.test2 { + color: red; +} +@media all { + /* line 5, {pathimport}test.less */ + .tst { + color: black; + } +} +@media all and screen { + /* line 7, {pathimport}test.less */ + .tst { + color: red; + } + /* line 9, {pathimport}test.less */ + .tst .tst3 { + color: white; + } +} +/* line 18, {pathimport}test.less */ +.tst2 { + color: white; +} +/* line 27, {path}linenumbers.less */ +.test { + color: red; + width: 2; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-mediaquery.css b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-mediaquery.css new file mode 100644 index 000000000..e252ab3c2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/debug/linenumbers-mediaquery.css @@ -0,0 +1,40 @@ +@charset "UTF-8"; +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000031}} +/* @charset "ISO-8859-1"; */ +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\0000323}} +.tst3 { + color: grey; +} +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\0000315}} +.test1 { + color: black; +} +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\000036}} +.test2 { + color: red; +} +@media all { + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000035}} + .tst { + color: black; + } +} +@media all and screen { + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000037}} + .tst { + color: red; + } + @media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\000039}} + .tst .tst3 { + color: white; + } +} +@media -sass-debug-info{filename{font-family:file\:\/\/{pathimportesc}test\.less}line{font-family:\0000318}} +.tst2 { + color: white; +} +@media -sass-debug-info{filename{font-family:file\:\/\/{pathesc}linenumbers\.less}line{font-family:\0000327}} +.test { + color: red; + width: 2; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/detached-rulesets.css b/node_modules/less-middleware/node_modules/less/test/css/detached-rulesets.css new file mode 100644 index 000000000..300c08d09 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/detached-rulesets.css @@ -0,0 +1,71 @@ +.wrap-selector { + color: black; + one: 1px; + four: magic-frame; + visible-one: visible; + visible-two: visible; +} +.wrap-selector { + color: red; + visible-one: visible; + visible-two: visible; +} +.wrap-selector { + color: black; + background: white; + visible-one: visible; + visible-two: visible; +} +header { + background: blue; +} +@media screen and (min-width: 1200) { + header { + background: red; + } +} +html.lt-ie9 header { + background: red; +} +.wrap-selector { + test: extra-wrap; + visible-one: visible; + visible-two: visible; +} +.wrap-selector .wrap-selector { + test: wrapped-twice; + visible-one: visible; + visible-two: visible; +} +.wrap-selector { + test-func: 90; + test-arithmetic: 18px; + visible-one: visible; + visible-two: visible; +} +.without-mixins { + b: 1; +} +@media (orientation: portrait) and tv { + .my-selector { + background-color: black; + } +} +@media (orientation: portrait) and widescreen and print and tv { + .triple-wrapped-mq { + triple: true; + } +} +@media (orientation: portrait) and widescreen and tv { + .triple-wrapped-mq { + triple: true; + } +} +@media (orientation: portrait) and tv { + .triple-wrapped-mq { + triple: true; + } +} +.a { + test: test; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/empty.css b/node_modules/less-middleware/node_modules/less/test/css/empty.css new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-chaining.css b/node_modules/less-middleware/node_modules/less/test/css/extend-chaining.css new file mode 100644 index 000000000..820e134f0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-chaining.css @@ -0,0 +1,81 @@ +.a, +.b, +.c { + color: black; +} +.f, +.e, +.d { + color: black; +} +.g.h, +.i.j.h, +.k.j.h { + color: black; +} +.i.j, +.k.j { + color: white; +} +.l, +.m, +.n, +.o, +.p, +.q, +.r, +.s, +.t { + color: black; +} +.u, +.v.u.v { + color: black; +} +.w, +.v.w.v { + color: black; +} +.x, +.y, +.z { + color: x; +} +.y, +.z, +.x { + color: y; +} +.z, +.x, +.y { + color: z; +} +.va, +.vb, +.vc { + color: black; +} +.vb, +.vc { + color: white; +} +@media tv { + .ma, + .mb, + .mc { + color: black; + } + .md, + .ma, + .mb, + .mc { + color: white; + } +} +@media tv and plasma { + .me, + .mf { + background: red; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-clearfix.css b/node_modules/less-middleware/node_modules/less/test/css/extend-clearfix.css new file mode 100644 index 000000000..966892a27 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-clearfix.css @@ -0,0 +1,19 @@ +.clearfix, +.foo, +.bar { + *zoom: 1; +} +.clearfix:after, +.foo:after, +.bar:after { + content: ''; + display: block; + clear: both; + height: 0; +} +.foo { + color: red; +} +.bar { + color: blue; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-exact.css b/node_modules/less-middleware/node_modules/less/test/css/extend-exact.css new file mode 100644 index 000000000..beff4133e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-exact.css @@ -0,0 +1,37 @@ +.replace.replace .replace, +.c.replace + .replace .replace, +.replace.replace .c, +.c.replace + .replace .c, +.rep_ace { + prop: copy-paste-replace; +} +.a .b .c { + prop: not_effected; +} +.a, +.effected { + prop: is_effected; +} +.a .b { + prop: not_effected; +} +.a .b.c { + prop: not_effected; +} +.c .b .a, +.a .b .a, +.c .a .a, +.a .a .a, +.c .b .c, +.a .b .c, +.c .a .c, +.a .a .c { + prop: not_effected; +} +.e.e, +.dbl { + prop: extend-double; +} +.e.e:hover { + hover: not-extended; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-media.css b/node_modules/less-middleware/node_modules/less/test/css/extend-media.css new file mode 100644 index 000000000..23bd7b85c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-media.css @@ -0,0 +1,24 @@ +.ext1 .ext2, +.all .ext2 { + background: black; +} +@media tv { + .ext1 .ext3, + .tv-lowres .ext3, + .all .ext3 { + color: white; + } + .tv-lowres { + background: blue; + } +} +@media tv and hires { + .ext1 .ext4, + .tv-hires .ext4, + .all .ext4 { + color: green; + } + .tv-hires { + background: red; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-nest.css b/node_modules/less-middleware/node_modules/less/test/css/extend-nest.css new file mode 100644 index 000000000..2c3905d95 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-nest.css @@ -0,0 +1,57 @@ +.sidebar, +.sidebar2, +.type1 .sidebar3, +.type2.sidebar4 { + width: 300px; + background: red; +} +.sidebar .box, +.sidebar2 .box, +.type1 .sidebar3 .box, +.type2.sidebar4 .box { + background: #FFF; + border: 1px solid #000; + margin: 10px 0; +} +.sidebar2 { + background: blue; +} +.type1 .sidebar3 { + background: green; +} +.type2.sidebar4 { + background: red; +} +.button, +.submit { + color: black; +} +.button:hover, +.submit:hover { + color: white; +} +.button2 :hover { + nested: white; +} +.button2 :hover { + notnested: black; +} +.amp-test-h, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-a.amp-test-d.amp-test-b.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-a.amp-test-e.amp-test-g, +.amp-test-f.amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e + .amp-test-c .amp-test-b.amp-test-d.amp-test-b.amp-test-e.amp-test-g { + test: extended by masses of selectors; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend-selector.css b/node_modules/less-middleware/node_modules/less/test/css/extend-selector.css new file mode 100644 index 000000000..da47254b3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend-selector.css @@ -0,0 +1,80 @@ +.error, +.badError { + border: 1px #f00; + background: #fdd; +} +.error.intrusion, +.badError.intrusion { + font-size: 1.3em; + font-weight: bold; +} +.intrusion .error, +.intrusion .badError { + display: none; +} +.badError { + border-width: 3px; +} +.foo .bar, +.foo .baz, +.ext1 .ext2 .bar, +.ext1 .ext2 .baz, +.ext3 .bar, +.ext3 .baz, +.ext4 .bar, +.ext4 .baz { + display: none; +} +div.ext5, +.ext6 > .ext5, +div.ext7, +.ext6 > .ext7 { + width: 100px; +} +.ext, +.a .c, +.b .c { + test: 1; +} +.a, +.b { + test: 2; +} +.a .c, +.b .c { + test: 3; +} +.a .c .d, +.b .c .d { + test: 4; +} +.replace.replace .replace, +.c.replace + .replace .replace, +.replace.replace .c, +.c.replace + .replace .c, +.rep_ace.rep_ace .rep_ace, +.c.rep_ace + .rep_ace .rep_ace, +.rep_ace.rep_ace .c, +.c.rep_ace + .rep_ace .c { + prop: copy-paste-replace; +} +.attributes [data="test"], +.attributes .attributes .attribute-test { + extend: attributes; +} +.attributes [data], +.attributes .attributes .attribute-test2 { + extend: attributes2; +} +.attributes [data="test3"], +.attributes .attributes .attribute-test { + extend: attributes2; +} +.header .header-nav, +.footer .footer-nav { + background: red; +} +.header .header-nav:before, +.footer .footer-nav:before { + background: blue; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extend.css b/node_modules/less-middleware/node_modules/less/test/css/extend.css new file mode 100644 index 000000000..2895641a7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extend.css @@ -0,0 +1,76 @@ +.error, +.badError { + border: 1px #f00; + background: #fdd; +} +.error.intrusion, +.badError.intrusion { + font-size: 1.3em; + font-weight: bold; +} +.intrusion .error, +.intrusion .badError { + display: none; +} +.badError { + border-width: 3px; +} +.foo .bar, +.foo .baz, +.ext1 .ext2 .bar, +.ext1 .ext2 .baz, +.ext3 .bar, +.ext3 .baz, +.foo .ext3, +.ext4 .bar, +.ext4 .baz, +.foo .ext4 { + display: none; +} +div.ext5, +.ext6 > .ext5, +div.ext7, +.ext6 > .ext7 { + width: 100px; +} +.ext8.ext9, +.fuu { + result: add-foo; +} +.ext8 .ext9, +.ext8 + .ext9, +.ext8 > .ext9, +.buu, +.zap, +.zoo { + result: bar-matched; +} +.ext8.nomatch { + result: none; +} +.ext8 .ext9, +.buu { + result: match-nested-bar; +} +.ext8.ext9, +.fuu { + result: match-nested-foo; +} +.aa, +.cc { + color: black; +} +.aa .dd, +.aa .ee { + background: red; +} +.bb, +.cc, +.ee, +.ff { + background: red; +} +.bb .bb, +.ff .ff { + color: black; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/extract-and-length.css b/node_modules/less-middleware/node_modules/less/test/css/extract-and-length.css new file mode 100644 index 000000000..f550e201b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/extract-and-length.css @@ -0,0 +1,133 @@ +.multiunit { + length: 6; + extract: abc "abc" 1 1px 1% #112233; +} +.incorrect-index { + v1: extract(a b c, 5); + v2: extract(a, b, c, -2); +} +.scalar { + var-value: variable; + var-length: 1; + ill-index: extract(variable, 2); + name-value: name; + string-value: "string"; + number-value: 12345678; + color-value: #0000ff; + rgba-value: rgba(80, 160, 240, 0.67); + empty-value: ; + name-length: 1; + string-length: 1; + number-length: 1; + color-length: 1; + rgba-length: 1; + empty-length: 1; +} +.mixin-arguments-1 { + length: 4; + extract: c | b | a; +} +.mixin-arguments-2 { + length: 4; + extract: c | b | a; +} +.mixin-arguments-3 { + length: 4; + extract: c | b | a; +} +.mixin-arguments-4 { + length: 0; + extract: extract(, 2) | extract(, 1); +} +.mixin-arguments-2 { + length: 4; + extract: c | b | a; +} +.mixin-arguments-3 { + length: 4; + extract: c | b | a; +} +.mixin-arguments-4 { + length: 3; + extract: c | b; +} +.mixin-arguments-2 { + length: 4; + extract: 3 | 2 | 1; +} +.mixin-arguments-3 { + length: 4; + extract: 3 | 2 | 1; +} +.mixin-arguments-4 { + length: 3; + extract: 3 | 2; +} +.md-space-comma { + length-1: 3; + extract-1: 1 2 3; + length-2: 3; + extract-2: 2; +} +.md-space-comma-as-args-2 { + length: 3; + extract: "x" "y" "z" | 1 2 3 | a b c; +} +.md-space-comma-as-args-3 { + length: 3; + extract: "x" "y" "z" | 1 2 3 | a b c; +} +.md-space-comma-as-args-4 { + length: 2; + extract: "x" "y" "z" | 1 2 3; +} +.md-cat-space-comma { + length-1: 3; + extract-1: 1 2 3; + length-2: 3; + extract-2: 2; +} +.md-cat-space-comma-as-args-2 { + length: 3; + extract: "x" "y" "z" | 1 2 3 | a b c; +} +.md-cat-space-comma-as-args-3 { + length: 3; + extract: "x" "y" "z" | 1 2 3 | a b c; +} +.md-cat-space-comma-as-args-4 { + length: 2; + extract: "x" "y" "z" | 1 2 3; +} +.md-cat-comma-space { + length-1: 3; + extract-1: 1, 2, 3; + length-2: 3; + extract-2: 2; +} +.md-cat-comma-space-as-args-1 { + length: 3; + extract: "x", "y", "z" | 1, 2, 3 | a, b, c; +} +.md-cat-comma-space-as-args-2 { + length: 3; + extract: "x", "y", "z" | 1, 2, 3 | a, b, c; +} +.md-cat-comma-space-as-args-3 { + length: 3; + extract: "x", "y", "z" | 1, 2, 3 | a, b, c; +} +.md-cat-comma-space-as-args-4 { + length: 0; + extract: extract(, 2) | extract(, 1); +} +.md-3D { + length-1: 2; + extract-1: a b c d, 1 2 3 4; + length-2: 2; + extract-2: 5 6 7 8; + length-3: 4; + extract-3: 7; + length-4: 1; + extract-4: 8; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/functions.css b/node_modules/less-middleware/node_modules/less/test/css/functions.css new file mode 100644 index 000000000..e39f7ecf1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/functions.css @@ -0,0 +1,158 @@ +#functions { + color: #660000; + width: 16; + height: undefined("self"); + border-width: 5; + variable: 11; + background: linear-gradient(#000000, #ffffff); +} +#built-in { + escaped: -Some::weird(#thing, y); + lighten: #ffcccc; + darken: #330000; + saturate: #203c31; + desaturate: #29332f; + greyscale: #2e2e2e; + hsl-clamp: #ffffff; + spin-p: #bf6a40; + spin-n: #bf4055; + luma-white: 100%; + luma-black: 0%; + luma-black-alpha: 0%; + luma-red: 21.26%; + luma-green: 71.52%; + luma-blue: 7.22%; + luma-yellow: 92.78%; + luma-cyan: 78.74%; + luma-differs-from-luminance: 23.89833349%; + luminance-white: 100%; + luminance-black: 0%; + luminance-black-alpha: 0%; + luminance-red: 21.26%; + luminance-differs-from-luma: 36.40541176%; + contrast-filter: contrast(30%); + saturate-filter: saturate(5%); + contrast-white: #000000; + contrast-black: #ffffff; + contrast-red: #ffffff; + contrast-green: #000000; + contrast-blue: #ffffff; + contrast-yellow: #000000; + contrast-cyan: #000000; + contrast-light: #111111; + contrast-dark: #eeeeee; + contrast-wrongorder: #111111; + contrast-light-thresh: #111111; + contrast-dark-thresh: #eeeeee; + contrast-high-thresh: #eeeeee; + contrast-low-thresh: #111111; + contrast-light-thresh-per: #111111; + contrast-dark-thresh-per: #eeeeee; + contrast-high-thresh-per: #eeeeee; + contrast-low-thresh-per: #111111; + replace: "Hello, World!"; + replace-captured: "This is a new string."; + replace-with-flags: "2 + 2 = 4"; + replace-single-quoted: 'foo-2'; + replace-escaped-string: bar-2; + replace-keyword: baz-2; + format: "rgb(32, 128, 64)"; + format-string: "hello world"; + format-multiple: "hello earth 2"; + format-url-encode: "red is %23ff0000"; + format-single-quoted: 'hello single world'; + format-escaped-string: hello escaped world; + eformat: rgb(32, 128, 64); + unitless: 12; + unit: 14em; + unitpercentage: 100%; + get-unit: px; + get-unit-empty: ; + hue: 98; + saturation: 12%; + lightness: 95%; + hsvhue: 98; + hsvsaturation: 12%; + hsvvalue: 95%; + red: 255; + green: 255; + blue: 255; + rounded: 11; + rounded-two: 10.67; + roundedpx: 3px; + roundedpx-three: 3.333px; + rounded-percentage: 10%; + ceil: 11px; + floor: 12px; + sqrt: 5px; + pi: 3.14159265; + mod: 2m; + abs: 4%; + tan: 0.90040404; + sin: 0.17364818; + cos: 0.84385396; + atan: 0.1rad; + atan: 34deg; + atan: 45deg; + pow: 64px; + pow: 64; + pow: 27; + min: 0; + min: 5; + min: 1pt; + min: 3mm; + max: 3; + max: 5em; + percentage: 20%; + color: #ff0011; + tint: #898989; + tint-full: #ffffff; + tint-percent: #898989; + tint-negative: #656565; + shade: #686868; + shade-full: #000000; + shade-percent: #686868; + shade-negative: #868686; + fade-out: rgba(255, 0, 0, 0.95); + fade-in: rgba(255, 0, 0, 0.95); + hsv: #4d2926; + hsva: rgba(77, 40, 38, 0.2); + mix: #ff3300; + mix-0: #ffff00; + mix-100: #ff0000; + mix-weightless: #ff8000; + mixt: rgba(255, 0, 0, 0.5); +} +#built-in .is-a { + color: true; + color1: true; + color2: true; + color3: true; + keyword: true; + number: true; + string: true; + pixel: true; + percent: true; + em: true; + cat: true; +} +#alpha { + alpha: rgba(153, 94, 51, 0.6); + alpha2: 0.5; + alpha3: 0; +} +#blendmodes { + multiply: #ed0000; + screen: #f600f6; + overlay: #ed0000; + softlight: #fa0000; + hardlight: #0000ed; + difference: #f600f6; + exclusion: #f600f6; + average: #7b007b; + negation: #d73131; +} +#extract-and-length { + extract: 3 2 1 C B A; + length: 6; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/globalVars/extended.css b/node_modules/less-middleware/node_modules/less/test/css/globalVars/extended.css new file mode 100644 index 000000000..1149ac878 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/globalVars/extended.css @@ -0,0 +1,12 @@ +/** + * Test + */ +#header { + color: #333333; + border-left: 1px; + border-right: 2px; +} +#footer { + color: #114411; + border-color: #f20d0d; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/globalVars/simple.css b/node_modules/less-middleware/node_modules/less/test/css/globalVars/simple.css new file mode 100644 index 000000000..55779d8b2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/globalVars/simple.css @@ -0,0 +1,6 @@ +/** + * Test + */ +.class { + color: #ff0000; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/ie-filters.css b/node_modules/less-middleware/node_modules/less/test/css/ie-filters.css new file mode 100644 index 000000000..007aa536b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/ie-filters.css @@ -0,0 +1,9 @@ +.nav { + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20); + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#333333", endColorstr="#000000", GradientType=0); +} +.evalTest1 { + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=30); + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=5); +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/import-inline.css b/node_modules/less-middleware/node_modules/less/test/css/import-inline.css new file mode 100644 index 000000000..5e729d198 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/import-inline.css @@ -0,0 +1,8 @@ +#import { + color: #ff0000; +} +@media (min-width: 600px) { + #css { color: yellow; } + +} +this isn't very valid CSS. diff --git a/node_modules/less-middleware/node_modules/less/test/css/import-interpolation.css b/node_modules/less-middleware/node_modules/less/test/css/import-interpolation.css new file mode 100644 index 000000000..16b7a1502 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/import-interpolation.css @@ -0,0 +1,6 @@ +body { + width: 100%; +} +.a { + var: test; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/import-once.css b/node_modules/less-middleware/node_modules/less/test/css/import-once.css new file mode 100644 index 000000000..2f86b3b34 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/import-once.css @@ -0,0 +1,15 @@ +#import { + color: #ff0000; +} +body { + width: 100%; +} +.test-f { + height: 10px; +} +body { + width: 100%; +} +.test-f { + height: 10px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/import-reference.css b/node_modules/less-middleware/node_modules/less/test/css/import-reference.css new file mode 100644 index 000000000..f25f4b1dc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/import-reference.css @@ -0,0 +1,68 @@ +input[type="text"].class#id[attr=32]:not(1) { + color: white; +} +div#id.class[a=1][b=2].class:not(1) { + color: white; +} +@media print { + .class { + color: blue; + } + .class .sub { + width: 42; + } +} +.visible { + color: red; +} +.visible .c { + color: green; +} +.visible { + color: green; +} +.visible:hover { + color: green; +} +.only-with-visible + .visible, +.visible + .only-with-visible, +.visible + .visible { + color: green; +} +.only-with-visible + .visible .sub, +.visible + .only-with-visible .sub, +.visible + .visible .sub { + color: green; +} +.b { + color: red; + color: green; +} +.b .c { + color: green; +} +.b:hover { + color: green; +} +.b + .b { + color: green; +} +.b + .b .sub { + color: green; +} +.y { + pulled-in: yes; +} +/* comment pulled in */ +.visible { + extend: test; +} +.test-mediaq-import { + color: green; + test: 340px; +} +@media (max-size: 450px) { + .test-mediaq-import { + color: red; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/import.css b/node_modules/less-middleware/node_modules/less/test/css/import.css new file mode 100644 index 000000000..eea93c2b7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/import.css @@ -0,0 +1,42 @@ +@charset "UTF-8"; +@import url(http://fonts.googleapis.com/css?family=Open+Sans); +@import url(/absolute/something.css) screen and (color) and (max-width: 600px); +@import url("//ha.com/file.css") (min-width: 100px); +#import-test { + height: 10px; + color: #ff0000; + width: 10px; + height: 30%; +} +@media screen and (max-width: 600px) { + body { + width: 100%; + } +} +#import { + color: #ff0000; +} +.mixin { + height: 10px; + color: #ff0000; +} +@media screen and (max-width: 601px) { + #css { + color: yellow; + } +} +@media screen and (max-width: 602px) { + body { + width: 100%; + } +} +@media screen and (max-width: 603px) { + #css { + color: yellow; + } +} +@media print { + body { + width: 100%; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/javascript.css b/node_modules/less-middleware/node_modules/less/test/css/javascript.css new file mode 100644 index 000000000..9cc1c3e91 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/javascript.css @@ -0,0 +1,28 @@ +.eval { + js: 42; + js: 2; + js: "hello world"; + js: 1, 2, 3; + title: "string"; + ternary: true; + multiline: 2; +} +.scope { + var: 42; + escaped: 7px; +} +.vars { + width: 8; +} +.escape-interpol { + width: hello world; +} +.arrays { + ary: "1, 2, 3"; + ary1: "1, 2, 3"; +} +.test-tran { + 1: opacity 0.3s ease-in 0.3s, max-height 0.6s linear, margin-bottom 0.4s linear; + 2: [opacity 0.3s ease-in 0.3s, max-height 0.6s linear, margin-bottom 0.4s linear]; + 3: opacity 0.3s ease-in 0.3s, max-height 0.6s linear, margin-bottom 0.4s linear; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/lazy-eval.css b/node_modules/less-middleware/node_modules/less/test/css/lazy-eval.css new file mode 100644 index 000000000..1adfb8f38 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/lazy-eval.css @@ -0,0 +1,3 @@ +.lazy-eval { + width: 100%; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/legacy/legacy.css b/node_modules/less-middleware/node_modules/less/test/css/legacy/legacy.css new file mode 100644 index 000000000..2f9bb80b5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/legacy/legacy.css @@ -0,0 +1,7 @@ +@media (-o-min-device-pixel-ratio: 2/1) { + .test-math-and-units { + font: ignores 0/0 rules; + test-division: 7em; + simple: 2px; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/media.css b/node_modules/less-middleware/node_modules/less/test/css/media.css new file mode 100644 index 000000000..607f0e44e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/media.css @@ -0,0 +1,219 @@ +@media print { + .class { + color: blue; + } + .class .sub { + width: 42; + } + .top, + header > h1 { + color: #444444; + } +} +@media screen { + body { + max-width: 480; + } +} +@media all and (device-aspect-ratio: 16 / 9) { + body { + max-width: 800px; + } +} +@media all and (orientation: portrait) { + aside { + float: none; + } +} +@media handheld and (min-width: 42), screen and (min-width: 20em) { + body { + max-width: 480px; + } +} +@media print { + body { + padding: 20px; + } + body header { + background-color: red; + } +} +@media print and (orientation: landscape) { + body { + margin-left: 20px; + } +} +@media screen { + .sidebar { + width: 300px; + } +} +@media screen and (orientation: landscape) { + .sidebar { + width: 500px; + } +} +@media a and b { + .first .second .third { + width: 300px; + } + .first .second .fourth { + width: 3; + } +} +@media a and b and c { + .first .second .third { + width: 500px; + } +} +@media a, b and c { + body { + width: 95%; + } +} +@media a and x, b and c and x, a and y, b and c and y { + body { + width: 100%; + } +} +.a { + background: black; +} +@media handheld { + .a { + background: white; + } +} +@media handheld and (max-width: 100px) { + .a { + background: red; + } +} +.b { + background: black; +} +@media handheld { + .b { + background: white; + } +} +@media handheld and (max-width: 200px) { + .b { + background: red; + } +} +@media only screen and (max-width: 200px) { + body { + width: 480px; + } +} +@media print { + @page :left { + margin: 0.5cm; + } + @page :right { + margin: 0.5cm; + } + @page Test:first { + margin: 1cm; + } + @page :first { + size: 8.5in 11in; + + @top-left { + margin: 1cm; + } + @top-left-corner { + margin: 1cm; + } + @top-center { + margin: 1cm; + } + @top-right { + margin: 1cm; + } + @top-right-corner { + margin: 1cm; + } + @bottom-left { + margin: 1cm; + } + @bottom-left-corner { + margin: 1cm; + } + @bottom-center { + margin: 1cm; + } + @bottom-right { + margin: 1cm; + } + @bottom-right-corner { + margin: 1cm; + } + @left-top { + margin: 1cm; + } + @left-middle { + margin: 1cm; + } + @left-bottom { + margin: 1cm; + } + @right-top { + margin: 1cm; + } + @right-middle { + content: "Page " counter(page); + } + @right-bottom { + margin: 1cm; + } + } +} +@media (-webkit-min-device-pixel-ratio: 2), (min--moz-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (min-resolution: 2dppx), (min-resolution: 128dpcm) { + .b { + background: red; + } +} +body { + background: red; +} +@media (max-width: 500px) { + body { + background: green; + } +} +@media (max-width: 1000px) { + body { + background: red; + background: blue; + } +} +@media (max-width: 1000px) and (max-width: 500px) { + body { + background: green; + } +} +@media (max-width: 1200px) { + /* a comment */ +} +@media (max-width: 1200px) and (max-width: 900px) { + body { + font-size: 11px; + } +} +@media (min-width: 480px) { + .nav-justified > li { + display: table-cell; + } +} +@media (min-width: 768px) and (min-width: 480px) { + .menu > li { + display: table-cell; + } +} +@media all and tv { + .all-and-tv-variables { + var: all-and-tv; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/merge.css b/node_modules/less-middleware/node_modules/less/test/css/merge.css new file mode 100644 index 000000000..fe29dc83b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/merge.css @@ -0,0 +1,34 @@ +.test1 { + transform: rotate(90deg), skew(30deg), scale(2, 4); +} +.test2 { + transform: rotate(90deg), skew(30deg); + transform: scaleX(45deg); +} +.test3 { + transform: scaleX(45deg); + background: url(data://img1.png); +} +.test4 { + transform: rotate(90deg), skew(30deg); + transform: scale(2, 4) !important; +} +.test5 { + transform: rotate(90deg), skew(30deg); + transform: scale(2, 4) !important; +} +.test6 { + transform: scale(2, 4); +} +.test-interleaved { + transform: t1, t2, t3; + background: b1, b2, b3; +} +.test-spaced { + transform: t1 t2 t3; + background: b1 b2, b3; +} +.test-interleaved-with-spaced { + transform: t1s, t2 t3s, t4 t5s t6s; + background: b1 b2s, b3, b4; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-args.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-args.css new file mode 100644 index 000000000..2b6c5c962 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-args.css @@ -0,0 +1,113 @@ +#hidden { + color: transparent; +} +#hidden1 { + color: transparent; +} +.two-args { + color: blue; + width: 10px; + height: 99%; + border: 2px dotted #000000; +} +.one-arg { + width: 15px; + height: 49%; +} +.no-parens { + width: 5px; + height: 49%; +} +.no-args { + width: 5px; + height: 49%; +} +.var-args { + width: 45; + height: 17%; +} +.multi-mix { + width: 10px; + height: 29%; + margin: 4; + padding: 5; +} +body { + padding: 30px; + color: #ff0000; +} +.scope-mix { + width: 8; +} +.content { + width: 600px; +} +.content .column { + margin: 600px; +} +#same-var-name { + radius: 5px; +} +#var-inside { + width: 10px; +} +.arguments { + border: 1px solid #000000; + width: 1px; +} +.arguments2 { + border: 0px; + width: 0px; +} +.arguments3 { + border: 0px; + width: 0px; +} +.arguments4 { + border: 0 1 2 3 4; + rest: 1 2 3 4; + width: 0; +} +.edge-case { + border: "{"; + width: "{"; +} +.slash-vs-math { + border-radius: 2px/5px; + border-radius: 5px/10px; + border-radius: 6px; +} +.comma-vs-semi-colon { + one: a; + two: b, c; + one: d, e; + two: f; + one: g; + one: h; + one: i; + one: j; + one: k; + two: l; + one: m, n; + one: o, p; + two: q; + one: r, s; + two: t; +} +#named-conflict { + four: a, 11, 12, 13; + four: a, 21, 22, 23; +} +.test-mixin-default-arg { + defaults: 1px 1px 1px; + defaults: 2px 2px 2px; +} +.selector { + margin: 2, 2, 2, 2; +} +.selector2 { + margin: 2, 2, 2, 2; +} +.selector3 { + margin: 4; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-closure.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-closure.css new file mode 100644 index 000000000..b1021b6fb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-closure.css @@ -0,0 +1,9 @@ +.class { + width: 99px; +} +.overwrite { + width: 99px; +} +.nested .class { + width: 5px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-guards-default-func.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-guards-default-func.css new file mode 100644 index 000000000..e47f05cf6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-guards-default-func.css @@ -0,0 +1,129 @@ +guard-default-basic-1-1 { + case: 1; +} +guard-default-basic-1-2 { + default: 2; +} +guard-default-basic-2-0 { + default: 0; +} +guard-default-basic-2-2 { + case: 2; +} +guard-default-basic-3-0 { + default: 0; +} +guard-default-basic-3-2 { + case: 2; +} +guard-default-basic-3-3 { + case: 3; +} +guard-default-definition-order-0 { + default: 0; +} +guard-default-definition-order-2 { + case: 2; +} +guard-default-definition-order-2 { + case: 3; +} +guard-default-out-of-guard-0 { + case-0: default(); + case-1: 1; + default: 2; + case-2: default(); +} +guard-default-out-of-guard-1 { + default: default(); +} +guard-default-out-of-guard-2 { + default: default(); +} +guard-default-expr-not-1 { + case: 1; + default: 1; +} +guard-default-expr-eq-true { + case: true; +} +guard-default-expr-eq-false { + case: false; + default: false; +} +guard-default-expr-or-1 { + case: 1; +} +guard-default-expr-or-2 { + case: 2; + default: 2; +} +guard-default-expr-or-3 { + default: 3; +} +guard-default-expr-and-1 { + case: 1; +} +guard-default-expr-and-2 { + case: 2; +} +guard-default-expr-and-3 { + default: 3; +} +guard-default-expr-always-1 { + case: 1; + default: 1; +} +guard-default-expr-always-2 { + default: 2; +} +guard-default-expr-never-1 { + case: 1; +} +guard-default-multi-1-0 { + case: 0; +} +guard-default-multi-1-1 { + default-1: 1; +} +guard-default-multi-2-1 { + default-1: no; +} +guard-default-multi-2-2 { + default-2: no; +} +guard-default-multi-2-3 { + default-3: 3; +} +guard-default-multi-3-blue { + case-2: #00008b; +} +guard-default-multi-3-green { + default-color: #008000; +} +guard-default-multi-3-foo { + case-1: I am 'foo'; +} +guard-default-multi-3-baz { + default-string: I am 'baz'; +} +guard-default-multi-4 { + always: 1; + always: 2; + case: 2; +} +guard-default-not-ambiguos-2 { + case: 1; + not-default: 2; +} +guard-default-not-ambiguos-3 { + case: 1; + not-default-1: 2; + not-default-2: 2; +} +guard-default-scopes-3 { + 3: when default; +} +guard-default-scopes-1 { + 1: no condition; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-guards.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-guards.css new file mode 100644 index 000000000..59b6f932c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-guards.css @@ -0,0 +1,93 @@ +.light1 { + color: white; + margin: 1px; +} +.light2 { + color: black; + margin: 1px; +} +.max1 { + width: 6; +} +.max2 { + width: 8; +} +.glob1 { + margin: auto auto; +} +.ops1 { + height: gt-or-eq; + height: lt-or-eq; + height: lt-or-eq-alias; +} +.ops2 { + height: gt-or-eq; + height: not-eq; +} +.ops3 { + height: lt-or-eq; + height: lt-or-eq-alias; + height: not-eq; +} +.default1 { + content: default; +} +.test1 { + content: "true."; +} +.test2 { + content: "false."; +} +.test3 { + content: "false."; +} +.test4 { + content: "false."; +} +.test5 { + content: "false."; +} +.bool1 { + content: true and true; + content: true; + content: false, true; + content: false and true and true, true; + content: false, true and true; + content: false, false, true; + content: false, true and true and true, false; + content: not false; + content: not false and false, not false; +} +.equality-units { + test: pass; +} +.colorguardtest { + content: is #ff0000; + content: is not #0000ff its #ff0000; + content: is not #0000ff its #800080; +} +.stringguardtest { + content: "theme1" is "theme1"; + content: "theme1" is not "theme2"; + content: "theme1" is 'theme1'; + content: "theme1" is not 'theme2'; + content: 'theme1' is "theme1"; + content: 'theme1' is not "theme2"; + content: 'theme1' is 'theme1'; + content: 'theme1' is not 'theme2'; + content: theme1 is not "theme2"; + content: theme1 is not 'theme2'; + content: theme1 is theme1; +} +#tryNumberPx { + catch: all; + declare: 4; + declare: 4px; +} +.call-lock-mixin .call-inner-lock-mixin { + a: 1; + x: 1; +} +.mixin-generated-class { + a: 1; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-important.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-important.css new file mode 100644 index 000000000..b100af7ff --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-important.css @@ -0,0 +1,45 @@ +.class { + border: 1; + boxer: 1; + border-width: 1; + border: 2 !important; + boxer: 2 !important; + border-width: 2 !important; + border: 3; + boxer: 3; + border-width: 3; + border: 4 !important; + boxer: 4 !important; + border-width: 4 !important; + border: 5; + boxer: 5; + border-width: 5; + border: 0 !important; + boxer: 0 !important; + border-width: 0 !important; + border: 9 !important; + border: 9; + boxer: 9; + border-width: 9; +} +.class .inner { + test: 1; +} +.class .inner { + test: 2 !important; +} +.class .inner { + test: 3; +} +.class .inner { + test: 4 !important; +} +.class .inner { + test: 5; +} +.class .inner { + test: 0 !important; +} +.class .inner { + test: 9; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-interpolated.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-interpolated.css new file mode 100644 index 000000000..637b5b682 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-interpolated.css @@ -0,0 +1,39 @@ +.foo { + a: 1; +} +.foo { + a: 2; +} +#foo { + a: 3; +} +#foo { + a: 4; +} +mi-test-a { + a: 1; + a: 2; + a: 3; + a: 4; +} +.b .bb.foo-xxx .yyy-foo#foo .foo.bbb { + b: 1; +} +mi-test-b { + b: 1; +} +#foo-foo > .bar .baz { + c: c; +} +mi-test-c-1 > .bar .baz { + c: c; +} +mi-test-c-2 .baz { + c: c; +} +mi-test-c-3 { + c: c; +} +mi-test-d { + gender: "Male"; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-named-args.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-named-args.css new file mode 100644 index 000000000..e460aa104 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-named-args.css @@ -0,0 +1,27 @@ +.named-arg { + color: blue; + width: 5px; + height: 99%; + args: 1px 100%; + text-align: center; +} +.class { + width: 5px; + height: 19%; + args: 1px 20%; +} +.all-args-wrong-args { + width: 10px; + height: 9%; + args: 2px 10%; +} +.named-args2 { + width: 15px; + height: 49%; + color: #646464; +} +.named-args3 { + width: 5px; + height: 29%; + color: #123456; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-nested.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-nested.css new file mode 100644 index 000000000..6378c4756 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-nested.css @@ -0,0 +1,14 @@ +.class .inner { + height: 300; +} +.class .inner .innest { + width: 30; + border-width: 60; +} +.class2 .inner { + height: 600; +} +.class2 .inner .innest { + width: 60; + border-width: 120; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins-pattern.css b/node_modules/less-middleware/node_modules/less/test/css/mixins-pattern.css new file mode 100644 index 000000000..1515f32a9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins-pattern.css @@ -0,0 +1,51 @@ +.zero { + variadic: true; + named-variadic: true; + zero: 0; + one: 1; + two: 2; + three: 3; +} +.one { + variadic: true; + named-variadic: true; + one: 1; + one-req: 1; + two: 2; + three: 3; +} +.two { + variadic: true; + named-variadic: true; + two: 2; + three: 3; +} +.three { + variadic: true; + named-variadic: true; + three-req: 3; + three: 3; +} +.left { + left: 1; +} +.right { + right: 1; +} +.border-right { + color: black; + border-right: 4px; +} +.border-left { + color: black; + border-left: 4px; +} +.only-right { + right: 33; +} +.only-left { + left: 33; +} +.left-right { + both: 330; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/mixins.css b/node_modules/less-middleware/node_modules/less/test/css/mixins.css new file mode 100644 index 000000000..4d9824f5c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/mixins.css @@ -0,0 +1,144 @@ +.mixin { + border: 1px solid black; +} +.mixout { + border-color: orange; +} +.borders { + border-style: dashed; +} +.mixin > * { + border: do not match me; +} +#namespace .borders { + border-style: dotted; +} +#namespace .biohazard { + content: "death"; +} +#namespace .biohazard .man { + color: transparent; +} +#theme > .mixin { + background-color: grey; +} +#container { + color: black; + border: 1px solid black; + border-color: orange; + background-color: grey; +} +#header .milk { + color: white; + border: 1px solid black; + background-color: grey; +} +#header #cookie { + border-style: dashed; +} +#header #cookie .chips { + border-style: dotted; +} +#header #cookie .chips .calories { + color: black; + border: 1px solid black; + border-color: orange; + background-color: grey; +} +.secure-zone { + color: transparent; +} +.direct { + border-style: dotted; +} +.bo, +.bar { + width: 100%; +} +.bo { + border: 1px; +} +.ar.bo.ca { + color: black; +} +.jo.ki { + background: none; +} +.amp.support { + color: orange; +} +.amp.support .higher { + top: 0px; +} +.amp.support.deeper { + height: auto; +} +.extended { + width: 100%; + border: 1px; + background: none; + color: orange; + top: 0px; + height: auto; +} +.extended .higher { + top: 0px; +} +.extended.deeper { + height: auto; +} +.do .re .mi .fa .sol .la .si { + color: cyan; +} +.mutli-selector-parents { + color: cyan; +} +.foo .bar { + width: 100%; +} +.underParents { + color: red; +} +.parent .underParents { + color: red; +} +* + h1 { + margin-top: 25px; +} +legend + h1 { + margin-top: 0; +} +h1 + * { + margin-top: 10px; +} +* + h2 { + margin-top: 20px; +} +legend + h2 { + margin-top: 0; +} +h2 + * { + margin-top: 8px; +} +* + h3 { + margin-top: 15px; +} +legend + h3 { + margin-top: 0; +} +h3 + * { + margin-top: 5px; +} +.error { + background-image: "/a.png"; + background-position: center center; +} +.test-rec .recursion { + color: black; +} +.button { + padding-left: 44px; +} +.button.large { + padding-left: 40em; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/modifyVars/extended.css b/node_modules/less-middleware/node_modules/less/test/css/modifyVars/extended.css new file mode 100644 index 000000000..32edb38f1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/modifyVars/extended.css @@ -0,0 +1,9 @@ +#header { + color: #333333; + border-left: 1px; + border-right: 2px; +} +#footer { + color: #114411; + border-color: #842210; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/no-output.css b/node_modules/less-middleware/node_modules/less/test/css/no-output.css new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/less-middleware/node_modules/less/test/css/operations.css b/node_modules/less-middleware/node_modules/less/test/css/operations.css new file mode 100644 index 000000000..fb9e0aff7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/operations.css @@ -0,0 +1,49 @@ +#operations { + color: #111111; + height: 9px; + width: 3em; + substraction: 0; + division: 1; +} +#operations .spacing { + height: 9px; + width: 3em; +} +.with-variables { + height: 16em; + width: 24em; + size: 1cm; +} +.with-functions { + color: #646464; + color: #ff8080; + color: #c94a4a; +} +.negative { + height: 0px; + width: 4px; +} +.shorthands { + padding: -1px 2px 0 -4px; +} +.rem-dimensions { + font-size: 5.5rem; +} +.colors { + color: #123; + border-color: #334455; + background-color: #000000; +} +.colors .other { + color: #222222; + border-color: #222222; +} +.negations { + variable: -4px; + variable1: 0px; + variable2: 0px; + variable3: 8px; + variable4: 0px; + paren: -4px; + paren2: 16px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/parens.css b/node_modules/less-middleware/node_modules/less/test/css/parens.css new file mode 100644 index 000000000..dc09fdf52 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/parens.css @@ -0,0 +1,36 @@ +.parens { + border: 2px solid #000000; + margin: 1px 3px 16 3; + width: 36; + padding: 2px 36px; +} +.more-parens { + padding: 8 4 4 4px; + width-all: 96; + width-first: 16 * 6; + width-keep: (4 * 4) * 6; + height-keep: (7 * 7) + (8 * 8); + height-all: 113; + height-parts: 49 + 64; + margin-keep: (4 * (5 + 5) / 2) - (4 * 2); + margin-parts: 20 - 8; + margin-all: 12; + border-radius-keep: 4px * (1 + 1) / 4 + 3px; + border-radius-parts: 8px / 7px; + border-radius-all: 5px; +} +.negative { + neg-var: -1; + neg-var-paren: -(1); +} +.nested-parens { + width: 2 * (4 * (2 + (1 + 6))) - 1; + height: ((2 + 3) * (2 + 3) / (9 - 4)) + 1; +} +.mixed-units { + margin: 2px 4em 1 5pc; + padding: 6px 1em 2px 2; +} +.test-false-negatives { + a: (; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/property-name-interp.css b/node_modules/less-middleware/node_modules/less/test/css/property-name-interp.css new file mode 100644 index 000000000..315815e3f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/property-name-interp.css @@ -0,0 +1,21 @@ +pi-test { + border: 0; + @not-variable: @not-variable; + ufo-width: 50%; + *-z-border: 1px dashed blue; + -www-border-top: 2px; + radius-is-not-a-border: true; + border-top-left-radius: 2em; + border-top-red-radius-: 3pt; + global-local-mixer-property: strong; +} +pi-test-merge { + pre-property-ish: high, middle, low, base; + pre-property-ish+: nice try dude; +} +pi-indirect-vars { + auto: auto; +} +pi-complex-values { + 3px rgba(255, 255, 0, 0.5), 3.141592653589793 /* foo */3px rgba(255, 255, 0, 0.5), 3.141592653589793 /* foo */: none; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/rulesets.css b/node_modules/less-middleware/node_modules/less/test/css/rulesets.css new file mode 100644 index 000000000..408c76aad --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/rulesets.css @@ -0,0 +1,33 @@ +#first > .one { + font-size: 2em; +} +#first > .one > #second .two > #deux { + width: 50%; +} +#first > .one > #second .two > #deux #third { + height: 100%; +} +#first > .one > #second .two > #deux #third:focus { + color: black; +} +#first > .one > #second .two > #deux #third:focus #fifth > #sixth .seventh #eighth + #ninth { + color: purple; +} +#first > .one > #second .two > #deux #fourth, +#first > .one > #second .two > #deux #five, +#first > .one > #second .two > #deux #six { + color: #110000; +} +#first > .one > #second .two > #deux #fourth .seven, +#first > .one > #second .two > #deux #five .seven, +#first > .one > #second .two > #deux #six .seven, +#first > .one > #second .two > #deux #fourth .eight > #nine, +#first > .one > #second .two > #deux #five .eight > #nine, +#first > .one > #second .two > #deux #six .eight > #nine { + border: 1px solid black; +} +#first > .one > #second .two > #deux #fourth #ten, +#first > .one > #second .two > #deux #five #ten, +#first > .one > #second .two > #deux #six #ten { + color: red; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/scope.css b/node_modules/less-middleware/node_modules/less/test/css/scope.css new file mode 100644 index 000000000..0e4c17d53 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/scope.css @@ -0,0 +1,38 @@ +.tiny-scope { + color: #998899; +} +.scope1 { + color: #0000ff; + border-color: #000000; +} +.scope1 .scope2 { + color: #0000ff; +} +.scope1 .scope2 .scope3 { + color: #ff0000; + border-color: #000000; + background-color: #ffffff; +} +.scope { + scoped-val: #008000; +} +.heightIsSet { + height: 1024px; +} +.useHeightInMixinCall { + mixin-height: 1024px; +} +.imported { + exists: true; +} +.testImported { + exists: true; +} +#allAreUsedHere { + default: 'top level'; + scope: 'top level'; + sub-scope-only: 'inside'; +} +#parentSelectorScope { + prop: #ffffff; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/selectors.css b/node_modules/less-middleware/node_modules/less/test/css/selectors.css new file mode 100644 index 000000000..ec855becb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/selectors.css @@ -0,0 +1,153 @@ +h1 a:hover, +h2 a:hover, +h3 a:hover, +h1 p:hover, +h2 p:hover, +h3 p:hover { + color: red; +} +#all { + color: blue; +} +#the { + color: blue; +} +#same { + color: blue; +} +ul, +li, +div, +q, +blockquote, +textarea { + margin: 0; +} +td { + margin: 0; + padding: 0; +} +td, +input { + line-height: 1em; +} +a { + color: red; +} +a:hover { + color: blue; +} +div a { + color: green; +} +p a span { + color: yellow; +} +.foo .bar .qux, +.foo .baz .qux { + display: block; +} +.qux .foo .bar, +.qux .foo .baz { + display: inline; +} +.qux.foo .bar, +.qux.foo .baz { + display: inline-block; +} +.qux .foo .bar .biz, +.qux .foo .baz .biz { + display: none; +} +.a.b.c { + color: red; +} +.c .b.a { + color: red; +} +.foo .p.bar { + color: red; +} +.foo.p.bar { + color: red; +} +.foo + .foo { + background: amber; +} +.foo + .foo { + background: amber; +} +.foo + .foo, +.foo + .bar, +.bar + .foo, +.bar + .bar { + background: amber; +} +.foo a > .foo a, +.foo a > .bar a, +.foo a > .foo b, +.foo a > .bar b, +.bar a > .foo a, +.bar a > .bar a, +.bar a > .foo b, +.bar a > .bar b, +.foo b > .foo a, +.foo b > .bar a, +.foo b > .foo b, +.foo b > .bar b, +.bar b > .foo a, +.bar b > .bar a, +.bar b > .foo b, +.bar b > .bar b { + background: amber; +} +.other ::fnord { + color: #ff0000; +} +.other::fnord { + color: #ff0000; +} +.other ::bnord { + color: #ff0000; +} +.other::bnord { + color: #ff0000; +} +.blood { + color: red; +} +.bloodred { + color: green; +} +#blood.blood.red.black { + color: black; +} +:nth-child(3) { + selector: interpolated; +} +.test:nth-child(odd):not(:nth-child(3)) { + color: #ff0000; +} +[prop], +[prop=10%], +[prop="value3"], +[prop*="val3"], +[|prop~="val3"], +[*|prop$="val3"], +[ns|prop^="val3"], +[3^="val3"], +[3=3], +[3] { + attributes: yes; +} +/* +Large comment means chunk will be emitted after } which means chunk will begin with whitespace... +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +*/ +.blood { + color: red; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/static-urls/urls.css b/node_modules/less-middleware/node_modules/less/test/css/static-urls/urls.css new file mode 100644 index 000000000..ed174e87b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/static-urls/urls.css @@ -0,0 +1,45 @@ +@import "css/background.css"; +@import "folder (1)/import-test-d.css"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(folder\ \(1\)/fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(folder\ \(1\)/images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(folder\ \(1\)/bg.jpg) no-repeat, url(folder\ \(1\)/bg.png) repeat-x top left, url(folder\ \(1\)/bg); +} +.values { + url: url('folder (1)/Trebuchet'); +} +#logo { + width: 100px; + height: 100px; + background: url('assets/logo.png'); +} +@font-face { + font-family: xecret; + src: url('assets/xecret.ttf'); +} +#secret { + font-family: xecret, sans-serif; +} +#imported-relative-path { + background-image: url(../data/image.jpg); + border-image: url('../data/image.jpg'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/strings.css b/node_modules/less-middleware/node_modules/less/test/css/strings.css new file mode 100644 index 000000000..cd6d60202 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/strings.css @@ -0,0 +1,43 @@ +#strings { + background-image: url("http://son-of-a-banana.com"); + quotes: "~" "~"; + content: "#*%:&^,)!.(~*})"; + empty: ""; + brackets: "{" "}"; + escapes: "\"hello\" \\world"; + escapes2: "\"llo"; +} +#comments { + content: "/* hello */ // not-so-secret"; +} +#single-quote { + quotes: "'" "'"; + content: '""#!&""'; + empty: ''; + semi-colon: ';'; +} +#escaped { + filter: DX.Transform.MS.BS.filter(opacity=50); +} +#one-line { + image: url(http://tooks.com); +} +#crazy { + image: url(http://), "}", url("http://}"); +} +#interpolation { + url: "http://lesscss.org/dev/image.jpg"; + url2: "http://lesscss.org/image-256.jpg"; + url3: "http://lesscss.org#445566"; + url4: "http://lesscss.org/hello"; + url5: "http://lesscss.org/54.4px"; +} +.mix-mul-class { + color: #0000ff; + color: #ff0000; + color: #000000; + color: #ffa500; +} +.watermark { + family: Univers, Arial, Verdana, San-Serif; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/url-args/urls.css b/node_modules/less-middleware/node_modules/less/test/css/url-args/urls.css new file mode 100644 index 000000000..0b4b13f35 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/url-args/urls.css @@ -0,0 +1,56 @@ +@font-face { + src: url("/fonts/garamond-pro.ttf?424242"); + src: local(Futura-Medium), url(fonts.svg?424242#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html?424242") no-repeat 0 4px; + background: url("img.jpg?424242") center / 100px; + background: #ffffff url(image.png?424242) center / 1px 100px repeat-x scroll content-box padding-box; +} +#misc { + background-image: url(images/image.jpg?424242); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700&424242); + background-image: url("http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700&424242"); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(bg.jpg?424242) no-repeat, url(bg.png?424242) repeat-x top left, url(bg?424242); +} +.values { + url: url('Trebuchet?424242'); +} +@font-face { + font-family: xecret; + src: url('../assets/xecret.ttf?424242'); +} +#secret { + font-family: xecret, sans-serif; +} +#data-uri { + uri: url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg=="); +} +#data-uri-guess { + uri: url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg=="); +} +#data-uri-ascii { + uri-1: url("data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A"); + uri-2: url("data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A"); +} +#svg-functions { + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIvPjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIvPjwvbGluZWFyR3JhZGllbnQ+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkaWVudCkiIC8+PC9zdmc+'); + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIvPjxzdG9wIG9mZnNldD0iMyUiIHN0b3AtY29sb3I9IiNmZmE1MDAiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiLz48L2xpbmVhckdyYWRpZW50PjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZGllbnQpIiAvPjwvc3ZnPg=='); + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIxJSIgc3RvcC1jb2xvcj0iI2M0YzRjNCIvPjxzdG9wIG9mZnNldD0iMyUiIHN0b3AtY29sb3I9IiNmZmE1MDAiLz48c3RvcCBvZmZzZXQ9IjUlIiBzdG9wLWNvbG9yPSIjMDA4MDAwIi8+PHN0b3Agb2Zmc2V0PSI5NSUiIHN0b3AtY29sb3I9IiNmZmZmZmYiLz48L2xpbmVhckdyYWRpZW50PjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZGllbnQpIiAvPjwvc3ZnPg=='); +} +#data-uri-with-spaces { + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(' data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9=='); +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/urls.css b/node_modules/less-middleware/node_modules/less/test/css/urls.css new file mode 100644 index 000000000..160425114 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/urls.css @@ -0,0 +1,77 @@ +@import "css/background.css"; +@import "import/import-test-d.css"; +@import "file.css"; +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; + background: url("img.jpg") center / 100px; + background: #ffffff url(image.png) center / 1px 100px repeat-x scroll content-box padding-box; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); + background-image: url("http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700"); +} +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + url: url('Trebuchet'); +} +#logo { + width: 100px; + height: 100px; + background: url('import/assets/logo.png'); +} +@font-face { + font-family: xecret; + src: url('import/assets/xecret.ttf'); +} +#secret { + font-family: xecret, sans-serif; +} +#imported-relative-path { + background-image: url(../data/image.jpg); + border-image: url('../data/image.jpg'); +} +#relative-url-import { + background-image: url(../data/image.jpg); + border-image: url('../data/image.jpg'); +} +#data-uri { + uri: url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg=="); + uri-fragment: url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==#fragment"); +} +#data-uri-guess { + uri: url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg=="); +} +#data-uri-ascii { + uri-1: url("data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A"); + uri-2: url("data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A"); +} +#data-uri-toobig { + uri: url('../data/data-uri-fail.png'); +} +#svg-functions { + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIvPjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIvPjwvbGluZWFyR3JhZGllbnQ+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkaWVudCkiIC8+PC9zdmc+'); + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIvPjxzdG9wIG9mZnNldD0iMyUiIHN0b3AtY29sb3I9IiNmZmE1MDAiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiLz48L2xpbmVhckdyYWRpZW50PjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZGllbnQpIiAvPjwvc3ZnPg=='); + background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIxJSIgc3RvcC1jb2xvcj0iI2M0YzRjNCIvPjxzdG9wIG9mZnNldD0iMyUiIHN0b3AtY29sb3I9IiNmZmE1MDAiLz48c3RvcCBvZmZzZXQ9IjUlIiBzdG9wLWNvbG9yPSIjMDA4MDAwIi8+PHN0b3Agb2Zmc2V0PSI5NSUiIHN0b3AtY29sb3I9IiNmZmZmZmYiLz48L2xpbmVhckdyYWRpZW50PjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZGllbnQpIiAvPjwvc3ZnPg=='); +} +@font-face { + font-family: 'MyWebFont'; + src: url(webfont.eot); + src: url('webfont.eot?#iefix') format('embedded-opentype'), url('webfont.woff') format('woff'), format('truetype') url('webfont.ttf'), url('webfont.svg#svgFontName') format('svg'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/variables-in-at-rules.css b/node_modules/less-middleware/node_modules/less/test/css/variables-in-at-rules.css new file mode 100644 index 000000000..0327eb18d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/variables-in-at-rules.css @@ -0,0 +1,18 @@ +@charset "UTF-8"; +@namespace less "http://lesscss.org"; +@keyframes enlarger { + from { + font-size: 12px; + } + to { + font-size: 15px; + } +} +@-webkit-keyframes reducer { + from { + font-size: 13px; + } + to { + font-size: 10px; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/variables.css b/node_modules/less-middleware/node_modules/less/test/css/variables.css new file mode 100644 index 000000000..f8d8518b9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/variables.css @@ -0,0 +1,45 @@ +.variables { + width: 14cm; +} +.variables { + height: 24px; + color: #888888; + font-family: "Trebuchet MS", Verdana, sans-serif; + quotes: "~" "~"; +} +.redef { + zero: 0; +} +.redef .inition { + three: 3; +} +.values { + minus-one: -1; + font-family: 'Trebuchet', 'Trebuchet', 'Trebuchet'; + color: #888888 !important; + multi: something 'A', B, C, 'Trebuchet'; +} +.variable-names { + name: 'hello'; +} +.alpha { + filter: alpha(opacity=42); +} +.testPollution { + a: 'no-pollution'; +} +.units { + width: 1px; + same-unit-as-previously: 1px; + square-pixel-divided: 1px; + odd-unit: 2; + percentage: 500%; + pixels: 500px; + conversion-metric-a: 30mm; + conversion-metric-b: 3cm; + conversion-imperial: 3in; + custom-unit: 420octocats; + custom-unit-cancelling: 18dogs; + mix-units: 2px; + invalid-units: 1px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/css/whitespace.css b/node_modules/less-middleware/node_modules/less/test/css/whitespace.css new file mode 100644 index 000000000..74c9b65e6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/css/whitespace.css @@ -0,0 +1,42 @@ +.whitespace { + color: white; +} +.whitespace { + color: white; +} +.whitespace { + color: white; +} +.whitespace { + color: white; +} +.whitespace { + color: white ; +} +.white, +.space, +.mania { + color: white; +} +.no-semi-column { + color: #ffffff; +} +.no-semi-column { + color: white; + white-space: pre; +} +.no-semi-column { + border: 2px solid #ffffff; +} +.newlines { + background: the, + great, + wall; + border: 2px + solid + black; +} +.sel .newline_ws .tab_ws { + color: white; + background-position: 45 -23; +} diff --git a/node_modules/less-middleware/node_modules/less/test/data/data-uri-fail.png b/node_modules/less-middleware/node_modules/less/test/data/data-uri-fail.png new file mode 100644 index 000000000..f91b59fb3 Binary files /dev/null and b/node_modules/less-middleware/node_modules/less/test/data/data-uri-fail.png differ diff --git a/node_modules/less-middleware/node_modules/less/test/data/image.jpg b/node_modules/less-middleware/node_modules/less/test/data/image.jpg new file mode 100644 index 000000000..83f777909 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/data/image.jpg @@ -0,0 +1 @@ +not actually a jpeg file diff --git a/node_modules/less-middleware/node_modules/less/test/data/page.html b/node_modules/less-middleware/node_modules/less/test/data/page.html new file mode 100644 index 000000000..ccdfe565d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/data/page.html @@ -0,0 +1 @@ +

    This page is 100% Awesome.

    diff --git a/node_modules/less-middleware/node_modules/less/test/index.js b/node_modules/less-middleware/node_modules/less/test/index.js new file mode 100644 index 000000000..33e79637f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/index.js @@ -0,0 +1,45 @@ +var lessTest = require("./less-test"), + lessTester = lessTest(), + path = require("path"), + stylize = require('../lib/less/lessc_helper').stylize; + +function getErrorPathReplacementFunction(dir) { + return function(input) { + return input.replace( + "{path}", path.join(process.cwd(), "/test/less/" + dir + "/")) + .replace("{pathrel}", path.join("test", "less", dir + "/")) + .replace("{pathhref}", "") + .replace("{404status}", "") + .replace(/\r\n/g, '\n'); + }; +} + +console.log("\n" + stylize("Less", 'underline') + "\n"); +lessTester.runTestSet({strictMath: true, relativeUrls: true, silent: true}); +lessTester.runTestSet({strictMath: true, strictUnits: true}, "errors/", + lessTester.testErrors, null, getErrorPathReplacementFunction("errors")); +lessTester.runTestSet({strictMath: true, strictUnits: true, javascriptEnabled: false}, "no-js-errors/", + lessTester.testErrors, null, getErrorPathReplacementFunction("no-js-errors")); +lessTester.runTestSet({strictMath: true, dumpLineNumbers: 'comments'}, "debug/", null, + function(name) { return name + '-comments'; }); +lessTester.runTestSet({strictMath: true, dumpLineNumbers: 'mediaquery'}, "debug/", null, + function(name) { return name + '-mediaquery'; }); +lessTester.runTestSet({strictMath: true, dumpLineNumbers: 'all'}, "debug/", null, + function(name) { return name + '-all'; }); +lessTester.runTestSet({strictMath: true, relativeUrls: false, rootpath: "folder (1)/"}, "static-urls/"); +lessTester.runTestSet({strictMath: true, compress: true}, "compression/"); +lessTester.runTestSet({}, "legacy/"); +lessTester.runTestSet({strictMath: true, strictUnits: true, sourceMap: true, globalVars: true }, "sourcemaps/", + lessTester.testSourcemap, null, null, + function(filename, type) { + if (type === "vars") { + return path.join('test/less/', filename) + '.json'; + } + return path.join('test/sourcemaps', filename) + '.json'; + }); +lessTester.runTestSet({globalVars: true, banner: "/**\n * Test\n */\n"}, "globalVars/", + null, null, null, function(name) { return path.join('test/less/', name) + '.json'; }); +lessTester.runTestSet({modifyVars: true}, "modifyVars/", + null, null, null, function(name) { return path.join('test/less/', name) + '.json'; }); +lessTester.runTestSet({urlArgs: '424242'}, "url-args/"); +lessTester.testNoOptions(); diff --git a/node_modules/less-middleware/node_modules/less/test/less-test.js b/node_modules/less-middleware/node_modules/less/test/less-test.js new file mode 100644 index 000000000..4bba05b24 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less-test.js @@ -0,0 +1,258 @@ +/*jshint latedef: nofunc */ + +module.exports = function() { + var path = require('path'), + fs = require('fs'); + + var less = require('../lib/less'); + var stylize = require('../lib/less/lessc_helper').stylize; + + var globals = Object.keys(global); + + var oneTestOnly = process.argv[2]; + + var isVerbose = process.env.npm_config_loglevel === 'verbose'; + + var totalTests = 0, + failedTests = 0, + passedTests = 0; + + + less.tree.functions.add = function (a, b) { + return new(less.tree.Dimension)(a.value + b.value); + }; + less.tree.functions.increment = function (a) { + return new(less.tree.Dimension)(a.value + 1); + }; + less.tree.functions._color = function (str) { + if (str.value === "evil red") { return new(less.tree.Color)("600"); } + }; + + function testSourcemap(name, err, compiledLess, doReplacements, sourcemap) { + fs.readFile(path.join('test/', name) + '.json', 'utf8', function (e, expectedSourcemap) { + process.stdout.write("- " + name + ": "); + if (sourcemap === expectedSourcemap) { + ok('OK'); + } else if (err) { + fail("ERROR: " + (err && err.message)); + if (isVerbose) { + console.error(); + console.error(err.stack); + } + } else { + difference("FAIL", expectedSourcemap, sourcemap); + } + }); + } + + function testErrors(name, err, compiledLess, doReplacements) { + fs.readFile(path.join('test/less/', name) + '.txt', 'utf8', function (e, expectedErr) { + process.stdout.write("- " + name + ": "); + expectedErr = doReplacements(expectedErr, 'test/less/errors/'); + if (!err) { + if (compiledLess) { + fail("No Error", 'red'); + } else { + fail("No Error, No Output"); + } + } else { + var errMessage = less.formatError(err); + if (errMessage === expectedErr) { + ok('OK'); + } else { + difference("FAIL", expectedErr, errMessage); + } + } + }); + } + + function globalReplacements(input, directory) { + var p = path.join(process.cwd(), directory), + pathimport = path.join(process.cwd(), directory + "import/"), + pathesc = p.replace(/[.:/\\]/g, function(a) { return '\\' + (a=='\\' ? '\/' : a); }), + pathimportesc = pathimport.replace(/[.:/\\]/g, function(a) { return '\\' + (a=='\\' ? '\/' : a); }); + + return input.replace(/\{path\}/g, p) + .replace(/\{pathesc\}/g, pathesc) + .replace(/\{pathimport\}/g, pathimport) + .replace(/\{pathimportesc\}/g, pathimportesc) + .replace(/\r\n/g, '\n'); + } + + function checkGlobalLeaks() { + return Object.keys(global).filter(function(v) { + return globals.indexOf(v) < 0; + }); + } + + function runTestSet(options, foldername, verifyFunction, nameModifier, doReplacements, getFilename) { + foldername = foldername || ""; + + if(!doReplacements) { + doReplacements = globalReplacements; + } + + function getBasename(file) { + return foldername + path.basename(file, '.less'); + } + + fs.readdirSync(path.join('test/less/', foldername)).forEach(function (file) { + if (! /\.less/.test(file)) { return; } + + var name = getBasename(file); + + if (oneTestOnly && name !== oneTestOnly) { + return; + } + + totalTests++; + + if (options.sourceMap) { + var sourceMapOutput; + options.writeSourceMap = function(output) { + sourceMapOutput = output; + }; + options.sourceMapOutputFilename = name + ".css"; + options.sourceMapBasepath = path.join(process.cwd(), "test/less"); + options.sourceMapRootpath = "testweb/"; + } + + options.getVars = function(file) { + return JSON.parse(fs.readFileSync(getFilename(getBasename(file), 'vars'), 'utf8')); + }; + + toCSS(options, path.join('test/less/', foldername + file), function (err, less) { + + if (verifyFunction) { + return verifyFunction(name, err, less, doReplacements, sourceMapOutput); + } + var css_name = name; + if(nameModifier) { css_name = nameModifier(name); } + fs.readFile(path.join('test/css', css_name) + '.css', 'utf8', function (e, css) { + process.stdout.write("- " + css_name + ": "); + + css = css && doReplacements(css, 'test/less/' + foldername); + if (less === css) { ok('OK'); } + else if (err) { + fail("ERROR: " + (err && err.message)); + if (isVerbose) { + console.error(); + console.error(err.stack); + } + } else { + difference("FAIL", css, less); + } + }); + }); + }); + } + + function diff(left, right) { + require('diff').diffLines(left, right).forEach(function(item) { + if(item.added || item.removed) { + var text = item.value.replace("\n", String.fromCharCode(182) + "\n"); + process.stdout.write(stylize(text, item.added ? 'green' : 'red')); + } else { + process.stdout.write(item.value); + } + }); + console.log(""); + } + + function fail(msg) { + console.error(stylize(msg, 'red')); + failedTests++; + endTest(); + } + + function difference(msg, left, right) { + console.warn(stylize(msg, 'yellow')); + failedTests++; + + diff(left, right); + endTest(); + } + + function ok(msg) { + console.log(stylize(msg, 'green')); + passedTests++; + endTest(); + } + + function endTest() { + var leaked = checkGlobalLeaks(); + if (failedTests + passedTests === totalTests) { + console.log(""); + if (failedTests > 0) { + console.error(failedTests + stylize(" Failed", "red") + ", " + passedTests + " passed"); + } else { + console.log(stylize("All Passed ", "green") + passedTests + " run"); + } + if (leaked.length > 0) { + console.log(""); + console.warn(stylize("Global leak detected: ", "red") + leaked.join(', ')); + } + + if (leaked.length || failedTests) { + //process.exit(1); + process.on('exit', function() { process.reallyExit(1) }); + } + } + } + + function toCSS(options, path, callback) { + var css; + options = options || {}; + fs.readFile(path, 'utf8', function (e, str) { + if (e) { return callback(e); } + + options.paths = [require('path').dirname(path)]; + options.filename = require('path').resolve(process.cwd(), path); + options.optimization = options.optimization || 0; + + var parser = new(less.Parser)(options); + var additionalData = {}; + if (options.globalVars) { + additionalData.globalVars = options.getVars(path); + } else if (options.modifyVars) { + additionalData.modifyVars = options.getVars(path); + } + if (options.banner) { + additionalData.banner = options.banner; + } + parser.parse(str, function (err, tree) { + if (err) { + callback(err); + } else { + try { + css = tree.toCSS(options); + var css2 = tree.toCSS(options); // integration test that 2nd call gets same output + if (css2 !== css) { throw new Error("css not equal to 2nd call"); } + callback(null, css); + } catch (e) { + callback(e); + } + } + }, additionalData); + }); + } + + function testNoOptions() { + totalTests++; + try { + process.stdout.write("- Integration - creating parser without options: "); + new(less.Parser)(); + } catch(e) { + fail(stylize("FAIL\n", "red")); + return; + } + ok(stylize("OK\n", "green")); + } + + return { + runTestSet: runTestSet, + testErrors: testErrors, + testSourcemap: testSourcemap, + testNoOptions: testNoOptions + }; +}; diff --git a/node_modules/less-middleware/node_modules/less/test/less/charsets.less b/node_modules/less-middleware/node_modules/less/test/less/charsets.less new file mode 100644 index 000000000..550d40e97 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/charsets.less @@ -0,0 +1,3 @@ +@charset "UTF-8"; + +@import "import/import-charset-test"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/colors.less b/node_modules/less-middleware/node_modules/less/test/less/colors.less new file mode 100644 index 000000000..7abda4e53 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/colors.less @@ -0,0 +1,98 @@ +#yelow { + #short { + color: #fea; + } + #long { + color: #ffeeaa; + } + #rgba { + color: rgba(255, 238, 170, 0.1); + } + #argb { + color: argb(rgba(255, 238, 170, 0.1)); + } +} + +#blue { + #short { + color: #00f; + } + #long { + color: #0000ff; + } + #rgba { + color: rgba(0, 0, 255, 0.1); + } + #argb { + color: argb(rgba(0, 0, 255, 0.1)); + } +} + +#alpha #hsla { + color: hsla(11, 20%, 20%, 0.6); +} + +#overflow { + .a { color: (#111111 - #444444); } // #000000 + .b { color: (#eee + #fff); } // #ffffff + .c { color: (#aaa * 3); } // #ffffff + .d { color: (#00ee00 + #009900); } // #00ff00 + .e { color: rgba(-99.9, 31.4159, 321, 0.42); } +} + +#grey { + color: rgb(200, 200, 200); +} + +#333333 { + color: rgb(20%, 20%, 20%); +} + +#808080 { + color: hsl(50, 0%, 50%); +} + +#00ff00 { + color: hsl(120, 100%, 50%); +} + +.lightenblue { + color: lighten(blue, 10%); +} + +.darkenblue { + color: darken(blue, 10%); +} + +.unknowncolors { + color: blue2; + border: 2px solid superred; +} + +.transparent { + color: transparent; + background-color: rgba(0, 0, 0, 0); +} +#alpha { + @colorvar: rgba(150, 200, 150, 0.7); + #fromvar { + opacity: alpha(@colorvar); + } + #short { + opacity: alpha(#aaa); + } + #long { + opacity: alpha(#bababa); + } + #rgba { + opacity: alpha(rgba(50, 120, 95, 0.2)); + } + #hsl { + opacity: alpha(hsl(120, 100%, 50%)); + } +} + +#percentage { + color: red(rgb(100%, 0, 0)); + border-color: rgba(100%, 0, 0, 50%); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/comments.less b/node_modules/less-middleware/node_modules/less/test/less/comments.less new file mode 100644 index 000000000..bfdce2480 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/comments.less @@ -0,0 +1,96 @@ +/******************\ +* * +* Comment Header * +* * +\******************/ + +/* + + Comment + +*/ + +/* + * Comment Test + * + * - cloudhead (http://cloudhead.net) + * + */ + +//////////////// +@var: "content"; +//////////////// + +/* Colors + * ------ + * #EDF8FC (background blue) + * #166C89 (darkest blue) + * + * Text: + * #333 (standard text) // A comment within a comment! + * #1F9EC9 (standard link) + * + */ + +/* @group Variables +------------------- */ +#comments /* boo *//* boo again*/, +//.commented_out1 +//.commented_out2 +//.commented_out3 +.comments //end of comments1 +//end of comments2 +{ + /**/ // An empty comment + color: red; /* A C-style comment */ /* A C-style comment */ + background-color: orange; // A little comment + font-size: 12px; + + /* lost comment */ content: @var; + + border: 1px solid black; + + // padding & margin // + padding: 0; // }{ '" + margin: 2em; +} // + +/* commented out + #more-comments { + color: grey; + } +*/ + +.selector /* .with */, .lots, /* of */ .comments { + color/* survive */ /* me too */: grey, /* blue */ orange; + -webkit-border-radius: 2px /* webkit only */; + -moz-border-radius: (2px * 4) /* moz only with operation */; +} + +.mixin_def_with_colors(@a: white, // in + @b: 1px //put in @b - causes problems! ---> + ) // the + when (@a = white) { + .test { + color: @b; + } +} +.mixin_def_with_colors(); + +// .s when +//R/2 + +.sr-only-focusable { + clip: auto; +} + +@-webkit-keyframes /* Safari */ hover /* and Chrome */ { + 0% { + color: red; + } +} + +#last { color: blue } +// + +/* *//* { *//* *//* *//* */#div { color:#A33; }/* } */ diff --git a/node_modules/less-middleware/node_modules/less/test/less/compression/compression.less b/node_modules/less-middleware/node_modules/less/test/less/compression/compression.less new file mode 100644 index 000000000..c196336a7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/compression/compression.less @@ -0,0 +1,36 @@ +#colours { + color1: #fea; + color2: #ffeeaa; + color3: rgba(255, 238, 170, 0.1); + @color1: #fea; + string: "@{color1}"; + /* comments are stripped */ + // both types! + /*! but not this type + Note preserved whitespace + */ +} +dimensions { + val: 0.1px; + val: 0em; + val: 4cm; + val: 0.2; + val: 5; + angles-must-have-unit: 0deg; + durations-must-have-unit: 0s; + length-doesnt-have-unit: 0px; + width: auto\9; +} +@page { + marks: none; +@top-left-corner { + vertical-align: top; +} +@top-left { + vertical-align: top; +} +} +.shadow ^ .dom, +body ^^ .shadow { + display: done; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/css-3.less b/node_modules/less-middleware/node_modules/less/test/less/css-3.less new file mode 100644 index 000000000..312653c07 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/css-3.less @@ -0,0 +1,140 @@ +.comma-delimited { + text-shadow: -1px -1px 1px red, 6px 5px 5px yellow; + -moz-box-shadow: 0pt 0pt 2px rgba(255, 255, 255, 0.4) inset, + 0pt 4px 6px rgba(255, 255, 255, 0.4) inset; + -webkit-transform: rotate(-0.0000000001deg); +} +@font-face { + font-family: Headline; + unicode-range: U+??????, U+0???, U+0-7F, U+A5; +} +.other { + -moz-transform: translate(0, 11em) rotate(-90deg); + transform: rotateX(45deg); +} +.item[data-cra_zy-attr1b-ut3=bold] { + font-weight: bold; +} +p:not([class*="lead"]) { + color: black; +} + +input[type="text"].class#id[attr=32]:not(1) { + color: white; +} + +div#id.class[a=1][b=2].class:not(1) { + color: white; +} + +ul.comma > li:not(:only-child)::after { + color: white; +} + +ol.comma > li:nth-last-child(2)::after { + color: white; +} + +li:nth-child(4n+1), +li:nth-child(-5n), +li:nth-child(-n+2) { + color: white; +} + +a[href^="http://"] { + color: black; +} + +a[href$="http://"] { + color: black; +} + +form[data-disabled] { + color: black; +} + +p::before { + color: black; +} + +#issue322 { + -webkit-animation: anim2 7s infinite ease-in-out; +} + +@-webkit-keyframes frames { + 0% { border: 1px } + 5.5% { border: 2px } + 100% { border: 3px } +} + +@keyframes fontbulger1 { + to { + font-size: 15px; + } + from,to { + font-size: 12px; + } + 0%,100% { + font-size: 12px; + } +} + +.units { + font: 1.2rem/2rem; + font: 8vw/9vw; + font: 10vh/12vh; + font: 12vm/15vm; + font: 12vmin/15vmin; + font: 1.2ch/1.5ch; +} + +@supports ( box-shadow: 2px 2px 2px black ) or + ( -moz-box-shadow: 2px 2px 2px black ) { + .outline { + box-shadow: 2px 2px 2px black; + -moz-box-shadow: 2px 2px 2px black; + } +} + +@-x-document url-prefix(""github.com"") { + h1 { + color: red; + } +} + +@viewport { + font-size: 10px; +} +@namespace foo url(http://www.example.com); + +foo|h1 { color: blue; } +foo|* { color: yellow; } +|h1 { color: red; } +*|h1 { color: green; } +h1 { color: green; } +.upper-test { + UpperCaseProperties: allowed; +} +@host { + div { + display: block; + } +} +::distributed(input::placeholder) { + color: #b3b3b3; +} +.shadow ^ .dom, +body ^^ .shadow { + display: done; +} + +:host(.sel .a), +:host-context(.sel .b), +.sel /deep/ .b, +::content .sel { + type: shadow-dom; +} + +#issue2066 { + background: url('/images/icon-team.svg') 0 0 / contain; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/css-escapes.less b/node_modules/less-middleware/node_modules/less/test/less/css-escapes.less new file mode 100644 index 000000000..6a4b28306 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/css-escapes.less @@ -0,0 +1,33 @@ +@ugly: fuchsia; + +.escape\|random\|char { + color: red; +} + +.mixin\!tUp { + font-weight: bold; +} + +// class="404" +.\34 04 { + background: red; + + strong { + color: @ugly; + .mixin\!tUp; + } +} + +.trailingTest\+ { + color: red; +} + +/* This hideous test of hideousness checks for the selector "blockquote" with various permutations of hex escapes */ +\62\6c\6f \63 \6B \0071 \000075o\74 e { + color: silver; +} + +[ng\:cloak], +ng\:form { + display: none; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/css-guards.less b/node_modules/less-middleware/node_modules/less/test/less/css-guards.less new file mode 100644 index 000000000..85ec8d294 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/css-guards.less @@ -0,0 +1,102 @@ + +.light when (lightness(@a) > 50%) { + color: green; +} +.dark when (lightness(@a) < 50%) { + color: orange; +} +@a: #ddd; + +.see-the { + @a: #444; // this mirrors what mixins do - they evaluate the guards at the point of definition + .light(); + .dark(); +} + +.hide-the { + .light(); + .dark(); +} + +.multiple-conditions-1 when (@b = 1), (@c = 2), (@d = 3) { + color: red; +} + +.multiple-conditions-2 when (@b = 1), (@c = 2), (@d = 2) { + color: blue; +} + +@b: 2; +@c: 3; +@d: 3; + +.inheritance when (@b = 2) { + .test { + color: black; + } + &:hover { + color: pink; + } + .hideme when (@b = 1) { + color: green; + } + & when (@b = 1) { + hideme: green; + } +} + +.hideme when (@b = 1) { + .test { + color: black; + } + &:hover { + color: pink; + } + .hideme when (@b = 1) { + color: green; + } +} + +& when (@b = 1) { + .hideme { + color: red; + } +} + +.mixin-with-guard-inside(@colWidth) { + // selector with guard (applies also to & when() ...) + .clsWithGuard when (@colWidth <= 0) { + dispaly: none; + } +} + +.mixin-with-guard-inside(0px); + +.dont-split-me-up { + width: 1px; + & when (@c = 3) { + color: red; + } + & when (@c = 3) { + height: 1px; + } + + & when (@c = 3) { // creates invalid css but tests that we don't fold it in + sibling: true; + } +} + +.scope-check when (@c = 3) { + @k: 1px; + & when (@c = 3) { + @k: 2px; + sub-prop: @k; + } + prop: @k; +} +.scope-check-2 { + .scope-check(); + @k:4px; +} +.errors-if-called when (@c = never) { + .mixin-doesnt-exist(); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/css.less b/node_modules/less-middleware/node_modules/less/test/less/css.less new file mode 100644 index 000000000..766bdd4d0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/css.less @@ -0,0 +1,108 @@ +@charset "utf-8"; +div { color: black; } +div { width: 99%; } + +* { + min-width: 45em; +} + +h1, h2 > a > p, h3 { + color: none; +} + +div.class { + color: blue; +} + +div#id { + color: green; +} + +.class#id { + color: purple; +} + +.one.two.three { + color: grey; +} + +@media print { + * { + font-size: 3em; + } +} + +@media screen { + * { + font-size: 10px; + } +} + +@font-face { + font-family: 'Garamond Pro'; +} + +a:hover, a:link { + color: #999; +} + +p, p:first-child { + text-transform: none; +} + +q:lang(no) { + quotes: none; +} + +p + h1 { + font-size: +2.2em; +} + +#shorthands { + border: 1px solid #000; + font: 12px/16px Arial; + font: 100%/16px Arial; + margin: 1px 0; + padding: 0 auto; +} + +#more-shorthands { + margin: 0; + padding: 1px 0 2px 0; + font: normal small/20px 'Trebuchet MS', Verdana, sans-serif; + font: 0/0 a; + border-radius: 5px / 10px; +} + +.misc { + -moz-border-radius: 2px; + display: -moz-inline-stack; + width: .1em; + background-color: #009998; + background: -webkit-gradient(linear, left top, left bottom, from(red), to(blue)); + margin: ; + .nested-multiple { + multiple-semi-colons: yes;;;;;; + }; + filter: alpha(opacity=100); + width: auto\9; +} + +#important { + color: red !important; + width: 100%!important; + height: 20px ! important; +} + +.def-font(@name) { + @font-face { + font-family: @name + } +} + +.def-font(font-a); +.def-font(font-b); + +.æøå { + margin: 0; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/debug/import/test.less b/node_modules/less-middleware/node_modules/less/test/less/debug/import/test.less new file mode 100644 index 000000000..795082f5a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/debug/import/test.less @@ -0,0 +1,25 @@ +@charset "ISO-8859-1"; + +.mixin_import1() { + @media all { + .tst { + color: black; + @media screen { + color: red; + .tst3 { + color: white; + } + } + } + } +} + +.mixin_import2() { + .tst2 { + color: white; + } +} + +.tst3 { + color: grey; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/debug/linenumbers.less b/node_modules/less-middleware/node_modules/less/test/less/debug/linenumbers.less new file mode 100644 index 000000000..3bcaed014 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/debug/linenumbers.less @@ -0,0 +1,33 @@ +@charset "UTF-8"; + +@import "import/test.less"; + +.start() { + .test2 { + color: red; + } +} + +.mix() { + color: black; +} + +.test1 { + .mix(); +} + +.start(); + +.mixin_import1(); + +.mixin_import2(); + +@debug: 1; +& when (@debug = 1) { + .test { + color: red; + & when (@debug = 1) { + width: 2; + } + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/detached-rulesets.less b/node_modules/less-middleware/node_modules/less/test/less/detached-rulesets.less new file mode 100644 index 000000000..6a98d890a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/detached-rulesets.less @@ -0,0 +1,103 @@ +@ruleset: { + color: black; + background: white; + }; + +@a: 1px; +.wrap-mixin(@ruleset) { + @a: hidden and if you see this in the output its a bug; + @b: visible; + @d: magic-frame; // same behaviour as mixin calls - falls back to this frame + .wrap-selector { + @c: visible; + @ruleset(); + visible-one: @b; + visible-two: @c; + } +}; + +.wrap-mixin({ + color: black; + one: @a; + @b: hidden and if you see this in the output its a bug; + @c: hidden and if you see this in the output its a bug; + four: @d; +}); + +.wrap-mixin(@ruleset: { + color: red; +}); + +.wrap-mixin(@ruleset); + +.desktop-and-old-ie(@rules) { + @media screen and (min-width: 1200) { @rules(); } + html.lt-ie9 & { @rules(); } +} + +header { + background: blue; + + .desktop-and-old-ie({ + background: red; + }); +} + +.wrap-mixin-calls-wrap(@ruleset) { + .wrap-mixin(@ruleset); +}; + +.wrap-mixin({ + test: extra-wrap; + .wrap-mixin-calls-wrap({ + test: wrapped-twice; + }); +}); + +.wrap-mixin({ + test-func: unit(90px); + test-arithmetic: unit((9+9), px); +}); +// without mixins +@ruleset-2: { + b: 1; +}; +.without-mixins { + @ruleset-2(); +} +@my-ruleset: { + .my-selector { + @media tv { + background-color: black; + } + } + }; +@media (orientation:portrait) { + @my-ruleset(); + .wrap-media-mixin({ + @media tv { + .triple-wrapped-mq { + triple: true; + } + } + }); +} +.wrap-media-mixin(@ruleset) { + @media widescreen { + @media print { + @ruleset(); + } + @ruleset(); + } + @ruleset(); +} +// unlocking mixins +@my-mixins: { + .mixin() { + test: test; + } +}; +@my-mixins(); +.a { + .mixin(); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/empty.less b/node_modules/less-middleware/node_modules/less/test/less/empty.less new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.less b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.less new file mode 100644 index 000000000..9b708de93 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.less @@ -0,0 +1,3 @@ +.a { + error: (1px + 3em); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.txt new file mode 100644 index 000000000..9ea454387 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units.txt @@ -0,0 +1,4 @@ +SyntaxError: Incompatible units. Change the units or use the unit function. Bad units: 'px' and 'em'. in {path}add-mixed-units.less on line 2, column 3: +1 .a { +2 error: (1px + 3em); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.less new file mode 100644 index 000000000..266311605 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.less @@ -0,0 +1,3 @@ +.a { + error: ((1px * 2px) + (3em * 3px)); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.txt new file mode 100644 index 000000000..ca34304f6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/add-mixed-units2.txt @@ -0,0 +1,4 @@ +SyntaxError: Incompatible units. Change the units or use the unit function. Bad units: 'px*px' and 'em*px'. in {path}add-mixed-units2.less on line 2, column 3: +1 .a { +2 error: ((1px * 2px) + (3em * 3px)); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.less b/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.less new file mode 100644 index 000000000..a1473805d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.less @@ -0,0 +1,4 @@ + +@keyframes @name { + 50% {width: 20px;} +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.txt new file mode 100644 index 000000000..240540a06 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/at-rules-undefined-var.txt @@ -0,0 +1,4 @@ +NameError: variable @name is undefined in {path}at-rules-undefined-var.less on line 2, column 12: +1 +2 @keyframes @name { +3 50% {width: 20px;} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.less new file mode 100644 index 000000000..c2dc6ac0e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.less @@ -0,0 +1 @@ +@@demo: "hi"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.txt new file mode 100644 index 000000000..5ae9d4a41 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/bad-variable-declaration1.txt @@ -0,0 +1,2 @@ +ParseError: Unrecognised input in {path}bad-variable-declaration1.less on line 1, column 1: +1 @@demo: "hi"; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.less b/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.less new file mode 100644 index 000000000..5a1edd011 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.less @@ -0,0 +1,3 @@ +.test { + color: color("NOT A COLOR"); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.txt new file mode 100644 index 000000000..08990c30a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-func-invalid-color.txt @@ -0,0 +1,4 @@ +ArgumentError: error evaluating function `color`: argument must be a color keyword or 3/6 digit hex e.g. #FFF in {path}color-func-invalid-color.less on line 2, column 10: +1 .test { +2 color: color("NOT A COLOR"); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.less b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.less new file mode 100644 index 000000000..0e6c5debe --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.less @@ -0,0 +1,3 @@ +.a { + @wrongHEXColorCode: #DCALLB; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.txt new file mode 100644 index 000000000..0f8a82ce4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code.txt @@ -0,0 +1,4 @@ +SyntaxError: Invalid HEX color code in {path}color-invalid-hex-code.less on line 2, column 29: +1 .a { +2 @wrongHEXColorCode: #DCALLB; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.less new file mode 100644 index 000000000..cb9a9b767 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.less @@ -0,0 +1,3 @@ +.a { + @wrongHEXColorCode: #fffblack; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.txt new file mode 100644 index 000000000..dd3996b1f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/color-invalid-hex-code2.txt @@ -0,0 +1,4 @@ +SyntaxError: Invalid HEX color code in {path}color-invalid-hex-code2.less on line 2, column 29: +1 .a { +2 @wrongHEXColorCode: #fffblack; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.less b/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.less new file mode 100644 index 000000000..a7d263965 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.less @@ -0,0 +1 @@ +#gaga /* Comment */ span { color: red } \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.txt new file mode 100644 index 000000000..e48f878ca --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/comment-in-selector.txt @@ -0,0 +1,2 @@ +ParseError: Unrecognised input in {path}comment-in-selector.less on line 1, column 21: +1 #gaga /* Comment */ span { color: red } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.less b/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.less new file mode 100644 index 000000000..db6639e17 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.less @@ -0,0 +1,4 @@ + +selector when (default()) { + color: red; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.txt new file mode 100644 index 000000000..022f5222e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/css-guard-default-func.txt @@ -0,0 +1,4 @@ +SyntaxError: error evaluating function `default`: it is currently only allowed in parametric mixin guards, in {path}css-guard-default-func.less on line 2, column 16: +1 +2 selector when (default()) { +3 color: red; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.less new file mode 100644 index 000000000..ac5b8db03 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.less @@ -0,0 +1,6 @@ +@a: { + b: 1; +}; +.a { + a: @a; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.txt new file mode 100644 index 000000000..7407741c8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-1.txt @@ -0,0 +1,4 @@ +SyntaxError: Rulesets cannot be evaluated on a property. in {path}detached-ruleset-1.less on line 5, column 3: +4 .a { +5 a: @a; +6 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.less new file mode 100644 index 000000000..51a7af6be --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.less @@ -0,0 +1,6 @@ +@a: { + b: 1; +}; +.a { + a: @a(); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.txt new file mode 100644 index 000000000..f18e09353 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-2.txt @@ -0,0 +1,4 @@ +ParseError: Unrecognised input in {path}detached-ruleset-2.less on line 5, column 3: +4 .a { +5 a: @a(); +6 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.less new file mode 100644 index 000000000..c50119d99 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.less @@ -0,0 +1,4 @@ +@a: { + b: 1; +}; +@a(); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.txt new file mode 100644 index 000000000..15d281fa3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-3.txt @@ -0,0 +1,4 @@ +SyntaxError: properties must be inside selector blocks, they cannot be in the root. in {path}detached-ruleset-3.less on line 2, column 3: +1 @a: { +2 b: 1; +3 }; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.less new file mode 100644 index 000000000..14ac314bb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.less @@ -0,0 +1,5 @@ +.mixin-definition(@a: { + b: 1; +}) { + @a(); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.txt new file mode 100644 index 000000000..d6d6526d4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-4.txt @@ -0,0 +1,3 @@ +ParseError: Unrecognised input in {path}detached-ruleset-4.less on line 1, column 18: +1 .mixin-definition(@a: { +2 b: 1; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.less new file mode 100644 index 000000000..174ebf354 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.less @@ -0,0 +1,4 @@ +.mixin-definition(@b) { + @a(); +} +.mixin-definition({color: red;}); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.txt new file mode 100644 index 000000000..561897950 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-5.txt @@ -0,0 +1,3 @@ +SyntaxError: variable @a is undefined in {path}detached-ruleset-5.less on line 4, column 1: +3 } +4 .mixin-definition({color: red;}); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.less b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.less new file mode 100644 index 000000000..121099f75 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.less @@ -0,0 +1,5 @@ +.a { + b: { + color: red; + }; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.txt new file mode 100644 index 000000000..07840445e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/detached-ruleset-6.txt @@ -0,0 +1,4 @@ +ParseError: Unrecognised input in {path}detached-ruleset-6.less on line 2, column 3: +1 .a { +2 b: { +3 color: red; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.less b/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.less new file mode 100644 index 000000000..d228b7c47 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.less @@ -0,0 +1,3 @@ +.a { + error: (1px / 3em); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.txt new file mode 100644 index 000000000..c189d2aad --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/divide-mixed-units.txt @@ -0,0 +1,4 @@ +SyntaxError: Multiple units in dimension. Correct the units or use the unit function. Bad unit: px/em in {path}divide-mixed-units.less on line 2, column 3: +1 .a { +2 error: (1px / 3em); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.less b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.less new file mode 100644 index 000000000..84689ef39 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.less @@ -0,0 +1,3 @@ +:extend(.a all) { + property: red; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.txt new file mode 100644 index 000000000..bd2e3cd75 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-no-selector.txt @@ -0,0 +1,3 @@ +SyntaxError: Extend must be used to extend a selector, it cannot be used on its own in {path}extend-no-selector.less on line 1, column 17: +1 :extend(.a all) { +2 property: red; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.less b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.less new file mode 100644 index 000000000..90ee512c5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.less @@ -0,0 +1,3 @@ +.a:extend(.b all).c { + property: red; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.txt new file mode 100644 index 000000000..32ebedfc4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/extend-not-at-end.txt @@ -0,0 +1,3 @@ +SyntaxError: Extend can only be used at the end of selector in {path}extend-not-at-end.less on line 1, column 21: +1 .a:extend(.b all).c { +2 property: red; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.less b/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.less new file mode 100644 index 000000000..66768c854 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.less @@ -0,0 +1 @@ +@import malformed "this-statement-is-invalid.less"; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.txt new file mode 100644 index 000000000..f8ba9f87c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-malformed.txt @@ -0,0 +1,3 @@ +SyntaxError: malformed import statement in {path}import-malformed.less on line 1, column 1: +1 @import malformed "this-statement-is-invalid.less"; +2 diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.less b/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.less new file mode 100644 index 000000000..5ce8e4d9e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.less @@ -0,0 +1,6 @@ +.a { + color: green; + // tests line number for import reference is correct +} + +@import "file-does-not-exist.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.txt new file mode 100644 index 000000000..488d154a8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-missing.txt @@ -0,0 +1,3 @@ +FileError: '{pathhref}file-does-not-exist.less' wasn't found{404status} in {path}import-missing.less on line 6, column 1: +5 +6 @import "file-does-not-exist.less"; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.less b/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.less new file mode 100644 index 000000000..bf2c7f65f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.less @@ -0,0 +1 @@ +@import "this-statement-is-invalid.less" \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.txt new file mode 100644 index 000000000..aaa4ac583 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-no-semi.txt @@ -0,0 +1,2 @@ +SyntaxError: missing semi-colon or unrecognised media features on import in {path}import-no-semi.less on line 1, column 1: +1 @import "this-statement-is-invalid.less" diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.less new file mode 100644 index 000000000..4280673b5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.less @@ -0,0 +1 @@ +@import "imports/import-subfolder1.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.txt new file mode 100644 index 000000000..976292765 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder1.txt @@ -0,0 +1,3 @@ +NameError: .mixin-not-defined is undefined in {path}mixin-not-defined.less on line 11, column 1: +10 +11 .mixin-not-defined(); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.less new file mode 100644 index 000000000..a6b9b9ce9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.less @@ -0,0 +1 @@ +@import "imports/import-subfolder2.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.txt new file mode 100644 index 000000000..b5b1a69ba --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/import-subfolder2.txt @@ -0,0 +1,4 @@ +ParseError: missing opening `{` in {path}parse-error-curly-bracket.less on line 4, column 1: +3 } +4 } +5 diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder1.less new file mode 100644 index 000000000..24ec0532a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder1.less @@ -0,0 +1 @@ +@import "subfolder/mixin-not-defined.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder2.less new file mode 100644 index 000000000..6058ad14e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-subfolder2.less @@ -0,0 +1 @@ +@import "subfolder/parse-error-curly-bracket.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-test.less b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-test.less new file mode 100644 index 000000000..a91ae0544 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/import-test.less @@ -0,0 +1,4 @@ +.someclass +{ + font-weight: bold; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/mixin-not-defined.less b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/mixin-not-defined.less new file mode 100644 index 000000000..2bb2d0916 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/mixin-not-defined.less @@ -0,0 +1 @@ +@import "../../mixin-not-defined.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/parse-error-curly-bracket.less b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/parse-error-curly-bracket.less new file mode 100644 index 000000000..f37fa9d00 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/imports/subfolder/parse-error-curly-bracket.less @@ -0,0 +1 @@ +@import "../../parse-error-curly-bracket.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.less b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.less new file mode 100644 index 000000000..9332a37d8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.less @@ -0,0 +1,3 @@ +.scope { + var: `this.foo.toJS`; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.txt new file mode 100644 index 000000000..c4da95085 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-error.txt @@ -0,0 +1,4 @@ +SyntaxError: JavaScript evaluation error: 'TypeError: Cannot read property 'toJS' of undefined' in {path}javascript-error.less on line 2, column 25: +1 .scope { +2 var: `this.foo.toJS`; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.less b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.less new file mode 100644 index 000000000..7cd580c4a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.less @@ -0,0 +1,3 @@ +.scope { + @a: `@{b}`; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.txt new file mode 100644 index 000000000..024bf92bb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/javascript-undefined-var.txt @@ -0,0 +1,4 @@ +NameError: variable @b is undefined in {path}javascript-undefined-var.less on line 2, column 15: +1 .scope { +2 @a: `@{b}`; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.less new file mode 100644 index 000000000..9b0e23afa --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.less @@ -0,0 +1,6 @@ +.mixin(@a : 4, @b : 3, @c: 2) { + will: fail; +} +.mixin-test { + .mixin(@a: 5; @b: 6, @c: 7); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.txt new file mode 100644 index 000000000..a07f5e9d9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-1.txt @@ -0,0 +1,4 @@ +SyntaxError: Cannot mix ; and , as delimiter types in {path}mixed-mixin-definition-args-1.less on line 5, column 30: +4 .mixin-test { +5 .mixin(@a: 5; @b: 6, @c: 7); +6 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.less new file mode 100644 index 000000000..c9709427a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.less @@ -0,0 +1,6 @@ +.mixin(@a : 4, @b : 3, @c: 2) { + will: fail; +} +.mixin-test { + .mixin(@a: 5, @b: 6; @c: 7); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.txt new file mode 100644 index 000000000..fa00183b2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixed-mixin-definition-args-2.txt @@ -0,0 +1,4 @@ +SyntaxError: Cannot mix ; and , as delimiter types in {path}mixed-mixin-definition-args-2.less on line 5, column 26: +4 .mixin-test { +5 .mixin(@a: 5, @b: 6; @c: 7); +6 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.less new file mode 100644 index 000000000..e2dad5cea --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.less @@ -0,0 +1,11 @@ + +.error-is-further-on() { +} + +.pad-here-to-reproduce-error-in() { +} + +.the-import-subfolder-test() { +} + +.mixin-not-defined(); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.txt new file mode 100644 index 000000000..976292765 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-defined.txt @@ -0,0 +1,3 @@ +NameError: .mixin-not-defined is undefined in {path}mixin-not-defined.less on line 11, column 1: +10 +11 .mixin-not-defined(); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.less new file mode 100644 index 000000000..be0d6b1a1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.less @@ -0,0 +1,6 @@ +@saxofon:trumpete; + +.mixin(saxofon) { +} + +.mixin(@saxofon); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.txt new file mode 100644 index 000000000..57df97728 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched.txt @@ -0,0 +1,3 @@ +RuntimeError: No matching definition was found for `.mixin(trumpete)` in {path}mixin-not-matched.less on line 6, column 1: +5 +6 .mixin(@saxofon); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.less new file mode 100644 index 000000000..14f44bf32 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.less @@ -0,0 +1,6 @@ +@saxofon:trumpete; + +.mixin(@a, @b) { +} + +.mixin(@a: @saxofon); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.txt new file mode 100644 index 000000000..dceedaf05 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-matched2.txt @@ -0,0 +1,3 @@ +RuntimeError: No matching definition was found for `.mixin(@a:trumpete)` in {path}mixin-not-matched2.less on line 6, column 1: +5 +6 .mixin(@a: @saxofon); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.less new file mode 100644 index 000000000..2842613ef --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.less @@ -0,0 +1,9 @@ +.something { + & { + .a {value: a} + } + + & { + .b {.a} // was Err. before 1.6.2 + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.txt new file mode 100644 index 000000000..15e64dc20 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixin-not-visible-in-scope-1.txt @@ -0,0 +1,4 @@ +NameError: .a is undefined in {path}mixin-not-visible-in-scope-1.less on line 7, column 13: +6 & { +7 .b {.a} // was Err. before 1.6.2 +8 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.less new file mode 100644 index 000000000..dc90b86b6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.less @@ -0,0 +1,9 @@ + +guard-default-func-conflict { + .m(@x, 1) {} + .m(@x, 2) when (default()) {} + .m(@x, 2) when (default()) {} + + .m(1, 1); + .m(1, 2); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.txt new file mode 100644 index 000000000..e6aaa0a19 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-1.txt @@ -0,0 +1,4 @@ +RuntimeError: Ambiguous use of `default()` found when matching for `.m(1, 2)` in {path}mixins-guards-default-func-1.less on line 8, column 5: +7 .m(1, 1); +8 .m(1, 2); +9 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.less new file mode 100644 index 000000000..079b57379 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.less @@ -0,0 +1,9 @@ + +guard-default-func-conflict { + .m(1) {} + .m(@x) when not(default()) {} + .m(@x) when (@x = 3) and (default()) {} + + .m(2); + .m(3); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.txt new file mode 100644 index 000000000..99a3a66f3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-2.txt @@ -0,0 +1,4 @@ +RuntimeError: Ambiguous use of `default()` found when matching for `.m(3)` in {path}mixins-guards-default-func-2.less on line 8, column 5: +7 .m(2); +8 .m(3); +9 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.less b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.less new file mode 100644 index 000000000..ec357fa18 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.less @@ -0,0 +1,9 @@ + +guard-default-func-conflict { + .m(1) {} + .m(@x) when not(default()) {} + .m(@x) when not(default()) {} + + .m(1); + .m(2); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.txt new file mode 100644 index 000000000..0a85a34cc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/mixins-guards-default-func-3.txt @@ -0,0 +1,4 @@ +RuntimeError: Ambiguous use of `default()` found when matching for `.m(2)` in {path}mixins-guards-default-func-3.less on line 8, column 5: +7 .m(1); +8 .m(2); +9 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.less b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.less new file mode 100644 index 000000000..4eabb60a1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.less @@ -0,0 +1,4 @@ +@ie8: true; +.a when (@ie8 = true), +.b { +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.txt new file mode 100644 index 000000000..3d23e26bc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors.txt @@ -0,0 +1,4 @@ +SyntaxError: Guards are only currently allowed on a single selector. in {path}multiple-guards-on-css-selectors.less on line 3, column 1: +2 .a when (@ie8 = true), +3 .b { +4 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.less new file mode 100644 index 000000000..4b1bc6ff4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.less @@ -0,0 +1,4 @@ +@ie8: true; +.a, +.b when (@ie8 = true) { +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.txt new file mode 100644 index 000000000..d0e5a52bd --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiple-guards-on-css-selectors2.txt @@ -0,0 +1,4 @@ +SyntaxError: Guards are only currently allowed on a single selector. in {path}multiple-guards-on-css-selectors2.less on line 3, column 23: +2 .a, +3 .b when (@ie8 = true) { +4 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.less b/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.less new file mode 100644 index 000000000..ff983a85e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.less @@ -0,0 +1,7 @@ +/* Test */ +#blah { + // blah +} +.a { + error: (1px * 1em); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.txt new file mode 100644 index 000000000..9ed834f1d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/multiply-mixed-units.txt @@ -0,0 +1,4 @@ +SyntaxError: Multiple units in dimension. Correct the units or use the unit function. Bad unit: em*px in {path}multiply-mixed-units.less on line 6, column 3: +5 .a { +6 error: (1px * 1em); +7 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.less new file mode 100644 index 000000000..7c8ec10e6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.less @@ -0,0 +1,3 @@ +.a { + something: (12 (13 + 5 -23) + 5); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.txt new file mode 100644 index 000000000..6fc40ac0b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-1.txt @@ -0,0 +1,4 @@ +SyntaxError: expected ')' got '(' in {path}parens-error-1.less on line 2, column 18: +1 .a { +2 something: (12 (13 + 5 -23) + 5); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.less new file mode 100644 index 000000000..4a392b8ee --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.less @@ -0,0 +1,3 @@ +.a { + something: (12 * (13 + 5 -23)); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.txt new file mode 100644 index 000000000..cee5c52d1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-2.txt @@ -0,0 +1,4 @@ +SyntaxError: expected ')' got '-' in {path}parens-error-2.less on line 2, column 28: +1 .a { +2 something: (12 * (13 + 5 -23)); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.less new file mode 100644 index 000000000..9e6d5405b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.less @@ -0,0 +1,3 @@ +.a { + something: (12 + (13 + 10 -23)); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.txt new file mode 100644 index 000000000..3280ef04e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parens-error-3.txt @@ -0,0 +1,4 @@ +SyntaxError: expected ')' got '-' in {path}parens-error-3.less on line 2, column 29: +1 .a { +2 something: (12 + (13 + 10 -23)); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.less new file mode 100644 index 000000000..f78ceb701 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.less @@ -0,0 +1,4 @@ +body { + background-color: #fff; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.txt new file mode 100644 index 000000000..b5b1a69ba --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-curly-bracket.txt @@ -0,0 +1,4 @@ +ParseError: missing opening `{` in {path}parse-error-curly-bracket.less on line 4, column 1: +3 } +4 } +5 diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.less new file mode 100644 index 000000000..46d023a91 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.less @@ -0,0 +1,5 @@ +@media (extra: bracket)) { + body { + background-color: #fff; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.txt new file mode 100644 index 000000000..5c1aaef2a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-extra-parens.txt @@ -0,0 +1,3 @@ +ParseError: missing opening `(` in {path}parse-error-extra-parens.less on line 1, column 24: +1 @media (extra: bracket)) { +2 body { diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.less new file mode 100644 index 000000000..144a6edf7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.less @@ -0,0 +1,2 @@ +body { + background-color: #fff; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.txt new file mode 100644 index 000000000..7db2716ed --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-bracket.txt @@ -0,0 +1,3 @@ +ParseError: missing closing `}` in {path}parse-error-missing-bracket.less on line 1, column 6: +1 body { +2 background-color: #fff; diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.less new file mode 100644 index 000000000..55d257912 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.less @@ -0,0 +1,5 @@ +@media (missing: bracket { + body { + background-color: #fff; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.txt new file mode 100644 index 000000000..a7a67067a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-missing-parens.txt @@ -0,0 +1,3 @@ +ParseError: missing closing `)` in {path}parse-error-missing-parens.less on line 1, column 8: +1 @media (missing: bracket { +2 body { diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.less b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.less new file mode 100644 index 000000000..6be3de853 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.less @@ -0,0 +1,13 @@ +@import 'import/import-test.less'; + +body +{ + font-family: arial, sans-serif; +} + +nonsense; + +.clickable +{ + cursor: pointer; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.txt new file mode 100644 index 000000000..07732c929 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/parse-error-with-import.txt @@ -0,0 +1,4 @@ +ParseError: Unrecognised input in {path}parse-error-with-import.less on line 8, column 9: +7 +8 nonsense; +9 diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.less b/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.less new file mode 100644 index 000000000..247f77331 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.less @@ -0,0 +1,3 @@ +.a { + error: calc(1 %); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.txt new file mode 100644 index 000000000..776d8d5d7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/percentage-missing-space.txt @@ -0,0 +1,4 @@ +SyntaxError: Invalid % without number in {path}percentage-missing-space.less on line 2, column 3: +1 .a { +2 error: calc(1 %); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.less new file mode 100644 index 000000000..c6a9990ca --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.less @@ -0,0 +1,3 @@ +a { + * : 1; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.txt new file mode 100644 index 000000000..6adc6c696 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-asterisk-only-name.txt @@ -0,0 +1,4 @@ +ParseError: Unrecognised input in {path}property-asterisk-only-name.less on line 2, column 5: +1 a { +2 * : 1; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.less new file mode 100644 index 000000000..51bf6e397 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.less @@ -0,0 +1,3 @@ +.test { + display/*/: block; /*sorry for IE5*/ +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.txt new file mode 100644 index 000000000..e42ef90eb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-ie5-hack.txt @@ -0,0 +1,4 @@ +ParseError: Unrecognised input in {path}property-ie5-hack.less on line 2, column 3: +1 .test { +2 display/*/: block; /*sorry for IE5*/ +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.less new file mode 100644 index 000000000..8fed4be3b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.less @@ -0,0 +1,4 @@ +.a() { + prop:1; +} +.a(); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.txt new file mode 100644 index 000000000..04b277660 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root.txt @@ -0,0 +1,4 @@ +SyntaxError: properties must be inside selector blocks, they cannot be in the root. in {path}property-in-root.less on line 2, column 3: +1 .a() { +2 prop:1; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.less new file mode 100644 index 000000000..ce8656d17 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.less @@ -0,0 +1 @@ +@import "property-in-root"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.txt new file mode 100644 index 000000000..04b277660 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root2.txt @@ -0,0 +1,4 @@ +SyntaxError: properties must be inside selector blocks, they cannot be in the root. in {path}property-in-root.less on line 2, column 3: +1 .a() { +2 prop:1; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.less new file mode 100644 index 000000000..056c2f72a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.less @@ -0,0 +1,4 @@ +prop:1; +.a { + prop:1; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.txt new file mode 100644 index 000000000..68ef9454d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-in-root3.txt @@ -0,0 +1,3 @@ +SyntaxError: properties must be inside selector blocks, they cannot be in the root. in {path}property-in-root3.less on line 1, column 1: +1 prop:1; +2 .a { diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.less b/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.less new file mode 100644 index 000000000..544fd5f9c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.less @@ -0,0 +1 @@ +a {outline-@{color}: green} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.txt new file mode 100644 index 000000000..dc803564f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/property-interp-not-defined.txt @@ -0,0 +1,2 @@ +NameError: variable @color is undefined in {path}property-interp-not-defined.less on line 1, column 12: +1 a {outline-@{color}: green} diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.less b/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.less new file mode 100644 index 000000000..c1ca75f11 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.less @@ -0,0 +1 @@ +@bodyColor: darken(@bodyColor, 30%); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.txt new file mode 100644 index 000000000..eb616e7d2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/recursive-variable.txt @@ -0,0 +1,2 @@ +NameError: Recursive variable definition for @bodyColor in {path}recursive-variable.less on line 1, column 20: +1 @bodyColor: darken(@bodyColor, 30%); diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.less b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.less new file mode 100644 index 000000000..c069ff724 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.less @@ -0,0 +1,3 @@ +.a { + a: svg-gradient(horizontal, black, white); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.txt new file mode 100644 index 000000000..ec662fe60 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient1.txt @@ -0,0 +1,4 @@ +ArgumentError: error evaluating function `svg-gradient`: svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center' in {path}svg-gradient1.less on line 2, column 6: +1 .a { +2 a: svg-gradient(horizontal, black, white); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.less b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.less new file mode 100644 index 000000000..ff14ef110 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.less @@ -0,0 +1,3 @@ +.a { + a: svg-gradient(to bottom, black, orange, 45%, white); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.txt new file mode 100644 index 000000000..7004115f7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient2.txt @@ -0,0 +1,4 @@ +ArgumentError: error evaluating function `svg-gradient`: svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] in {path}svg-gradient2.less on line 2, column 6: +1 .a { +2 a: svg-gradient(to bottom, black, orange, 45%, white); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.less b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.less new file mode 100644 index 000000000..8f1852460 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.less @@ -0,0 +1,3 @@ +.a { + a: svg-gradient(black, orange); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.txt new file mode 100644 index 000000000..eb0b483e3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/svg-gradient3.txt @@ -0,0 +1,4 @@ +ArgumentError: error evaluating function `svg-gradient`: svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] in {path}svg-gradient3.less on line 2, column 6: +1 .a { +2 a: svg-gradient(black, orange); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.less b/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.less new file mode 100644 index 000000000..119e9818f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.less @@ -0,0 +1,3 @@ +.a { + font-size: unit(80/16,rem); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.txt b/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.txt new file mode 100644 index 000000000..baf90f422 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/errors/unit-function.txt @@ -0,0 +1,4 @@ +ArgumentError: error evaluating function `unit`: the first argument to unit must be a number. Have you forgotten parenthesis? in {path}unit-function.less on line 2, column 14: +1 .a { +2 font-size: unit(80/16,rem); +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-chaining.less b/node_modules/less-middleware/node_modules/less/test/less/extend-chaining.less new file mode 100644 index 000000000..aad221ea6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-chaining.less @@ -0,0 +1,91 @@ +//very simple chaining +.a { + color: black; +} +.b:extend(.a) {} +.c:extend(.b) {} + +//very simple chaining, ordering not important + +.d:extend(.e) {} +.e:extend(.f) {} +.f { + color: black; +} + +//extend with all + +.g.h { + color: black; +} +.i.j:extend(.g all) { + color: white; +} +.k:extend(.i all) {} + +//extend multi-chaining + +.l { + color: black; +} +.m:extend(.l){} +.n:extend(.m){} +.o:extend(.n){} +.p:extend(.o){} +.q:extend(.p){} +.r:extend(.q){} +.s:extend(.r){} +.t:extend(.s){} + +// self referencing is ignored + +.u {color: black;} +.v.u.v:extend(.u all){} + +// circular reference because the new extend product will match the existing extend + +.w:extend(.w) {color: black;} +.v.w.v:extend(.w all){} + +// classic circular references + +.x:extend(.z) { + color: x; +} +.y:extend(.x) { + color: y; +} +.z:extend(.y) { + color: z; +} + +//very simple chaining, but with the extend inside the ruleset +.va { + color: black; +} +.vb { + &:extend(.va); + color: white; +} +.vc { + &:extend(.vb); +} + +// media queries - dont extend outside, do extend inside + +@media tv { + .ma:extend(.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,.md) { + color: black; + } + .md { + color: white; + } + @media plasma { + .me, .mf { + &:extend(.mb,.md); + background: red; + } + } +} +.mb:extend(.ma) {}; +.mc:extend(.mb) {}; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-clearfix.less b/node_modules/less-middleware/node_modules/less/test/less/extend-clearfix.less new file mode 100644 index 000000000..82445dfa5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-clearfix.less @@ -0,0 +1,19 @@ +.clearfix { + *zoom: 1; + &:after { + content: ''; + display: block; + clear: both; + height: 0; + } +} + +.foo { + &:extend(.clearfix all); + color: red; +} + +.bar { + &:extend(.clearfix all); + color: blue; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-exact.less b/node_modules/less-middleware/node_modules/less/test/less/extend-exact.less new file mode 100644 index 000000000..41dc41300 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-exact.less @@ -0,0 +1,46 @@ +.replace.replace, +.c.replace + .replace { + .replace, + .c { + prop: copy-paste-replace; + } +} +.rep_ace:extend(.replace.replace .replace) {} + +.a .b .c { + prop: not_effected; +} + +.a { + prop: is_effected; + .b { + prop: not_effected; + } + .b.c { + prop: not_effected; + } +} + +.c, .a { + .b, .a { + .a, .c { + prop: not_effected; + } + } +} + +.effected { + &:extend(.a); + &:extend(.b); + &:extend(.c); +} + +.e { + && { + prop: extend-double; + &:hover { + hover: not-extended; + } + } +} +.dbl:extend(.e.e) {} diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-media.less b/node_modules/less-middleware/node_modules/less/test/less/extend-media.less new file mode 100644 index 000000000..1b22c3faf --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-media.less @@ -0,0 +1,24 @@ +.ext1 .ext2 { + background: black; +} + +@media tv { + .ext1 .ext3 { + color: white; + } + .tv-lowres :extend(.ext1 all) { + background: blue; + } + @media hires { + .ext1 .ext4 { + color: green; + } + .tv-hires :extend(.ext1 all) { + background: red; + } + } +} + +.all:extend(.ext1 all) { + +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-nest.less b/node_modules/less-middleware/node_modules/less/test/less/extend-nest.less new file mode 100644 index 000000000..9d4d27bbc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-nest.less @@ -0,0 +1,65 @@ +.sidebar { + width: 300px; + background: red; + + .box { + background: #FFF; + border: 1px solid #000; + margin: 10px 0; + } +} + +.sidebar2 { + &:extend(.sidebar all); + background: blue; +} + +.type1 { + .sidebar3 { + &:extend(.sidebar all); + background: green; + } +} + +.type2 { + &.sidebar4 { + &:extend(.sidebar all); + background: red; + } +} + +.button { + color: black; + &:hover { + color: white; + } +} +.submit { + &:extend(.button); + &:hover:extend(.button:hover) {} +} + +.nomatch { + &:hover:extend(.button :hover) {} +} + +.button2 { + :hover { + nested: white; + } +} +.button2 :hover { + notnested: black; +} + +.nomatch :extend(.button2:hover) {} + +.amp-test-a, +.amp-test-b { + .amp-test-c &.amp-test-d&.amp-test-e { + .amp-test-f&+&.amp-test-g:extend(.amp-test-h) {} + } +} +.amp-test-h { + test: extended by masses of selectors; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend-selector.less b/node_modules/less-middleware/node_modules/less/test/less/extend-selector.less new file mode 100644 index 000000000..c7588ee0d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend-selector.less @@ -0,0 +1,99 @@ +.error { + border: 1px #f00; + background: #fdd; +} +.error.intrusion { + font-size: 1.3em; + font-weight: bold; +} +.intrusion .error { + display: none; +} +.badError:extend(.error all) { + border-width: 3px; +} + +.foo .bar, .foo .baz { + display: none; +} + +.ext1 .ext2 + :extend(.foo all) { +} + +.ext3:extend(.foo all), +.ext4:extend(.foo all) { +} + +div.ext5, +.ext6 > .ext5 { + width: 100px; +} + +.should-not-exist-in-output, +.ext7:extend(.ext5 all) { +} + +.ext { + test: 1; +} +// same as +// .a .c:extend(.ext all) +// .b .c:extend(.ext all) +// .a .c .d +// .b .c .d +.a, .b { + test: 2; + .c:extend(.ext all) { + test: 3; + .d { + test: 4; + } + } +} + +.replace.replace, +.c.replace + .replace { + .replace, + .c { + prop: copy-paste-replace; + } +} +.rep_ace:extend(.replace all) {} + +.attributes { + [data="test"] { + extend: attributes; + } + .attribute-test { + &:extend([data="test"] all); + } + [data] { + extend: attributes2; + } + .attribute-test2 { + &:extend([data] all); //you could argue it should match [data="test"]... not for now though... + } + @attr-data: "test3"; + [data=@{attr-data}] { + extend: attributes2; + } + .attribute-test { + &:extend([data="test3"] all); + } +} + +.header { + .header-nav { + background: red; + &:before { + background: blue; + } + } +} + +.footer { + .footer-nav { + &:extend( .header .header-nav all ); + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/extend.less b/node_modules/less-middleware/node_modules/less/test/less/extend.less new file mode 100644 index 000000000..1db5d431d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extend.less @@ -0,0 +1,81 @@ +.error { + border: 1px #f00; + background: #fdd; +} +.error.intrusion { + font-size: 1.3em; + font-weight: bold; +} +.intrusion .error { + display: none; +} +.badError { + &:extend(.error all); + border-width: 3px; +} + +.foo .bar, .foo .baz { + display: none; +} + +.ext1 .ext2 { + &:extend(.foo all); +} + +.ext3, +.ext4 { + &:extend(.foo all); + &:extend(.bar all); +} + +div.ext5, +.ext6 > .ext5 { + width: 100px; +} + +.ext7 { + &:extend(.ext5 all); +} + +.ext8.ext9 { + result: add-foo; +} +.ext8 .ext9, +.ext8 + .ext9, +.ext8 > .ext9 { + result: bar-matched; +} +.ext8.nomatch { + result: none; +} +.ext8 { + .ext9 { + result: match-nested-bar; + } +} +.ext8 { + &.ext9 { + result: match-nested-foo; + } +} + +.fuu:extend(.ext8.ext9 all) {} +.buu:extend(.ext8 .ext9 all) {} +.zap:extend(.ext8 + .ext9 all) {} +.zoo:extend(.ext8 > .ext9 all) {} + +.aa { + color: black; + .dd { + background: red; + } +} +.bb { + background: red; + .bb { + color: black; + } +} +.cc:extend(.aa,.bb) {} +.ee:extend(.dd all,.bb) {} +.ff:extend(.dd,.bb all) {} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/extract-and-length.less b/node_modules/less-middleware/node_modules/less/test/less/extract-and-length.less new file mode 100644 index 000000000..d81e118f5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/extract-and-length.less @@ -0,0 +1,133 @@ + +// simple array/list: + +.multiunit { + @v: abc "abc" 1 1px 1% #123; + length: length(@v); + extract: extract(@v, 1) extract(@v, 2) extract(@v, 3) extract(@v, 4) extract(@v, 5) extract(@v, 6); +} + +.incorrect-index { + @v1: a b c; + @v2: a, b, c; + v1: extract(@v1, 5); + v2: extract(@v2, -2); +} + +.scalar { + @var: variable; + var-value: extract(@var, 1); + var-length: length(@var); + ill-index: extract(@var, 2); + + name-value: extract(name, 1); + string-value: extract("string", 1); + number-value: extract(12345678, 1); + color-value: extract(blue, 1); + rgba-value: extract(rgba(80, 160, 240, 0.67), 1); + empty-value: extract(~'', 1); + + name-length: length(name); + string-length: length("string"); + number-length: length(12345678); + color-length: length(blue); + rgba-length: length(rgba(80, 160, 240, 0.67)); + empty-length: length(~''); +} + +.mixin-arguments { + .mixin-args(a b c d); + .mixin-args(a, b, c, d); + .mixin-args(1; 2; 3; 4); +} + +.mixin-args(@value) { + &-1 { + length: length(@value); + extract: extract(@value, 3) ~"|" extract(@value, 2) ~"|" extract(@value, 1); + } +} + +.mixin-args(...) { + &-2 { + length: length(@arguments); + extract: extract(@arguments, 3) ~"|" extract(@arguments, 2) ~"|" extract(@arguments, 1); + } +} + +.mixin-args(@values...) { + &-3 { + length: length(@values); + extract: extract(@values, 3) ~"|" extract(@values, 2) ~"|" extract(@values, 1); + } +} + +.mixin-args(@head, @tail...) { + &-4 { + length: length(@tail); + extract: extract(@tail, 2) ~"|" extract(@tail, 1); + } +} + +// "multidimensional" array/list + +.md-space-comma { + @v: a b c, 1 2 3, "x" "y" "z"; + length-1: length(@v); + extract-1: extract(@v, 2); + length-2: length(extract(@v, 2)); + extract-2: extract(extract(@v, 2), 2); + + &-as-args {.mixin-args(a b c, 1 2 3, "x" "y" "z")} +} + +.md-cat-space-comma { + @a: a b c; + @b: 1 2 3; + @c: "x" "y" "z"; + @v: @a, @b, @c; + length-1: length(@v); + extract-1: extract(@v, 2); + length-2: length(extract(@v, 2)); + extract-2: extract(extract(@v, 2), 2); + + &-as-args {.mixin-args(@a, @b, @c)} +} + +.md-cat-comma-space { + @a: a, b, c; + @b: 1, 2, 3; + @c: "x", "y", "z"; + @v: @a @b @c; + length-1: length(@v); + extract-1: extract(@v, 2); + length-2: length(extract(@v, 2)); + extract-2: extract(extract(@v, 2), 2); + + &-as-args {.mixin-args(@a @b @c)} +} + +.md-3D { + @a: a b c d, 1 2 3 4; + @b: 5 6 7 8, e f g h; + .3D(@a, @b); + + .3D(...) { + + @v1: @arguments; + length-1: length(@v1); + extract-1: extract(@v1, 1); + + @v2: extract(@v1, 2); + length-2: length(@v2); + extract-2: extract(@v2, 1); + + @v3: extract(@v2, 1); + length-3: length(@v3); + extract-3: extract(@v3, 3); + + @v4: extract(@v3, 4); + length-4: length(@v4); + extract-4: extract(@v4, 1); + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/functions.less b/node_modules/less-middleware/node_modules/less/test/less/functions.less new file mode 100644 index 000000000..4b4720d99 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/functions.less @@ -0,0 +1,173 @@ +#functions { + @var: 10; + @colors: #000, #fff; + color: _color("evil red"); // #660000 + width: increment(15); + height: undefined("self"); + border-width: add(2, 3); + variable: increment(@var); + background: linear-gradient(@colors); +} + +#built-in { + @r: 32; + escaped: e("-Some::weird(#thing, y)"); + lighten: lighten(#ff0000, 40%); + darken: darken(#ff0000, 40%); + saturate: saturate(#29332f, 20%); + desaturate: desaturate(#203c31, 20%); + greyscale: greyscale(#203c31); + hsl-clamp: hsl(380, 150%, 150%); + spin-p: spin(hsl(340, 50%, 50%), 40); + spin-n: spin(hsl(30, 50%, 50%), -40); + luma-white: luma(#fff); + luma-black: luma(#000); + luma-black-alpha: luma(rgba(0,0,0,0.5)); + luma-red: luma(#ff0000); + luma-green: luma(#00ff00); + luma-blue: luma(#0000ff); + luma-yellow: luma(#ffff00); + luma-cyan: luma(#00ffff); + luma-differs-from-luminance: luma(#ff3600); + luminance-white: luma(#fff); + luminance-black: luma(#000); + luminance-black-alpha: luma(rgba(0,0,0,0.5)); + luminance-red: luma(#ff0000); + luminance-differs-from-luma: luminance(#ff3600); + contrast-filter: contrast(30%); + saturate-filter: saturate(5%); + contrast-white: contrast(#fff); + contrast-black: contrast(#000); + contrast-red: contrast(#ff0000); + contrast-green: contrast(#00ff00); + contrast-blue: contrast(#0000ff); + contrast-yellow: contrast(#ffff00); + contrast-cyan: contrast(#00ffff); + contrast-light: contrast(#fff, #111111, #eeeeee); + contrast-dark: contrast(#000, #111111, #eeeeee); + contrast-wrongorder: contrast(#fff, #eeeeee, #111111, 0.5); + contrast-light-thresh: contrast(#fff, #111111, #eeeeee, 0.5); + contrast-dark-thresh: contrast(#000, #111111, #eeeeee, 0.5); + contrast-high-thresh: contrast(#555, #111111, #eeeeee, 0.6); + contrast-low-thresh: contrast(#555, #111111, #eeeeee, 0.09); + contrast-light-thresh-per: contrast(#fff, #111111, #eeeeee, 50%); + contrast-dark-thresh-per: contrast(#000, #111111, #eeeeee, 50%); + contrast-high-thresh-per: contrast(#555, #111111, #eeeeee, 60%); + contrast-low-thresh-per: contrast(#555, #111111, #eeeeee, 9%); + replace: replace("Hello, Mars.", "Mars\.", "World!"); + replace-captured: replace("This is a string.", "(string)\.$", "new $1."); + replace-with-flags: replace("One + one = 4", "one", "2", "gi"); + replace-single-quoted: replace('foo-1', "1", "2"); + replace-escaped-string: replace(~"bar-1", "1", "2"); + replace-keyword: replace(baz-1, "1", "2"); + format: %("rgb(%d, %d, %d)", @r, 128, 64); + format-string: %("hello %s", "world"); + format-multiple: %("hello %s %d", "earth", 2); + format-url-encode: %("red is %A", #ff0000); + format-single-quoted: %('hello %s', "single world"); + format-escaped-string: %(~"hello %s", "escaped world"); + eformat: e(%("rgb(%d, %d, %d)", @r, 128, 64)); + + unitless: unit(12px); + unit: unit((13px + 1px), em); + unitpercentage: unit(100, %); + + get-unit: get-unit(10px); + get-unit-empty: get-unit(10); + + hue: hue(hsl(98, 12%, 95%)); + saturation: saturation(hsl(98, 12%, 95%)); + lightness: lightness(hsl(98, 12%, 95%)); + hsvhue: hsvhue(hsv(98, 12%, 95%)); + hsvsaturation: hsvsaturation(hsv(98, 12%, 95%)); + hsvvalue: hsvvalue(hsv(98, 12%, 95%)); + red: red(#f00); + green: green(#0f0); + blue: blue(#00f); + rounded: round((@r/3)); + rounded-two: round((@r/3), 2); + roundedpx: round((10px / 3)); + roundedpx-three: round((10px / 3), 3); + rounded-percentage: round(10.2%); + ceil: ceil(10.1px); + floor: floor(12.9px); + sqrt: sqrt(25px); + pi: pi(); + mod: mod(13m, 11cm); // could take into account units, doesn't at the moment + abs: abs(-4%); + tan: tan(42deg); + sin: sin(10deg); + cos: cos(12); + atan: atan(tan(0.1rad)); + atan: convert(acos(cos(34deg)), deg); + atan: convert(acos(cos(50grad)), deg); + pow: pow(8px, 2); + pow: pow(4, 3); + pow: pow(3, 3em); + min: min(0); + min: min(6, 5); + min: min(1pt, 3pt); + min: min(1cm, 3mm); + max: max(1, 3); + max: max(3em, 1em, 2em, 5em); + percentage: percentage((10px / 50)); + color: color("#ff0011"); + tint: tint(#777777, 13); + tint-full: tint(#777777, 100); + tint-percent: tint(#777777, 13%); + tint-negative: tint(#777777, -13%); + shade: shade(#777777, 13); + shade-full: shade(#777777, 100); + shade-percent: shade(#777777, 13%); + shade-negative: shade(#777777, -13%); + + fade-out: fadeOut(red, 5%); // support fadeOut and fadeout + fade-in: fadein(fadeout(red, 10%), 5%); + + hsv: hsv(5, 50%, 30%); + hsva: hsva(3, 50%, 30%, 0.2); + + mix: mix(#ff0000, #ffff00, 80); + mix-0: mix(#ff0000, #ffff00, 0); + mix-100: mix(#ff0000, #ffff00, 100); + mix-weightless: mix(#ff0000, #ffff00); + mixt: mix(#ff0000, transparent); + + .is-a { + color: iscolor(#ddd); + color1: iscolor(red); + color2: iscolor(rgb(0, 0, 0)); + color3: iscolor(transparent); + keyword: iskeyword(hello); + number: isnumber(32); + string: isstring("hello"); + pixel: ispixel(32px); + percent: ispercentage(32%); + em: isem(32em); + cat: isunit(32cat, cat); + } +} + +#alpha { + alpha: darken(hsla(25, 50%, 50%, 0.6), 10%); + alpha2: alpha(rgba(3, 4, 5, 0.5)); + alpha3: alpha(transparent); +} + +#blendmodes { + multiply: multiply(#f60000, #f60000); + screen: screen(#f60000, #0000f6); + overlay: overlay(#f60000, #0000f6); + softlight: softlight(#f60000, #ffffff); + hardlight: hardlight(#f60000, #0000f6); + difference: difference(#f60000, #0000f6); + exclusion: exclusion(#f60000, #0000f6); + average: average(#f60000, #0000f6); + negation: negation(#f60000, #313131); +} + +#extract-and-length { + @anon: A B C 1 2 3; + extract: extract(@anon, 6) extract(@anon, 5) extract(@anon, 4) extract(@anon, 3) extract(@anon, 2) extract(@anon, 1); + length: length(@anon); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.json b/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.json new file mode 100644 index 000000000..6bd2a4845 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.json @@ -0,0 +1,5 @@ +{ + "the-border": "1px", + "base-color": "#111", + "red": "#842210" +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.less b/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.less new file mode 100644 index 000000000..7a3bf2911 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/globalVars/extended.less @@ -0,0 +1,10 @@ +#header { + color: (@base-color * 3); + border-left: @the-border; + border-right: (@the-border * 2); +} +#footer { + color: (@base-color + #003300); + border-color: @red; +} +@red: desaturate(red, 10%); // less file overrides passed in color <- note line comment on last line to check it is okay \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.json b/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.json new file mode 100644 index 000000000..76a63c5a4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.json @@ -0,0 +1,3 @@ +{ + "my-color": "red" +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.less b/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.less new file mode 100644 index 000000000..c3c5e3b83 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/globalVars/simple.less @@ -0,0 +1,3 @@ +.class { + color: @my-color; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/ie-filters.less b/node_modules/less-middleware/node_modules/less/test/less/ie-filters.less new file mode 100644 index 000000000..3350b6536 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/ie-filters.less @@ -0,0 +1,15 @@ +@fat: 0; +@cloudhead: "#000000"; + +.nav { + filter: progid:DXImageTransform.Microsoft.Alpha(opacity = 20); + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=@fat); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#333333", endColorstr=@cloudhead, GradientType=@fat); +} +.evalTest(@arg) { + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=@arg); +} +.evalTest1 { + .evalTest(30); + .evalTest(5); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import-inline.less b/node_modules/less-middleware/node_modules/less/test/less/import-inline.less new file mode 100644 index 000000000..213a57499 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import-inline.less @@ -0,0 +1,3 @@ +@import url("import/import-test-c.less");// import inline should not float above this #1954 +@import (inline) url("import/import-test-d.css") (min-width:600px); +@import (inline, css) url("import/invalid-css.less"); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import-interpolation.less b/node_modules/less-middleware/node_modules/less/test/less/import-interpolation.less new file mode 100644 index 000000000..21cfe086f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import-interpolation.less @@ -0,0 +1,8 @@ +@my_theme: "test"; + +@import "import/import-@{my_theme}-e.less"; + +@import "import/import-@{in}@{terpolation}.less"; + +@in: "in"; +@terpolation: "terpolation"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import-once.less b/node_modules/less-middleware/node_modules/less/test/less/import-once.less new file mode 100644 index 000000000..0a4024a38 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import-once.less @@ -0,0 +1,6 @@ +@import "import/import-once-test-c"; +@import "import/import-once-test-c"; +@import "import/import-once-test-c.less"; +@import "import/deeper/import-once-test-a"; +@import (multiple) "import/import-test-f.less"; +@import (multiple) "import/import-test-f.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import-reference.less b/node_modules/less-middleware/node_modules/less/test/less/import-reference.less new file mode 100644 index 000000000..93160ab5d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import-reference.less @@ -0,0 +1,21 @@ +@import (reference) url("import-once.less"); +@import (reference) url("css-3.less"); +@import (reference) url("media.less"); +@import (reference) url("import/import-reference.less"); + +.b { + .z(); +} + +.zz(); + +.visible:extend(.z all) { + extend: test; +} + +.test-mediaq-import { + .mixin-with-mediaq(340px); +} + +.class:extend(.class all) { +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import.less b/node_modules/less-middleware/node_modules/less/test/less/import.less new file mode 100644 index 000000000..9f8b2914f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import.less @@ -0,0 +1,28 @@ +@import url(http://fonts.googleapis.com/css?family=Open+Sans); + +@import url(/absolute/something.css) screen and (color) and (max-width: 600px); + +@var: 100px; +@import url("//ha.com/file.css") (min-width:@var); + +#import-test { + .mixin; + width: 10px; + height: (@a + 10%); +} +@import "import/import-test-e" screen and (max-width: 600px); + +@import url("import/import-test-a.less"); + +@import (less, multiple) "import/import-test-d.css" screen and (max-width: 601px); + +@import (multiple) "import/import-test-e" screen and (max-width: 602px); + +@import (less, multiple) url("import/import-test-d.css") screen and (max-width: 603px); + +@media print { + @import (multiple) "import/import-test-e"; +} + +@charset "UTF-8"; // climb on top #2126 + diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/deeper/import-once-test-a.less b/node_modules/less-middleware/node_modules/less/test/less/import/deeper/import-once-test-a.less new file mode 100644 index 000000000..8a747fc0a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/deeper/import-once-test-a.less @@ -0,0 +1 @@ +@import "../import-once-test-c"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-and-relative-paths-test.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-and-relative-paths-test.less new file mode 100644 index 000000000..d6256c6b8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-and-relative-paths-test.less @@ -0,0 +1,17 @@ +@import "../css/background.css"; +@import "import-test-d.css"; + +@import "imports/logo"; +@import "imports/font"; + +.unquoted-relative-path-bg() { + background-image: url(../../data/image.jpg); +} +.quoted-relative-path-border-image() { + border-image: url('../../data/image.jpg'); +} + +#imported-relative-path { + .unquoted-relative-path-bg; + .quoted-relative-path-border-image; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-charset-test.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-charset-test.less new file mode 100644 index 000000000..07a66e1a1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-charset-test.less @@ -0,0 +1 @@ +@charset "ISO-8859-1"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation.less new file mode 100644 index 000000000..aa49a7025 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation.less @@ -0,0 +1 @@ +@import "import-@{in}@{terpolation}2.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation2.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation2.less new file mode 100644 index 000000000..12bfb4e10 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-interpolation2.less @@ -0,0 +1,5 @@ +.a { + var: test; +} + +@in: "redefined-does-nothing"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-once-test-c.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-once-test-c.less new file mode 100644 index 000000000..686747a86 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-once-test-c.less @@ -0,0 +1,6 @@ + +@c: red; + +#import { + color: @c; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-reference.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-reference.less new file mode 100644 index 000000000..c77f692e7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-reference.less @@ -0,0 +1,51 @@ +.z { + color: red; + .c { + color: green; + } +} +.only-with-visible, +.z { + color: green; + &:hover { + color: green; + } + & { + color: green; + } + & + & { + color: green; + .sub { + color: green; + } + } +} + +& { + .hidden { + hidden: true; + } +} + +@media tv { + .hidden { + hidden: true; + } +} + +/* comment is not output */ + +.zz { + .y { + pulled-in: yes; + } + /* comment pulled in */ +} +@max-size: 450px; +.mixin-with-mediaq(@num) { + color: green; + test: @num; + @media (max-size: @max-size) { + color: red; + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-a.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-a.less new file mode 100644 index 000000000..b3b3b8fc8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-a.less @@ -0,0 +1,3 @@ +@import "import-test-b.less"; +@a: 20%; +@import "urls.less"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-b.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-b.less new file mode 100644 index 000000000..ce2d35a83 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-b.less @@ -0,0 +1,8 @@ +@import "import-test-c"; + +@b: 100%; + +.mixin { + height: 10px; + color: @c; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-c.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-c.less new file mode 100644 index 000000000..686747a86 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-c.less @@ -0,0 +1,6 @@ + +@c: red; + +#import { + color: @c; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-d.css b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-d.css new file mode 100644 index 000000000..30575f018 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-d.css @@ -0,0 +1 @@ +#css { color: yellow; } diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-e.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-e.less new file mode 100644 index 000000000..98b84b0a5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-e.less @@ -0,0 +1,2 @@ + +body { width: 100% } diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/import-test-f.less b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-f.less new file mode 100644 index 000000000..fad630f9c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/import-test-f.less @@ -0,0 +1,5 @@ +@import "import-test-e"; + +.test-f { + height: 10px; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/imports/font.less b/node_modules/less-middleware/node_modules/less/test/less/import/imports/font.less new file mode 100644 index 000000000..5abb7e769 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/imports/font.less @@ -0,0 +1,8 @@ +@font-face { + font-family: xecret; + src: url('../assets/xecret.ttf'); +} + +#secret { + font-family: xecret, sans-serif; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/imports/logo.less b/node_modules/less-middleware/node_modules/less/test/less/import/imports/logo.less new file mode 100644 index 000000000..22893a238 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/imports/logo.less @@ -0,0 +1,5 @@ +#logo { + width: 100px; + height: 100px; + background: url('../assets/logo.png'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/invalid-css.less b/node_modules/less-middleware/node_modules/less/test/less/import/invalid-css.less new file mode 100644 index 000000000..ed585d638 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/invalid-css.less @@ -0,0 +1 @@ +this isn't very valid CSS. \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/import/urls.less b/node_modules/less-middleware/node_modules/less/test/less/import/urls.less new file mode 100644 index 000000000..bb48f77a2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/import/urls.less @@ -0,0 +1 @@ +// empty file showing that it loads from the relative path first diff --git a/node_modules/less-middleware/node_modules/less/test/less/javascript.less b/node_modules/less-middleware/node_modules/less/test/less/javascript.less new file mode 100644 index 000000000..a8e7eb37f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/javascript.less @@ -0,0 +1,38 @@ +.eval { + js: `42`; + js: `1 + 1`; + js: `"hello world"`; + js: `[1, 2, 3]`; + title: `typeof process.title`; + ternary: `(1 + 1 == 2 ? true : false)`; + multiline: `(function(){var x = 1 + 1; + return x})()`; +} +.scope { + @foo: 42; + var: `parseInt(this.foo.toJS())`; + escaped: ~`2 + 5 + 'px'`; +} +.vars { + @var: `4 + 4`; + width: @var; +} +.escape-interpol { + @world: "world"; + width: ~`"hello" + " " + @{world}`; +} +.arrays { + @ary: 1, 2, 3; + @ary2: 1 2 3; + ary: `@{ary}.join(', ')`; + ary1: `@{ary2}.join(', ')`; +} +.transitions(...) { + @arg: ~`"@{arguments}".replace(/[\[\]]*/g, '')`; + 1: @arg; // rounded to integers + 2: ~`"@{arguments}"`; // rounded to integers + 3: @arguments; // OK +} +.test-tran { + .transitions(opacity 0.3s ease-in 0.3s, max-height 0.6s linear, margin-bottom 0.4s linear;); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/lazy-eval.less b/node_modules/less-middleware/node_modules/less/test/less/lazy-eval.less new file mode 100644 index 000000000..72b3fd46e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/lazy-eval.less @@ -0,0 +1,6 @@ +@var: @a; +@a: 100%; + +.lazy-eval { + width: @var; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/legacy/legacy.less b/node_modules/less-middleware/node_modules/less/test/less/legacy/legacy.less new file mode 100644 index 000000000..92d000889 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/legacy/legacy.less @@ -0,0 +1,7 @@ +@media (-o-min-device-pixel-ratio: 2/1) { + .test-math-and-units { + font: ignores 0/0 rules; + test-division: 4 / 2 + 5em; + simple: 1px + 1px; + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/media.less b/node_modules/less-middleware/node_modules/less/test/less/media.less new file mode 100644 index 000000000..01a6a0209 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/media.less @@ -0,0 +1,234 @@ + +// For now, variables can't be declared inside @media blocks. + +@var: 42; + +@media print { + .class { + color: blue; + .sub { + width: @var; + } + } + .top, header > h1 { + color: (#222 * 2); + } +} + +@media screen { + @base: 8; + body { max-width: (@base * 60); } +} + +@ratio_large: 16; +@ratio_small: 9; + +@media all and (device-aspect-ratio: @ratio_large / @ratio_small) { + body { max-width: 800px; } +} + +@media all and (orientation:portrait) { + aside { float: none; } +} + +@media handheld and (min-width: @var), screen and (min-width: 20em) { + body { + max-width: 480px; + } +} + +body { + @media print { + padding: 20px; + + header { + background-color: red; + } + + @media (orientation:landscape) { + margin-left: 20px; + } + } +} + +@media screen { + .sidebar { + width: 300px; + @media (orientation: landscape) { + width: 500px; + } + } +} + +@media a { + .first { + @media b { + .second { + .third { + width: 300px; + @media c { + width: 500px; + } + } + .fourth { + width: 3; + } + } + } + } +} + +body { + @media a, b and c { + width: 95%; + + @media x, y { + width: 100%; + } + } +} + +.mediaMixin(@fallback: 200px) { + background: black; + + @media handheld { + background: white; + + @media (max-width: @fallback) { + background: red; + } + } +} + +.a { + .mediaMixin(100px); +} + +.b { + .mediaMixin(); +} +@smartphone: ~"only screen and (max-width: 200px)"; +@media @smartphone { + body { + width: 480px; + } +} + +@media print { + @page :left { + margin: 0.5cm; + } + @page :right { + margin: 0.5cm; + } + @page Test:first { + margin: 1cm; + } + @page :first { + size: 8.5in 11in; + @top-left { + margin: 1cm; + } + @top-left-corner { + margin: 1cm; + } + @top-center { + margin: 1cm; + } + @top-right { + margin: 1cm; + } + @top-right-corner { + margin: 1cm; + } + @bottom-left { + margin: 1cm; + } + @bottom-left-corner { + margin: 1cm; + } + @bottom-center { + margin: 1cm; + } + @bottom-right { + margin: 1cm; + } + @bottom-right-corner { + margin: 1cm; + } + @left-top { + margin: 1cm; + } + @left-middle { + margin: 1cm; + } + @left-bottom { + margin: 1cm; + } + @right-top { + margin: 1cm; + } + @right-middle { + content: "Page " counter(page); + } + @right-bottom { + margin: 1cm; + } + } +} + +@media (-webkit-min-device-pixel-ratio: 2), (min--moz-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (min-resolution: 2dppx), (min-resolution: 128dpcm) { + .b { + background: red; + } +} + +.bg() { + background: red; + + @media (max-width: 500px) { + background: green; + } +} + +body { + .bg(); +} + +@bpMedium: 1000px; +@media (max-width: @bpMedium) { + body { + .bg(); + background: blue; + } +} + +@media (max-width: 1200px) { + /* a comment */ + + @media (max-width: 900px) { + body { font-size: 11px; } + } +} + +.nav-justified { + @media (min-width: 480px) { + > li { + display: table-cell; + } + } +} + +.menu +{ + @media (min-width: 768px) { + .nav-justified(); + } +} +@all: ~"all"; +@tv: ~"tv"; +@media @all and @tv { + .all-and-tv-variables { + var: all-and-tv; + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/merge.less b/node_modules/less-middleware/node_modules/less/test/less/merge.less new file mode 100644 index 000000000..5b5def35b --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/merge.less @@ -0,0 +1,78 @@ +.first-transform() { + transform+: rotate(90deg), skew(30deg); +} +.second-transform() { + transform+: scale(2,4); +} +.third-transform() { + transform: scaleX(45deg); +} +.fourth-transform() { + transform+: scaleX(45deg); +} +.fifth-transform() { + transform+: scale(2,4) !important; +} +.first-background() { + background+: url(data://img1.png); +} +.second-background() { + background+: url(data://img2.png); +} + +.test1 { + // Can merge values + .first-transform(); + .second-transform(); +} +.test2 { + // Wont merge values without +: merge directive, for backwards compatibility with css + .first-transform(); + .third-transform(); +} +.test3 { + // Wont merge values from two sources with different properties + .fourth-transform(); + .first-background(); +} +.test4 { + // Wont merge values from sources that merked as !important, for backwards compatibility with css + .first-transform(); + .fifth-transform(); +} +.test5 { + // Wont merge values from mixins that merked as !important, for backwards compatibility with css + .first-transform(); + .second-transform() !important; +} +.test6 { + // Ignores !merge if no peers found + .second-transform(); +} + +.test-interleaved { + transform+: t1; + background+: b1; + transform+: t2; + background+: b2, b3; + transform+: t3; +} + +.test-spaced { + transform+_: t1; + background+_: b1; + transform+_: t2; + background+_: b2, b3; + transform+_: t3; +} + +.test-interleaved-with-spaced { + transform+_: t1s; + transform+: t2; + background+: b1; + transform+_: t3s; + transform+: t4 t5s; + background+_: b2s, b3; + transform+_: t6s; + background+: b4; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-args.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-args.less new file mode 100644 index 000000000..8cdc67df1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-args.less @@ -0,0 +1,215 @@ +.mixin (@a: 1px, @b: 50%) { + width: (@a * 5); + height: (@b - 1%); +} + +.mixina (@style, @width, @color: black) { + border: @width @style @color; +} + +.mixiny +(@a: 0, @b: 0) { + margin: @a; + padding: @b; +} + +.hidden() { + color: transparent; // asd +} + +#hidden { + .hidden; +} + +#hidden1 { + .hidden(); +} + +.two-args { + color: blue; + .mixin(2px, 100%); + .mixina(dotted, 2px); +} + +.one-arg { + .mixin(3px); +} + +.no-parens { + .mixin; +} + +.no-args { + .mixin(); +} + +.var-args { + @var: 9; + .mixin(@var, (@var * 2)); +} + +.multi-mix { + .mixin(2px, 30%); + .mixiny(4, 5); +} + +.maxa(@arg1: 10, @arg2: #f00) { + padding: (@arg1 * 2px); + color: @arg2; +} + +body { + .maxa(15); +} + +@glob: 5; +.global-mixin(@a:2) { + width: (@glob + @a); +} + +.scope-mix { + .global-mixin(3); +} + +.nested-ruleset (@width: 200px) { + width: @width; + .column { margin: @width; } +} +.content { + .nested-ruleset(600px); +} + +// + +.same-var-name2(@radius) { + radius: @radius; +} +.same-var-name(@radius) { + .same-var-name2(@radius); +} +#same-var-name { + .same-var-name(5px); +} + +// + +.var-inside () { + @var: 10px; + width: @var; +} +#var-inside { .var-inside; } + +.mixin-arguments (@width: 0px, ...) { + border: @arguments; + width: @width; +} + +.arguments { + .mixin-arguments(1px, solid, black); +} +.arguments2 { + .mixin-arguments(); +} +.arguments3 { + .mixin-arguments; +} + +.mixin-arguments2 (@width, @rest...) { + border: @arguments; + rest: @rest; + width: @width; +} +.arguments4 { + .mixin-arguments2(0, 1, 2, 3, 4); +} + +// Edge cases + +.edge-case { + .mixin-arguments("{"); +} + +// Division vs. Literal Slash +.border-radius(@r: 2px/5px) { + border-radius: @r; +} +.slash-vs-math { + .border-radius(); + .border-radius(5px/10px); + .border-radius((3px * 2)); +} +// semi-colon vs comma for delimiting + +.mixin-takes-one(@a) { + one: @a; +} + +.mixin-takes-two(@a; @b) { + one: @a; + two: @b; +} + +.comma-vs-semi-colon { + .mixin-takes-two(@a : a; @b : b, c); + .mixin-takes-two(@a : d, e; @b : f); + .mixin-takes-one(@a: g); + .mixin-takes-one(@a : h;); + .mixin-takes-one(i); + .mixin-takes-one(j;); + .mixin-takes-two(k, l); + .mixin-takes-one(m, n;); + .mixin-takes-two(o, p; q); + .mixin-takes-two(r, s; t;); +} + +.mixin-conflict(@a:defA, @b:defB, @c:defC) { + three: @a, @b, @c; +} + +.mixin-conflict(@a:defA, @b:defB, @c:defC, @d:defD) { + four: @a, @b, @c, @d; +} + +#named-conflict { + .mixin-conflict(11, 12, 13, @a:a); + .mixin-conflict(@a:a, 21, 22, 23); +} +@a: 3px; +.mixin-default-arg(@a: 1px, @b: @a, @c: @b) { + defaults: 1px 1px 1px; + defaults: 2px 2px 2px; +} + +.test-mixin-default-arg { + .mixin-default-arg(); + .mixin-default-arg(2px); +} + +.mixin-comma-default1(@color; @padding; @margin: 2, 2, 2, 2) { + margin: @margin; +} +.selector { + .mixin-comma-default1(#33acfe; 4); +} +.mixin-comma-default2(@margin: 2, 2, 2, 2;) { + margin: @margin; +} +.selector2 { + .mixin-comma-default2(); +} +.mixin-comma-default3(@margin: 2, 2, 2, 2) { + margin: @margin; +} +.selector3 { + .mixin-comma-default3(4,2,2,2); +} + +.test-calling-one-arg-mixin(@a) { +} + +.test-calling-one-arg-mixin(@a, @b, @rest...) { +} + +div { + .test-calling-one-arg-mixin(1); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-closure.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-closure.less new file mode 100644 index 000000000..01251d2ad --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-closure.less @@ -0,0 +1,26 @@ +.scope { + @var: 99px; + .mixin () { + width: @var; + } +} + +.class { + .scope > .mixin; +} + +.overwrite { + @var: 0px; + .scope > .mixin; +} + +.nested { + @var: 5px; + .mixin () { + width: @var; + } + .class { + @var: 10px; + .mixin; + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-guards-default-func.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-guards-default-func.less new file mode 100644 index 000000000..eada93814 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-guards-default-func.less @@ -0,0 +1,195 @@ + +// basics: + +guard-default-basic-1 { + .m(1) {case: 1} + .m(@x) when (default()) {default: @x} + + &-1 {.m(1)} + &-2 {.m(2)} +} + +guard-default-basic-2 { + .m(1) {case: 1} + .m(2) {case: 2} + .m(3) {case: 3} + .m(@x) when (default()) {default: @x} + + &-0 {.m(0)} + &-2 {.m(2)} +} + +guard-default-basic-3 { + .m(@x) when (@x = 1) {case: 1} + .m(2) {case: 2} + .m(@x) when (@x = 3) {case: 3} + .m(@x) when (default()) {default: @x} + + &-0 {.m(0)} + &-2 {.m(2)} + &-3 {.m(3)} +} + +guard-default-definition-order { + .m(@x) when (default()) {default: @x} + .m(@x) when (@x = 1) {case: 1} + .m(2) {case: 2} + .m(@x) when (@x = 3) {case: 3} + + &-0 {.m(0)} + &-2 {.m(2)} + &-2 {.m(3)} +} + +// out of guard: + +guard-default-out-of-guard { + .m(1) {case-1: 1} + .m(@x: default()) when (default()) {default: @x} + + &-0 { + case-0: default(); + .m(1); + .m(2); + case-2: default(); + } + &-1 {.m(default())} + &-2 {.m()} +} + +// expressions: + +guard-default-expr-not { + .m(1) {case: 1} + .m(@x) when not(default()) {default: @x} + + &-1 {.m(1)} + &-2 {.m(2)} +} + +guard-default-expr-eq { + .m(@x) when (@x = true) {case: @x} + .m(@x) when (@x = false) {case: @x} + .m(@x) when (@x = default()) {default: @x} + + &-true {.m(true)} + &-false {.m(false)} +} + +guard-default-expr-or { + .m(1) {case: 1} + .m(2) {case: 2} + .m(@x) when (default()), (@x = 2) {default: @x} + + &-1 {.m(1)} + &-2 {.m(2)} + &-3 {.m(3)} +} + +guard-default-expr-and { + .m(1) {case: 1} + .m(2) {case: 2} + .m(@x) when (default()) and (@x = 3) {default: @x} + + &-1 {.m(1)} + &-2 {.m(2)} + &-3 {.m(3)} + &-4 {.m(4)} +} + +guard-default-expr-always { + .m(1) {case: 1} + .m(@x) when (default()), not(default()) {default: @x} // always match + + &-1 {.m(1)} + &-2 {.m(2)} +} + +guard-default-expr-never { + .m(1) {case: 1} + .m(@x) when (default()) and not(default()) {default: @x} // never match + + &-1 {.m(1)} + &-2 {.m(2)} +} + + +// not conflicting multiple default() uses: + +guard-default-multi-1 { + .m(0) {case: 0} + .m(@x) when (default()) {default-1: @x} + .m(2) when (default()) {default-2: @x} + + &-0 {.m(0)} + &-1 {.m(1)} +} + +guard-default-multi-2 { + .m(1, @x) when (default()) {default-1: @x} + .m(2, @x) when (default()) {default-2: @x} + .m(@x, yes) when (default()) {default-3: @x} + + &-1 {.m(1, no)} + &-2 {.m(2, no)} + &-3 {.m(3, yes)} +} + +guard-default-multi-3 { + .m(red) {case-1: darkred} + .m(blue) {case-2: darkblue} + .m(@x) when (iscolor(@x)) and (default()) {default-color: @x} + .m('foo') {case-1: I am 'foo'} + .m('bar') {case-2: I am 'bar'} + .m(@x) when (isstring(@x)) and (default()) {default-string: I am @x} + + &-blue {.m(blue)} + &-green {.m(green)} + &-foo {.m('foo')} + &-baz {.m('baz')} +} + +guard-default-multi-4 { + .m(@x) when (default()), not(default()) {always: @x} + .m(@x) when (default()) and not(default()) {never: @x} + .m(2) {case: 2} + + .m(1); + .m(2); +} + +guard-default-not-ambiguos-2 { + .m(@x) {case: 1} + .m(@x) when (default()) {default: @x} + .m(@x) when not(default()) {not-default: @x} + + .m(2); +} + +guard-default-not-ambiguos-3 { + .m(@x) {case: 1} + .m(@x) when not(default()) {not-default-1: @x} + .m(@x) when not(default()) {not-default-2: @x} + + .m(2); +} + +// default & scope + +guard-default-scopes { + .s1() {.m(@v) {1: no condition}} + .s2() {.m(@v) when (@v) {2: when true}} + .s3() {.m(@v) when (default()) {3: when default}} + + &-3 { + .s2(); + .s3(); + .m(false); + } + + &-1 { + .s1(); + .s3(); + .m(false); + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-guards.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-guards.less new file mode 100644 index 000000000..5aec2e51c --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-guards.less @@ -0,0 +1,173 @@ + +// Stacking, functions.. + +.light (@a) when (lightness(@a) > 50%) { + color: white; +} +.light (@a) when (lightness(@a) < 50%) { + color: black; +} +.light (@a) { + margin: 1px; +} + +.light1 { .light(#ddd) } +.light2 { .light(#444) } + +// Arguments against each other + +.max (@a, @b) when (@a > @b) { + width: @a; +} +.max (@a, @b) when (@a < @b) { + width: @b; +} + +.max1 { .max(3, 6) } +.max2 { .max(8, 1) } + +// Globals inside guards + +@g: auto; + +.glob (@a) when (@a = @g) { + margin: @a @g; +} +.glob1 { .glob(auto) } + +// Other operators + +.ops (@a) when (@a >= 0) { + height: gt-or-eq; +} +.ops (@a) when (@a =< 0) { + height: lt-or-eq; +} +.ops (@a) when (@a <= 0) { + height: lt-or-eq-alias; +} +.ops (@a) when not(@a = 0) { + height: not-eq; +} +.ops1 { .ops(0) } +.ops2 { .ops(1) } +.ops3 { .ops(-1) } + +// Scope and default values + +@a: auto; + +.default (@a: inherit) when (@a = inherit) { + content: default; +} +.default1 { .default } + +// true & false keywords +.test (@a) when (@a) { + content: "true."; +} +.test (@a) when not (@a) { + content: "false."; +} + +.test1 { .test(true) } +.test2 { .test(false) } +.test3 { .test(1) } +.test4 { .test(boo) } +.test5 { .test("true") } + +// Boolean expressions + +.bool () when (true) and (false) { content: true and false } // FALSE +.bool () when (true) and (true) { content: true and true } // TRUE +.bool () when (true) { content: true } // TRUE +.bool () when (false) and (false) { content: true } // FALSE +.bool () when (false), (true) { content: false, true } // TRUE +.bool () when (false) and (true) and (true), (true) { content: false and true and true, true } // TRUE +.bool () when (true) and (true) and (false), (false) { content: true and true and false, false } // FALSE +.bool () when (false), (true) and (true) { content: false, true and true } // TRUE +.bool () when (false), (false), (true) { content: false, false, true } // TRUE +.bool () when (false), (false) and (true), (false) { content: false, false and true, false } // FALSE +.bool () when (false), (true) and (true) and (true), (false) { content: false, true and true and true, false } // TRUE +.bool () when not (false) { content: not false } +.bool () when not (true) and not (false) { content: not true and not false } +.bool () when not (true) and not (true) { content: not true and not true } +.bool () when not (false) and (false), not (false) { content: not false and false, not false } + +.bool1 { .bool } + +.equality-unit-test(@num) when (@num = 1%) { + test: fail; +} +.equality-unit-test(@num) when (@num = 2) { + test: pass; +} +.equality-units { + .equality-unit-test(1px); + .equality-unit-test(2px); +} + +.colorguard(@col) when (@col = red) { content: is @col; } +.colorguard(@col) when not (blue = @col) { content: is not blue its @col; } +.colorguard(@col) {} +.colorguardtest { + .colorguard(red); + .colorguard(blue); + .colorguard(purple); +} + +.stringguard(@str) when (@str = "theme1") { content: @str is "theme1"; } +.stringguard(@str) when not ("theme2" = @str) { content: @str is not "theme2"; } +.stringguard(@str) when (@str = 'theme1') { content: @str is 'theme1'; } +.stringguard(@str) when not ('theme2' = @str) { content: @str is not 'theme2'; } +.stringguard(@str) when (~"theme1" = @str) { content: @str is theme1; } +.stringguard(@str) {} +.stringguardtest { + .stringguard("theme1"); + .stringguard("theme2"); + .stringguard('theme1'); + .stringguard('theme2'); + .stringguard(theme1); +} + +.mixin(...) { + catch:all; +} +.mixin(@var) when (@var=4) { + declare: 4; +} +.mixin(@var) when (@var=4px) { + declare: 4px; +} +#tryNumberPx { + .mixin(4px); +} + +.lock-mixin(@a) { + .inner-locked-mixin(@x: @a) when (@a = 1) { + a: @a; + x: @x; + } +} +.call-lock-mixin { + .lock-mixin(1); + .call-inner-lock-mixin { + .inner-locked-mixin(); + } +} +.bug-100cm-1m(@a) when (@a = 1) { + .failed { + one-hundred: not-equal-to-1; + } +} +.bug-100cm-1m(100cm); + +#ns { + .mixin-for-root-usage(@a) when (@a > 0) { + .mixin-generated-class { + a: @a; + } + } +} + +#ns > .mixin-for-root-usage(1); diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-important.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-important.less new file mode 100644 index 000000000..c8cc1d5ca --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-important.less @@ -0,0 +1,25 @@ +.submixin(@a) { + border-width: @a; +} +.mixin (9) { + border: 9 !important; +} +.mixin (@a: 0) { + border: @a; + boxer: @a; + .inner { + test: @a; + } + // comment + .submixin(@a); +} + +.class { + .mixin(1); + .mixin(2) !important; + .mixin(3); + .mixin(4) !important; + .mixin(5); + .mixin !important; + .mixin(9); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-interpolated.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-interpolated.less new file mode 100644 index 000000000..2e75e9805 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-interpolated.less @@ -0,0 +1,69 @@ + +@a1: foo; +@a2: ~".foo"; +@a4: ~"#foo"; + +.@{a1} { + a: 1; +} + +@{a2} { + a: 2; +} + +#@{a1} { + a: 3; +} + +@{a4} { + a: 4; +} + +mi-test-a { + .foo; + #foo; +} + +.b .bb { + &.@{a1}-xxx .yyy-@{a1}@{a4} { + & @{a2}.bbb { + b: 1; + } + } +} + +mi-test-b { + .b.bb.foo-xxx.yyy-foo#foo.foo.bbb; +} + +@c1: @a1; +@c2: bar; +@c3: baz; + +#@{c1}-foo { + > .@{c2} { + .@{c3} { + c: c; + } + } +} + +mi-test-c { + &-1 {#foo-foo;} + &-2 {#foo-foo > .bar;} + &-3 {#foo-foo > .bar.baz;} +} + +.Person(@name, @gender_) { + .@{name} { + @gender: @gender_; + .sayGender() { + gender: @gender; + } + } +} + +mi-test-d { + .Person(person, "Male"); + .person.sayGender(); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-named-args.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-named-args.less new file mode 100644 index 000000000..d79e0f473 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-named-args.less @@ -0,0 +1,36 @@ +.mixin (@a: 1px, @b: 50%) { + width: (@a * 5); + height: (@b - 1%); + args: @arguments; +} +.mixin (@a: 1px, @b: 50%) when (@b > 75%){ + text-align: center; +} + +.named-arg { + color: blue; + .mixin(@b: 100%); +} + +.class { + @var: 20%; + .mixin(@b: @var); +} + +.all-args-wrong-args { + .mixin(@b: 10%, @a: 2px); +} + +.mixin2 (@a: 1px, @b: 50%, @c: 50) { + width: (@a * 5); + height: (@b - 1%); + color: (#000000 + @c); +} + +.named-args2 { + .mixin2(3px, @c: 100); +} + +.named-args3 { + .mixin2(@b: 30%, @c: #123456); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-nested.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-nested.less new file mode 100644 index 000000000..43443de29 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-nested.less @@ -0,0 +1,22 @@ +.mix-inner (@var) { + border-width: @var; +} + +.mix (@a: 10) { + .inner { + height: (@a * 10); + + .innest { + width: @a; + .mix-inner((@a * 2)); + } + } +} + +.class { + .mix(30); +} + +.class2 { + .mix(60); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins-pattern.less b/node_modules/less-middleware/node_modules/less/test/less/mixins-pattern.less new file mode 100644 index 000000000..e769b0cf7 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins-pattern.less @@ -0,0 +1,102 @@ +.mixin (...) { + variadic: true; +} +.mixin (@a...) { + named-variadic: true; +} +.mixin () { + zero: 0; +} +.mixin (@a: 1px) { + one: 1; +} +.mixin (@a) { + one-req: 1; +} +.mixin (@a: 1px, @b: 2px) { + two: 2; +} + +.mixin (@a, @b, @c) { + three-req: 3; +} + +.mixin (@a: 1px, @b: 2px, @c: 3px) { + three: 3; +} + +.zero { + .mixin(); +} + +.one { + .mixin(1); +} + +.two { + .mixin(1, 2); +} + +.three { + .mixin(1, 2, 3); +} + +// + +.mixout ('left') { + left: 1; +} + +.mixout ('right') { + right: 1; +} + +.left { + .mixout('left'); +} +.right { + .mixout('right'); +} + +// + +.border (@side, @width) { + color: black; + .border-side(@side, @width); +} +.border-side (left, @w) { + border-left: @w; +} +.border-side (right, @w) { + border-right: @w; +} + +.border-right { + .border(right, 4px); +} +.border-left { + .border(left, 4px); +} + +// + + +.border-radius (@r) { + both: (@r * 10); +} +.border-radius (@r, left) { + left: @r; +} +.border-radius (@r, right) { + right: @r; +} + +.only-right { + .border-radius(33, right); +} +.only-left { + .border-radius(33, left); +} +.left-right { + .border-radius(33); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/mixins.less b/node_modules/less-middleware/node_modules/less/test/less/mixins.less new file mode 100644 index 000000000..b1a83c6ca --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/mixins.less @@ -0,0 +1,145 @@ +.mixin { border: 1px solid black; } +.mixout { border-color: orange; } +.borders { border-style: dashed; } +.mixin > * { border: do not match me; } + +#namespace { + .borders { + border-style: dotted; + } + .biohazard { + content: "death"; + .man { + color: transparent; + } + } +} +#theme { + > .mixin { + background-color: grey; + } +} +#container { + color: black; + .mixin; + .mixout; + #theme > .mixin; +} + +#header { + .milk { + color: white; + .mixin; + #theme > .mixin; + } + #cookie { + .chips { + #namespace .borders; + .calories { + #container; + } + } + .borders; + } +} +.secure-zone { #namespace .biohazard .man; } +.direct { + #namespace > .borders; +} + +.bo, .bar { + width: 100%; +} +.bo { + border: 1px; +} +.ar.bo.ca { + color: black; +} +.jo.ki { + background: none; +} +.amp { + &.support { + color: orange; + .higher { + top: 0px; + } + &.deeper { + height: auto; + } + } +} +.extended { + .bo; + .jo.ki; + .amp.support; + .amp.support.higher; + .amp.support.deeper; +} +.do .re .mi .fa { + .sol .la { + .si { + color: cyan; + } + } +} +.mutli-selector-parents { + .do.re.mi.fa.sol.la.si; +} +.foo .bar { + .bar; +} +.has_parents() { + & .underParents { + color: red; + } +} +.has_parents(); +.parent { + .has_parents(); +} +.margin_between(@above, @below) { + * + & { margin-top: @above; } + legend + & { margin-top: 0; } + & + * { margin-top: @below; } +} +h1 { .margin_between(25px, 10px); } +h2 { .margin_between(20px, 8px); } +h3 { .margin_between(15px, 5px); } + +.mixin_def(@url, @position){ + background-image: @url; + background-position: @position; +} +.error{ + @s: "/"; + .mixin_def( "@{s}a.png", center center); +} +.recursion() { + color: black; +} +.test-rec { + .recursion { + .recursion(); + } +} +.paddingFloat(@padding) { padding-left: @padding; } + +.button { + .paddingFloat(((10px + 12) * 2)); + + &.large { .paddingFloat(((10em * 2) * 2)); } +} +.clearfix() { + // ... +} +.clearfix { + .clearfix(); +} +.clearfix { + .clearfix(); +} +.foo { + .clearfix(); +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.json b/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.json new file mode 100644 index 000000000..6bd2a4845 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.json @@ -0,0 +1,5 @@ +{ + "the-border": "1px", + "base-color": "#111", + "red": "#842210" +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.less b/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.less new file mode 100644 index 000000000..0badc6715 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/modifyVars/extended.less @@ -0,0 +1,11 @@ +#header { + color: (@base-color * 3); + border-left: @the-border; + border-right: (@the-border * 2); +} +#footer { + color: (@base-color + #003300); + border-color: @red; +} +@red: blue; // var is overridden by the modifyVars +//@base-color: green; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.less b/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.less new file mode 100644 index 000000000..15ef8a456 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.less @@ -0,0 +1,3 @@ +.a { + a: `1 + 1`; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.txt b/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.txt new file mode 100644 index 000000000..d81dd2bdb --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/no-js-errors/no-js-errors.txt @@ -0,0 +1,4 @@ +SyntaxError: You are using JavaScript, which has been disabled. in {path}no-js-errors.less on line 2, column 6: +1 .a { +2 a: `1 + 1`; +3 } diff --git a/node_modules/less-middleware/node_modules/less/test/less/no-output.less b/node_modules/less-middleware/node_modules/less/test/less/no-output.less new file mode 100644 index 000000000..b4e6a499f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/no-output.less @@ -0,0 +1,2 @@ +.mixin() { +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/operations.less b/node_modules/less-middleware/node_modules/less/test/less/operations.less new file mode 100644 index 000000000..3e483c8b6 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/operations.less @@ -0,0 +1,62 @@ +#operations { + color: (#110000 + #000011 + #001100); // #111111 + height: (10px / 2px + 6px - 1px * 2); // 9px + width: (2 * 4 - 5em); // 3em + .spacing { + height: (10px / 2px+6px-1px*2); + width: (2 * 4-5em); + } + substraction: (20 - 10 - 5 - 5); // 0 + division: (20 / 5 / 4); // 1 +} + +@x: 4; +@y: 12em; + +.with-variables { + height: (@x + @y); // 16em + width: (12 + @y); // 24em + size: (5cm - @x); // 1cm +} + +.with-functions { + color: (rgb(200, 200, 200) / 2); + color: (2 * hsl(0, 50%, 50%)); + color: (rgb(10, 10, 10) + hsl(0, 50%, 50%)); +} + +@z: -2; + +.negative { + height: (2px + @z); // 0px + width: (2px - @z); // 4px +} + +.shorthands { + padding: -1px 2px 0 -4px; // +} + +.rem-dimensions { + font-size: (20rem / 5 + 1.5rem); // 5.5rem +} + +.colors { + color: #123; // #112233 + border-color: (#234 + #111111); // #334455 + background-color: (#222222 - #fff); // #000000 + .other { + color: (2 * #111); // #222222 + border-color: (#333333 / 3 + #111); // #222222 + } +} + +.negations { + @var: 4px; + variable: (-@var); // 4 + variable1: (-@var + @var); // 0 + variable2: (@var + -@var); // 0 + variable3: (@var - -@var); // 8 + variable4: (-@var - -@var); // 0 + paren: (-(@var)); // -4px + paren2: (-(2 + 2) * -@var); // 16 +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/parens.less b/node_modules/less-middleware/node_modules/less/test/less/parens.less new file mode 100644 index 000000000..eeef34481 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/parens.less @@ -0,0 +1,45 @@ +.parens { + @var: 1px; + border: (@var * 2) solid black; + margin: (@var * 1) (@var + 2) (4 * 4) 3; + width: (6 * 6); + padding: 2px (6 * 6px); +} + +.more-parens { + @var: (2 * 2); + padding: (2 * @var) 4 4 (@var * 1px); + width-all: ((@var * @var) * 6); + width-first: ((@var * @var)) * 6; + width-keep: (@var * @var) * 6; + height-keep: (7 * 7) + (8 * 8); + height-all: ((7 * 7) + (8 * 8)); + height-parts: ((7 * 7)) + ((8 * 8)); + margin-keep: (4 * (5 + 5) / 2) - (@var * 2); + margin-parts: ((4 * (5 + 5) / 2)) - ((@var * 2)); + margin-all: ((4 * (5 + 5) / 2) + (-(@var * 2))); + border-radius-keep: 4px * (1 + 1) / @var + 3px; + border-radius-parts: ((4px * (1 + 1))) / ((@var + 3px)); + border-radius-all: (4px * (1 + 1) / @var + 3px); + //margin: (6 * 6)px; +} + +.negative { + @var: 1; + neg-var: -@var; // -1 ? + neg-var-paren: -(@var); // -(1) ? +} + +.nested-parens { + width: 2 * (4 * (2 + (1 + 6))) - 1; + height: ((2 + 3) * (2 + 3) / (9 - 4)) + 1; +} + +.mixed-units { + margin: 2px 4em 1 5pc; + padding: (2px + 4px) 1em 2px 2; +} + +.test-false-negatives { + a: ~"("; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less b/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less new file mode 100644 index 000000000..46e337913 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less @@ -0,0 +1,56 @@ + +pi-test { + @prefix: ufo-; + @a: border; + @bb: top; + @c_c: left; + @d-d4: radius; + @-: -; + + @var: ~'@not-variable'; + + @{a}: 0; + @{var}: @var; + @{prefix}width: 50%; + *-z-@{a} :1px dashed blue; + -www-@{a}-@{bb}: 2px; + @{d-d4}-is-not-a-@{a}:true; + @{a}-@{bb}-@{c_c}-@{d-d4} : 2em; + @{a}@{-}@{bb}@{-}red@{-}@{d-d4}-: 3pt; + + .mixin(mixer); + .merge(ish, base); +} + +@global: global; + +.mixin(@arg) { + @local: local; + @{global}-@{local}-@{arg}-property: strong; +} + +.merge(@p, @v) { + &-merge { + @prefix: pre; + @suffix: ish; + @{prefix}-property-ish+ :high; + pre-property-@{suffix} +: middle; + @{prefix}-property-@{suffix}+: low; + @{prefix}-property-@{p} + : @v; + + @subterfuge: ~'+'; + pre-property-ish@{subterfuge}: nice try dude; + } +} + +pi-indirect-vars { + @{p}: @p; + @p: @@a; + @a: b; + @b: auto; +} + +pi-complex-values { + @{p}@{p}: none; + @p: (1 + 2px) fadeout(#ff0, 50%), pi() /* foo */; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less.orig b/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less.orig new file mode 100644 index 000000000..bda40ed61 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/property-name-interp.less.orig @@ -0,0 +1,59 @@ + +pi-test { + @prefix: ufo-; + @a: border; + @bb: top; + @c_c: left; + @d-d4: radius; + @-: -; + +<<<<<<< HEAD +======= + @var: ~'@not-variable'; + +>>>>>>> origin/master + @{a}: 0; + @{var}: @var; + @{prefix}width: 50%; + *-z-@{a} :1px dashed blue; + -www-@{a}-@{bb}: 2px; + @{d-d4}-is-not-a-@{a}:true; + @{a}-@{bb}-@{c_c}-@{d-d4} : 2em; + @{a}@{-}@{bb}@{-}red@{-}@{d-d4}-: 3pt; + + .mixin(mixer); + .merge(ish, base); +} + +@global: global; + +.mixin(@arg) { + @local: local; + @{global}-@{local}-@{arg}-property: strong; +} + +.merge(@p, @v) { + &-merge { + @prefix: pre; + @suffix: ish; + @{prefix}-property-ish+ :high; + pre-property-@{suffix} +: middle; + @{prefix}-property-@{suffix}+: low; + @{prefix}-property-@{p} + : @v; + + @subterfuge: ~'+'; + pre-property-ish@{subterfuge}: nice try dude; + } +} + +pi-indirect-vars { + @{p}: @p; + @p: @@a; + @a: b; + @b: auto; +} + +pi-complex-values { + @{p}@{p}: none; + @p: (1 + 2px) fadeout(#ff0, 50%), pi() /* foo */; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/rulesets.less b/node_modules/less-middleware/node_modules/less/test/less/rulesets.less new file mode 100644 index 000000000..e81192dbc --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/rulesets.less @@ -0,0 +1,30 @@ +#first > .one { + > #second .two > #deux { + width: 50%; + #third { + &:focus { + color: black; + #fifth { + > #sixth { + .seventh #eighth { + + #ninth { + color: purple; + } + } + } + } + } + height: 100%; + } + #fourth, #five, #six { + color: #110000; + .seven, .eight > #nine { + border: 1px solid black; + } + #ten { + color: red; + } + } + } + font-size: 2em; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/scope.less b/node_modules/less-middleware/node_modules/less/test/less/scope.less new file mode 100644 index 000000000..475b1f6db --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/scope.less @@ -0,0 +1,104 @@ +@x: red; +@x: blue; +@z: transparent; +@mix: none; + +.mixin { + @mix: #989; +} +@mix: blue; +.tiny-scope { + color: @mix; // #989 + .mixin; +} + +.scope1 { + @y: orange; + @z: black; + color: @x; // blue + border-color: @z; // black + .hidden { + @x: #131313; + } + .scope2 { + @y: red; + color: @x; // blue + .scope3 { + @local: white; + color: @y; // red + border-color: @z; // black + background-color: @local; // white + } + } +} + +#namespace { + .scoped_mixin() { + @local-will-be-made-global: green; + .scope { + scoped-val: @local-will-be-made-global; + } + } +} + +#namespace > .scoped_mixin(); + +.setHeight(@h) { @height: 1024px; } +.useHeightInMixinCall(@h) { .useHeightInMixinCall { mixin-height: @h; } } +@mainHeight: 50%; +.setHeight(@mainHeight); +.heightIsSet { height: @height; } +.useHeightInMixinCall(@height); + +.importRuleset() { + .imported { + exists: true; + } +} +.importRuleset(); +.testImported { + .imported; +} + +@parameterDefault: 'top level'; +@anotherVariable: 'top level'; +//mixin uses top-level variables +.mixinNoParam(@parameter: @parameterDefault) when (@parameter = 'top level') { + default: @parameter; + scope: @anotherVariable; + sub-scope-only: @subScopeOnly; +} + +#allAreUsedHere { + //redefine top-level variables in different scope + @parameterDefault: 'inside'; + @anotherVariable: 'inside'; + @subScopeOnly: 'inside'; + //use the mixin + .mixinNoParam(); +} +#parentSelectorScope { + @col: white; + & { + @col: black; + } + prop: @col; + & { + @col: black; + } +} +.test-empty-mixin() { +} +#parentSelectorScopeMixins { + & { + .test-empty-mixin() { + should: never seee 1; + } + } + .test-empty-mixin(); + & { + .test-empty-mixin() { + should: never seee 2; + } + } +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/selectors.less b/node_modules/less-middleware/node_modules/less/test/less/selectors.less new file mode 100644 index 000000000..8b30546fd --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/selectors.less @@ -0,0 +1,156 @@ +h1, h2, h3 { + a, p { + &:hover { + color: red; + } + } +} + +#all { color: blue; } +#the { color: blue; } +#same { color: blue; } + +ul, li, div, q, blockquote, textarea { + margin: 0; +} + +td { + margin: 0; + padding: 0; +} + +td, input { + line-height: 1em; +} + +a { + color: red; + + &:hover { color: blue; } + + div & { color: green; } + + p & span { color: yellow; } +} + +.foo { + .bar, .baz { + & .qux { + display: block; + } + .qux & { + display: inline; + } + .qux& { + display: inline-block; + } + .qux & .biz { + display: none; + } + } +} + +.b { + &.c { + .a& { + color: red; + } + } +} + +.b { + .c & { + &.a { + color: red; + } + } +} + +.p { + .foo &.bar { + color: red; + } +} + +.p { + .foo&.bar { + color: red; + } +} + +.foo { + .foo + & { + background: amber; + } + & + & { + background: amber; + } +} + +.foo, .bar { + & + & { + background: amber; + } +} + +.foo, .bar { + a, b { + & > & { + background: amber; + } + } +} + +.other ::fnord { color: red } +.other::fnord { color: red } +.other { + ::bnord {color: red } + &::bnord {color: red } +} +// selector interpolation +@theme: blood; +@selector: ~".@{theme}"; +@{selector} { + color:red; +} +@{selector}red { + color: green; +} +.red { + #@{theme}.@{theme}&.black { + color:black; + } +} +@num: 3; +:nth-child(@{num}) { + selector: interpolated; +} +.test { + &:nth-child(odd):not(:nth-child(3)) { + color: #ff0000; + } +} +[prop], +[prop=10%], +[prop="value@{num}"], +[prop*="val@{num}"], +[|prop~="val@{num}"], +[*|prop$="val@{num}"], +[ns|prop^="val@{num}"], +[@{num}^="val@{num}"], +[@{num}=@{num}], +[@{num}] { + attributes: yes; +} + +/* +Large comment means chunk will be emitted after } which means chunk will begin with whitespace... +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank blank +*/ +@{selector} { + color: red; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.json b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.json new file mode 100644 index 000000000..76a63c5a4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.json @@ -0,0 +1,3 @@ +{ + "my-color": "red" +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.less b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.less new file mode 100644 index 000000000..4ee8b4f6d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/basic.less @@ -0,0 +1,27 @@ +@var: black; + +.a() { + color: red; +} + +.b { + color: green; + .a(); + color: blue; + background: @var; +} + +.a, .b { + background: green; + .c, .d { + background: gray; + & + & { + color: red; + } + } +} + +.extend:extend(.a all) { + color: pink; +} +@import (inline) "imported.css"; \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/imported.css b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/imported.css new file mode 100644 index 000000000..2ee35f066 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/sourcemaps/imported.css @@ -0,0 +1,7 @@ +/*comments*/ +.unused-css { + color: white; +} +.imported { + color: black; +} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/less/static-urls/urls.less b/node_modules/less-middleware/node_modules/less/test/less/static-urls/urls.less new file mode 100644 index 000000000..b0c7de09a --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/static-urls/urls.less @@ -0,0 +1,33 @@ +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} + +@import "../import/import-and-relative-paths-test"; diff --git a/node_modules/less-middleware/node_modules/less/test/less/strings.less b/node_modules/less-middleware/node_modules/less/test/less/strings.less new file mode 100644 index 000000000..c43e368dd --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/strings.less @@ -0,0 +1,57 @@ +#strings { + background-image: url("http://son-of-a-banana.com"); + quotes: "~" "~"; + content: "#*%:&^,)!.(~*})"; + empty: ""; + brackets: "{" "}"; + escapes: "\"hello\" \\world"; + escapes2: "\"llo"; +} +#comments { + content: "/* hello */ // not-so-secret"; +} +#single-quote { + quotes: "'" "'"; + content: '""#!&""'; + empty: ''; + semi-colon: ';'; +} +#escaped { + filter: ~"DX.Transform.MS.BS.filter(opacity=50)"; +} +#one-line { image: url(http://tooks.com) } +#crazy { image: url(http://), "}", url("http://}") } +#interpolation { + @var: '/dev'; + url: "http://lesscss.org@{var}/image.jpg"; + + @var2: 256; + url2: "http://lesscss.org/image-@{var2}.jpg"; + + @var3: #456; + url3: "http://lesscss.org@{var3}"; + + @var4: hello; + url4: "http://lesscss.org/@{var4}"; + + @var5: 54.4px; + url5: "http://lesscss.org/@{var5}"; +} + +// multiple calls with string interpolation + +.mix-mul (@a: green) { + color: ~"@{a}"; +} +.mix-mul-class { + .mix-mul(blue); + .mix-mul(red); + .mix-mul(black); + .mix-mul(orange); +} + +@test: Arial, Verdana, San-Serif; +.watermark { + @family: ~"Univers, @{test}"; + family: @family; +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/url-args/urls.less b/node_modules/less-middleware/node_modules/less/test/less/url-args/urls.less new file mode 100644 index 000000000..2f1bd8727 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/url-args/urls.less @@ -0,0 +1,63 @@ +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; + background: url("img.jpg") center / 100px; + background: #fff url(image.png) center / 1px 100px repeat-x scroll content-box padding-box; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); + background-image: url("http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700"); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} + +@import "../import/imports/font"; + +#data-uri { + uri: data-uri('image/jpeg;base64', '../../data/image.jpg'); +} + +#data-uri-guess { + uri: data-uri('../../data/image.jpg'); +} + +#data-uri-ascii { + uri-1: data-uri('text/html', '../../data/page.html'); + uri-2: data-uri('../../data/page.html'); +} + +#svg-functions { + background-image: svg-gradient(to bottom, black, white); + background-image: svg-gradient(to bottom, black, orange 3%, white); + @green_5: green 5%; + @orange_percentage: 3%; + @orange_color: orange; + background-image: svg-gradient(to bottom, (mix(black, white) + #444) 1%, @orange_color @orange_percentage, ((@green_5)), white 95%); +} + +#data-uri-with-spaces { + background-image: url( data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url( ' data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9=='); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/urls.less b/node_modules/less-middleware/node_modules/less/test/less/urls.less new file mode 100644 index 000000000..9569415ec --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/urls.less @@ -0,0 +1,84 @@ +@font-face { + src: url("/fonts/garamond-pro.ttf"); + src: local(Futura-Medium), + url(fonts.svg#MyGeometricModern) format("svg"); +} +#shorthands { + background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px; + background: url("img.jpg") center / 100px; + background: #fff url(image.png) center / 1px 100px repeat-x scroll content-box padding-box; +} +#misc { + background-image: url(images/image.jpg); +} +#data-uri { + background: url(data:image/png;charset=utf-8;base64, + kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/ + k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U + kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); + background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==); + background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700); + background-image: url("http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700"); +} + +#svg-data-uri { + background: transparent url('data:image/svg+xml, '); +} + +.comma-delimited { + background: url(bg.jpg) no-repeat, url(bg.png) repeat-x top left, url(bg); +} +.values { + @a: 'Trebuchet'; + url: url(@a); +} + +@import "import/import-and-relative-paths-test"; + +#relative-url-import { + .unquoted-relative-path-bg; + .quoted-relative-path-border-image; +} + +#data-uri { + uri: data-uri('image/jpeg;base64', '../data/image.jpg'); + uri-fragment: data-uri('image/jpeg;base64', '../data/image.jpg#fragment'); +} + +#data-uri-guess { + uri: data-uri('../data/image.jpg'); +} + +#data-uri-ascii { + uri-1: data-uri('text/html', '../data/page.html'); + uri-2: data-uri('../data/page.html'); +} + +#data-uri-toobig { + uri: data-uri('../data/data-uri-fail.png'); +} +.add_an_import(@file_to_import) { +@import "@{file_to_import}"; +} + +.add_an_import("file.css"); + +#svg-functions { + background-image: svg-gradient(to bottom, black, white); + background-image: svg-gradient(to bottom, black, orange 3%, white); + @green_5: green 5%; + @orange_percentage: 3%; + @orange_color: orange; + background-image: svg-gradient(to bottom, (mix(black, white) + #444) 1%, @orange_color @orange_percentage, ((@green_5)), white 95%); +} +//it should work also inside @font-face #2035 +@font-face { + font-family: 'MyWebFont'; + src: url(webfont.eot); + src+: url('webfont.eot?#iefix'); + src+_: format('embedded-opentype'); + src+: url('webfont.woff') format('woff'); + src+: format('truetype'); + src+_: url('webfont.ttf'); + src+: url('webfont.svg#svgFontName') format('svg'); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/variables-in-at-rules.less b/node_modules/less-middleware/node_modules/less/test/less/variables-in-at-rules.less new file mode 100644 index 000000000..96d8c611d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/variables-in-at-rules.less @@ -0,0 +1,20 @@ + +@Eight: 8; +@charset "UTF-@{Eight}"; + +@ns: less; +@namespace @ns "http://lesscss.org"; + +@name: enlarger; +@keyframes @name { + from {font-size: 12px;} + to {font-size: 15px;} +} + +.m(reducer); +.m(@name) { + @-webkit-keyframes @name { + from {font-size: 13px;} + to {font-size: 10px;} + } +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/variables.less b/node_modules/less-middleware/node_modules/less/test/less/variables.less new file mode 100644 index 000000000..e896f4049 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/variables.less @@ -0,0 +1,83 @@ +@a: 2; +@x: (@a * @a); +@y: (@x + 1); +@z: (@x * 2 + @y); +@var: -1; + +.variables { + width: (@z + 1cm); // 14cm +} + +@b: @a * 10; +@c: #888; + +@fonts: "Trebuchet MS", Verdana, sans-serif; +@f: @fonts; + +@quotes: "~" "~"; +@q: @quotes; +@onePixel: 1px; + +.variables { + height: (@b + @x + 0px); // 24px + color: @c; + font-family: @f; + quotes: @q; +} + +.redef { + @var: 0; + .inition { + @var: 4; + @var: 2; + three: @var; + @var: 3; + } + zero: @var; +} + +.values { + minus-one: @var; + @a: 'Trebuchet'; + @multi: 'A', B, C; + font-family: @a, @a, @a; + color: @c !important; + multi: something @multi, @a; +} + +.variable-names { + @var: 'hello'; + @name: 'var'; + name: @@name; +} + +.alpha { + @var: 42; + filter: alpha(opacity=@var); +} + +.polluteMixin() { + @a: 'pollution'; +} +.testPollution { + @a: 'no-pollution'; + a: @a; + .polluteMixin(); + a: @a; +} + +.units { + width: @onePixel; + same-unit-as-previously: (@onePixel / @onePixel); + square-pixel-divided: (@onePixel * @onePixel / @onePixel); + odd-unit: unit((@onePixel * 4em / 2cm)); + percentage: (10 * 50%); + pixels: (50px * 10); + conversion-metric-a: (20mm + 1cm); + conversion-metric-b: (1cm + 20mm); + conversion-imperial: (1in + 72pt + 6pc); + custom-unit: (42octocats * 10); + custom-unit-cancelling: (8cats * 9dogs / 4cats); + mix-units: (1px + 1em); + invalid-units: (1px * 1px); +} diff --git a/node_modules/less-middleware/node_modules/less/test/less/whitespace.less b/node_modules/less-middleware/node_modules/less/test/less/whitespace.less new file mode 100644 index 000000000..ab4804da9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/less/whitespace.less @@ -0,0 +1,44 @@ + + +.whitespace + { color: white; } + +.whitespace +{ + color: white; +} + .whitespace +{ color: white; } + +.whitespace{color:white;} +.whitespace { color : white ; } + +.white, +.space, +.mania +{ color: white; } + +.no-semi-column { color: white } +.no-semi-column { + color: white; + white-space: pre +} +.no-semi-column {border: 2px solid white} +.newlines { + background: the, + great, + wall; + border: 2px + solid + black; +} +.empty { + +} +.sel +.newline_ws .tab_ws { +color: +white; +background-position: 45 +-23; +} diff --git a/node_modules/less-middleware/node_modules/less/test/modify-vars.js b/node_modules/less-middleware/node_modules/less/test/modify-vars.js new file mode 100644 index 000000000..c4c6c5b4f --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/modify-vars.js @@ -0,0 +1,17 @@ +var less = require('../lib/less'), + fs = require('fs') + +var input = fs.readFileSync("./test/less/modifyVars/extended.less", 'utf8') +var expectedCss = fs.readFileSync('./test/css/modifyVars/extended.css', 'utf8') +var options = { + modifyVars: JSON.parse(fs.readFileSync("./test/less/modifyVars/extended.json", 'utf8')) +} + +less.render(input, options, function (err, css) { + if (err) console.log(err); + if (css === expectedCss) { + console.log("PASS") + } else { + console.log("FAIL") + } +}) \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/rhino/test-header.js b/node_modules/less-middleware/node_modules/less/test/rhino/test-header.js new file mode 100644 index 000000000..884e5d150 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/rhino/test-header.js @@ -0,0 +1,15 @@ +function initRhinoTest() { + process = { title: 'dummy' }; + + less.tree.functions.add = function (a, b) { + return new(less.tree.Dimension)(a.value + b.value); + }; + less.tree.functions.increment = function (a) { + return new(less.tree.Dimension)(a.value + 1); + }; + less.tree.functions._color = function (str) { + if (str.value === "evil red") { return new(less.tree.Color)("600"); } + }; +} + +initRhinoTest(); \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/sourcemaps/basic.json b/node_modules/less-middleware/node_modules/less/test/sourcemaps/basic.json new file mode 100644 index 000000000..e548ead74 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/sourcemaps/basic.json @@ -0,0 +1 @@ +{"version":3,"sources":["testweb/sourcemaps/basic.less","testweb/sourcemaps/imported.css"],"names":[],"mappings":"AAMA;EACE,YAAA;EAJA,UAAA;EAWA,iBAAA;EALA,WAAA;EACA,mBAAA;;AAJF,EASE;AATF,EASM;EACF,gBAAA;;AACA,EAFF,GAEI,KAFJ;AAEE,EAFF,GAEI,KAFA;AAEF,EAFE,GAEA,KAFJ;AAEE,EAFE,GAEA,KAFA;EAGA,UAAA;;AALN;AAAI;AAUJ;EATE,iBAAA;;AADF,EAEE;AAFE,EAEF;AAFF,EAEM;AAFF,EAEE;AAQN,OARE;AAQF,OARM;EACF,gBAAA;;AACA,EAFF,GAEI,KAFJ;AAEE,EAFF,GAEI,KAFJ;AAEE,EAFF,GAEI,KAFA;AAEF,EAFF,GAEI,KAFA;AAEF,EAFF,GAEI,KAFJ;AAEE,EAFF,GAEI,KAFJ;AAEE,EAFF,GAEI,KAFA;AAEF,EAFF,GAEI,KAFA;AAEF,EAFE,GAEA,KAFJ;AAEE,EAFE,GAEA,KAFJ;AAEE,EAFE,GAEA,KAFA;AAEF,EAFE,GAEA,KAFA;AAEF,EAFE,GAEA,KAFJ;AAEE,EAFE,GAEA,KAFJ;AAEE,EAFE,GAEA,KAFA;AAEF,EAFE,GAEA,KAFA;AAQN,OARE,GAQF,UARE;AAQF,OARE,GAEI,KAFJ;AAQF,OARE,GAQF,UARM;AAQN,OARE,GAEI,KAFA;AAEF,EAFF,GAQF,UARE;AAEE,EAFF,GAQF,UARM;AAQN,OARM,GAQN,UARE;AAQF,OARM,GAEA,KAFJ;AAQF,OARM,GAQN,UARM;AAQN,OARM,GAEA,KAFA;AAEF,EAFE,GAQN,UARE;AAEE,EAFE,GAQN,UARM;EAGA,UAAA;;AAKN;EACE,WAAA;;ACxBF;AACA;AACA;AACA;AACA;AACA;AACA","file":"sourcemaps/basic.css"} \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/test/sourcemaps/index.html b/node_modules/less-middleware/node_modules/less/test/sourcemaps/index.html new file mode 100644 index 000000000..89acca77e --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/test/sourcemaps/index.html @@ -0,0 +1,17 @@ + + + + + + +
    id import-test
    +
    id import-test
    +
    class imported inline
    +
    class mixin
    +
    class a
    +
    class b
    +
    class b
    class c
    +
    class a
    class d
    +
    class extend
    class c
    + + \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/less/tmp/browser/test-runner-main.html b/node_modules/less-middleware/node_modules/less/tmp/browser/test-runner-main.html new file mode 100644 index 000000000..0722f1713 --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/tmp/browser/test-runner-main.html @@ -0,0 +1,247 @@ + + + + + Jasmine Spec Runner + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/node_modules/less-middleware/node_modules/less/tmp/less.js b/node_modules/less-middleware/node_modules/less/tmp/less.js new file mode 100644 index 000000000..d427eb89d --- /dev/null +++ b/node_modules/less-middleware/node_modules/less/tmp/less.js @@ -0,0 +1,8295 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= level) { + console.log('less: ' + str); + } +} + +/* + TODO - options is now hidden - we should expose it on the less object, but not have it "as" the less object + alternately even have it on environment + e.g. less.environment.options.fileAsync = true; + is it weird you do + less = { fileAsync: true } + then access as less.environment.options.fileAsync ? + */ + +var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol), + options = window.less, + environment = require("./environment/browser.js")(options, isFileProtocol, log, logLevel); + +window.less = less = require('./non-node-index.js')(environment); + +less.env = options.env || (location.hostname == '127.0.0.1' || + location.hostname == '0.0.0.0' || + location.hostname == 'localhost' || + (location.port && + location.port.length > 0) || + isFileProtocol ? 'development' + : 'production'); + +// The amount of logging in the javascript console. +// 3 - Debug, information and errors +// 2 - Information and errors +// 1 - Errors +// 0 - None +// Defaults to 2 +less.logLevel = typeof(options.logLevel) != 'undefined' ? options.logLevel : (less.env === 'development' ? logLevel.debug : logLevel.errors); + +// Load styles asynchronously (default: false) +// +// This is set to `false` by default, so that the body +// doesn't start loading before the stylesheets are parsed. +// Setting this to `true` can result in flickering. +// +options.async = options.async || false; +options.fileAsync = options.fileAsync || false; + +// Interval between watch polls +less.poll = less.poll || (isFileProtocol ? 1000 : 1500); + +//Setup user functions +if (options.functions) { + less.functions.functionRegistry.addMultiple(options.functions); +} + +var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash); +if (dumpLineNumbers) { + less.dumpLineNumbers = dumpLineNumbers[1]; +} + +var typePattern = /^text\/(x-)?less$/; +var cache = null; + +function extractId(href) { + return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain + .replace(/^\//, '' ) // Remove root / + .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension + .replace(/[^\.\w-]+/g, '-') // Replace illegal characters + .replace(/\./g, ':'); // Replace dots with colons(for valid id) +} + +function errorConsole(e, rootHref) { + var template = '{line} {content}'; + var filename = e.filename || rootHref; + var errors = []; + var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + + " in " + filename + " "; + + var errorline = function (e, i, classname) { + if (e.extract[i] !== undefined) { + errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) + .replace(/\{class\}/, classname) + .replace(/\{content\}/, e.extract[i])); + } + }; + + if (e.extract) { + errorline(e, 0, ''); + errorline(e, 1, 'line'); + errorline(e, 2, ''); + content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' + + errors.join('\n'); + } else if (e.stack) { + content += e.stack; + } + log(content, logLevel.errors); +} + +function createCSS(styles, sheet, lastModified) { + // Strip the query-string + var href = sheet.href || ''; + + // If there is no title set, use the filename, minus the extension + var id = 'less:' + (sheet.title || extractId(href)); + + // If this has already been inserted into the DOM, we may need to replace it + var oldCss = document.getElementById(id); + var keepOldCss = false; + + // Create a new stylesheet node for insertion or (if necessary) replacement + var css = document.createElement('style'); + css.setAttribute('type', 'text/css'); + if (sheet.media) { + css.setAttribute('media', sheet.media); + } + css.id = id; + + if (!css.styleSheet) { + css.appendChild(document.createTextNode(styles)); + + // If new contents match contents of oldCss, don't replace oldCss + keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 && + oldCss.firstChild.nodeValue === css.firstChild.nodeValue); + } + + var head = document.getElementsByTagName('head')[0]; + + // If there is no oldCss, just append; otherwise, only append if we need + // to replace oldCss with an updated stylesheet + if (oldCss === null || keepOldCss === false) { + var nextEl = sheet && sheet.nextSibling || null; + if (nextEl) { + nextEl.parentNode.insertBefore(css, nextEl); + } else { + head.appendChild(css); + } + } + if (oldCss && keepOldCss === false) { + oldCss.parentNode.removeChild(oldCss); + } + + // For IE. + // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash. + // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head + if (css.styleSheet) { + try { + css.styleSheet.cssText = styles; + } catch (e) { + throw new(Error)("Couldn't reassign styleSheet.cssText."); + } + } + + // Don't update the local store if the file wasn't modified + if (lastModified && cache) { + log('saving ' + href + ' to cache.', logLevel.info); + try { + cache.setItem(href, styles); + cache.setItem(href + ':timestamp', lastModified); + } catch(e) { + //TODO - could do with adding more robust error handling + log('failed to save', logLevel.errors); + } + } +} + +function postProcessCSS(styles) { + if (options.postProcessor && typeof options.postProcessor === 'function') { + styles = options.postProcessor.call(styles, styles) || styles; + } + return styles; +} + +function errorHTML(e, rootHref) { + var id = 'less-error-message:' + extractId(rootHref || ""); + var template = '
  • {content}
  • '; + var elem = document.createElement('div'), timer, content, errors = []; + var filename = e.filename || rootHref; + var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; + + elem.id = id; + elem.className = "less-error-message"; + + content = '

    ' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + + '

    ' + '

    in ' + filenameNoPath + " "; + + var errorline = function (e, i, classname) { + if (e.extract[i] !== undefined) { + errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) + .replace(/\{class\}/, classname) + .replace(/\{content\}/, e.extract[i])); + } + }; + + if (e.extract) { + errorline(e, 0, ''); + errorline(e, 1, 'line'); + errorline(e, 2, ''); + content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':

    ' + + '
      ' + errors.join('') + '
    '; + } else if (e.stack) { + content += '
    ' + e.stack.split('\n').slice(1).join('
    '); + } + elem.innerHTML = content; + + // CSS for error messages + createCSS([ + '.less-error-message ul, .less-error-message li {', + 'list-style-type: none;', + 'margin-right: 15px;', + 'padding: 4px 0;', + 'margin: 0;', + '}', + '.less-error-message label {', + 'font-size: 12px;', + 'margin-right: 15px;', + 'padding: 4px 0;', + 'color: #cc7777;', + '}', + '.less-error-message pre {', + 'color: #dd6666;', + 'padding: 4px 0;', + 'margin: 0;', + 'display: inline-block;', + '}', + '.less-error-message pre.line {', + 'color: #ff0000;', + '}', + '.less-error-message h3 {', + 'font-size: 20px;', + 'font-weight: bold;', + 'padding: 15px 0 5px 0;', + 'margin: 0;', + '}', + '.less-error-message a {', + 'color: #10a', + '}', + '.less-error-message .error {', + 'color: red;', + 'font-weight: bold;', + 'padding-bottom: 2px;', + 'border-bottom: 1px dashed red;', + '}' + ].join('\n'), { title: 'error-message' }); + + elem.style.cssText = [ + "font-family: Arial, sans-serif", + "border: 1px solid #e00", + "background-color: #eee", + "border-radius: 5px", + "-webkit-border-radius: 5px", + "-moz-border-radius: 5px", + "color: #e00", + "padding: 15px", + "margin-bottom: 15px" + ].join(';'); + + if (less.env == 'development') { + timer = setInterval(function () { + if (document.body) { + if (document.getElementById(id)) { + document.body.replaceChild(elem, document.getElementById(id)); + } else { + document.body.insertBefore(elem, document.body.firstChild); + } + clearInterval(timer); + } + }, 10); + } +} + +function error(e, rootHref) { + if (!options.errorReporting || options.errorReporting === "html") { + errorHTML(e, rootHref); + } else if (options.errorReporting === "console") { + errorConsole(e, rootHref); + } else if (typeof options.errorReporting === 'function') { + options.errorReporting("add", e, rootHref); + } +} + +function removeErrorHTML(path) { + var node = document.getElementById('less-error-message:' + extractId(path)); + if (node) { + node.parentNode.removeChild(node); + } +} + +function removeErrorConsole(path) { + //no action +} + +function removeError(path) { + if (!options.errorReporting || options.errorReporting === "html") { + removeErrorHTML(path); + } else if (options.errorReporting === "console") { + removeErrorConsole(path); + } else if (typeof options.errorReporting === 'function') { + options.errorReporting("remove", path); + } +} + +function loadStyles(modifyVars) { + var styles = document.getElementsByTagName('style'), + style; + for (var i = 0; i < styles.length; i++) { + style = styles[i]; + if (style.type.match(typePattern)) { + var env = new less.contexts.parseEnv(options), + lessText = style.innerHTML || ''; + env.filename = document.location.href.replace(/#.*$/, ''); + + if (modifyVars || options.globalVars) { + env.useFileCache = true; + } + + /*jshint loopfunc:true */ + // use closure to store current value of i + var callback = (function(style) { + return function (e, cssAST) { + if (e) { + return error(e, "inline"); + } + var css = cssAST.toCSS(options); + style.type = 'text/css'; + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { + style.innerHTML = css; + } + }; + })(style); + new(less.Parser)(env).parse(lessText, callback, {globalVars: options.globalVars, modifyVars: modifyVars}); + } + } +} + +function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) { + + var env = new less.contexts.parseEnv(options); + env.mime = sheet.type; + + if (modifyVars || options.globalVars) { + env.useFileCache = true; + } + + less.environment.loadFile(env, sheet.href, null, function loadInitialFileCallback(e, data, path, webInfo) { + + var newFileInfo = { + currentDirectory: less.environment.getPath(env, path), + filename: path, + rootFilename: path, + relativeUrls: env.relativeUrls}; + + newFileInfo.entryPath = newFileInfo.currentDirectory; + newFileInfo.rootpath = env.rootpath || newFileInfo.currentDirectory; + + if (webInfo) { + webInfo.remaining = remaining; + + var css = cache && cache.getItem(path), + timestamp = cache && cache.getItem(path + ':timestamp'); + + if (!reload && timestamp && webInfo.lastModified && + (new(Date)(webInfo.lastModified).valueOf() === + new(Date)(timestamp).valueOf())) { + // Use local copy + createCSS(css, sheet); + webInfo.local = true; + callback(null, null, data, sheet, webInfo, path); + return; + } + } + + //TODO add tests around how this behaves when reloading + removeError(path); + + if (data) { + env.currentFileInfo = newFileInfo; + new(less.Parser)(env).parse(data, function (e, root) { + if (e) { return callback(e, null, null, sheet); } + try { + callback(e, root, data, sheet, webInfo, path); + } catch (e) { + callback(e, null, null, sheet); + } + }, {modifyVars: modifyVars, globalVars: options.globalVars}); + } else { + callback(e, null, null, sheet, webInfo, path); + } + }, env, modifyVars); +} + +function loadStyleSheets(callback, reload, modifyVars) { + for (var i = 0; i < less.sheets.length; i++) { + loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars); + } +} + +function initRunningMode(){ + if (less.env === 'development') { + less.watchTimer = setInterval(function () { + if (less.watchMode) { + loadStyleSheets(function (e, root, _, sheet, env) { + if (e) { + error(e, sheet.href); + } else if (root) { + var styles = root.toCSS(less); + styles = postProcessCSS(styles); + createCSS(styles, sheet, env.lastModified); + } + }); + } + }, options.poll); + } +} + +// +// Watch mode +// +less.watch = function () { + if (!less.watchMode ){ + less.env = 'development'; + initRunningMode(); + } + this.watchMode = true; + return true; +}; + +less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; }; + +if (/!watch/.test(location.hash)) { + less.watch(); +} + +if (less.env != 'development') { + try { + cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; + } catch (_) {} +} + +// +// Get all tags with the 'rel' attribute set to "stylesheet/less" +// +var links = document.getElementsByTagName('link'); + +less.sheets = []; + +for (var i = 0; i < links.length; i++) { + if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && + (links[i].type.match(typePattern)))) { + less.sheets.push(links[i]); + } +} + +// +// With this function, it's possible to alter variables and re-render +// CSS without reloading less-files +// +less.modifyVars = function(record) { + less.refresh(false, record); +}; + +less.refresh = function (reload, modifyVars) { + var startTime, endTime; + startTime = endTime = new Date(); + + loadStyleSheets(function (e, root, _, sheet, env) { + if (e) { + return error(e, sheet.href); + } + if (env.local) { + log("loading " + sheet.href + " from cache.", logLevel.info); + } else { + log("parsed " + sheet.href + " successfully.", logLevel.debug); + var styles = root.toCSS(options); + styles = postProcessCSS(styles); + createCSS(styles, sheet, env.lastModified); + } + log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info); + if (env.remaining === 0) { + log("less has finished. css generated in " + (new Date() - startTime) + 'ms', logLevel.info); + } + endTime = new Date(); + }, reload, modifyVars); + + loadStyles(modifyVars); +}; + +less.refreshStyles = loadStyles; + +less.refresh(less.env === 'development'); + +},{"./environment/browser.js":6,"./non-node-index.js":20}],2:[function(require,module,exports){ +var contexts = {}; +module.exports = contexts; + +var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) { + if (!original) { return; } + + for(var i = 0; i < propertiesToCopy.length; i++) { + if (original.hasOwnProperty(propertiesToCopy[i])) { + destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; + } + } +}; + +var parseCopyProperties = [ + 'paths', // option - unmodified - paths to search for imports on + 'files', // list of files that have been imported, used for import-once + 'contents', // map - filename to contents of all the files + 'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore + 'relativeUrls', // option - whether to adjust URL's to be relative + 'rootpath', // option - rootpath to append to URL's + 'strictImports', // option - + 'insecure', // option - whether to allow imports from insecure ssl hosts + 'dumpLineNumbers', // option - whether to dump line numbers + 'compress', // option - whether to compress + 'processImports', // option - whether to process imports. if false then imports will not be imported + 'syncImport', // option - whether to import synchronously + 'chunkInput', // option - whether to chunk input. more performant but causes parse issues. + 'mime', // browser only - mime type for sheet import + 'useFileCache', // browser only - whether to use the per file session cache + 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc. +]; + +//currentFileInfo = { +// 'relativeUrls' - option - whether to adjust URL's to be relative +// 'filename' - full resolved filename of current file +// 'rootpath' - path to append to normal URLs for this node +// 'currentDirectory' - path to the current file, absolute +// 'rootFilename' - filename of the base file +// 'entryPath' - absolute path to the entry file +// 'reference' - whether the file should not be output and only output parts that are referenced + +contexts.parseEnv = function(options) { + copyFromOriginal(options, this, parseCopyProperties); + + if (!this.contents) { this.contents = {}; } + if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; } + if (!this.files) { this.files = {}; } + + if (typeof this.paths === "string") { this.paths = [this.paths]; } + + if (!this.currentFileInfo) { + var filename = (options && options.filename) || "input"; + var entryPath = filename.replace(/[^\/\\]*$/, ""); + if (options) { + options.filename = null; + } + this.currentFileInfo = { + filename: filename, + relativeUrls: this.relativeUrls, + rootpath: (options && options.rootpath) || "", + currentDirectory: entryPath, + entryPath: entryPath, + rootFilename: filename + }; + } +}; + +var evalCopyProperties = [ + 'silent', // whether to swallow errors and warnings + 'verbose', // whether to log more activity + 'compress', // whether to compress + 'yuicompress', // whether to compress with the outside tool yui compressor + 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) + 'strictMath', // whether math has to be within parenthesis + 'strictUnits', // whether units need to evaluate correctly + 'cleancss', // whether to compress with clean-css + 'sourceMap', // whether to output a source map + 'importMultiple', // whether we are currently importing multiple copies + 'urlArgs', // whether to add args into url tokens + 'javascriptEnabled'// option - whether JavaScript is enabled. if undefined, defaults to true + ]; + +contexts.evalEnv = function(options, frames) { + copyFromOriginal(options, this, evalCopyProperties); + + this.frames = frames || []; +}; + +contexts.evalEnv.prototype.inParenthesis = function () { + if (!this.parensStack) { + this.parensStack = []; + } + this.parensStack.push(true); +}; + +contexts.evalEnv.prototype.outOfParenthesis = function () { + this.parensStack.pop(); +}; + +contexts.evalEnv.prototype.isMathOn = function () { + return this.strictMath ? (this.parensStack && this.parensStack.length) : true; +}; + +contexts.evalEnv.prototype.isPathRelative = function (path) { + return !/^(?:[a-z-]+:|\/)/.test(path); +}; + +contexts.evalEnv.prototype.normalizePath = function( path ) { + var + segments = path.split("/").reverse(), + segment; + + path = []; + while (segments.length !== 0 ) { + segment = segments.pop(); + switch( segment ) { + case ".": + break; + case "..": + if ((path.length === 0) || (path[path.length - 1] === "..")) { + path.push( segment ); + } else { + path.pop(); + } + break; + default: + path.push( segment ); + break; + } + } + + return path.join("/"); +}; + +//todo - do the same for the toCSS env +//tree.toCSSEnv = function (options) { +//}; + + + +},{}],3:[function(require,module,exports){ +module.exports = { + 'aliceblue':'#f0f8ff', + 'antiquewhite':'#faebd7', + 'aqua':'#00ffff', + 'aquamarine':'#7fffd4', + 'azure':'#f0ffff', + 'beige':'#f5f5dc', + 'bisque':'#ffe4c4', + 'black':'#000000', + 'blanchedalmond':'#ffebcd', + 'blue':'#0000ff', + 'blueviolet':'#8a2be2', + 'brown':'#a52a2a', + 'burlywood':'#deb887', + 'cadetblue':'#5f9ea0', + 'chartreuse':'#7fff00', + 'chocolate':'#d2691e', + 'coral':'#ff7f50', + 'cornflowerblue':'#6495ed', + 'cornsilk':'#fff8dc', + 'crimson':'#dc143c', + 'cyan':'#00ffff', + 'darkblue':'#00008b', + 'darkcyan':'#008b8b', + 'darkgoldenrod':'#b8860b', + 'darkgray':'#a9a9a9', + 'darkgrey':'#a9a9a9', + 'darkgreen':'#006400', + 'darkkhaki':'#bdb76b', + 'darkmagenta':'#8b008b', + 'darkolivegreen':'#556b2f', + 'darkorange':'#ff8c00', + 'darkorchid':'#9932cc', + 'darkred':'#8b0000', + 'darksalmon':'#e9967a', + 'darkseagreen':'#8fbc8f', + 'darkslateblue':'#483d8b', + 'darkslategray':'#2f4f4f', + 'darkslategrey':'#2f4f4f', + 'darkturquoise':'#00ced1', + 'darkviolet':'#9400d3', + 'deeppink':'#ff1493', + 'deepskyblue':'#00bfff', + 'dimgray':'#696969', + 'dimgrey':'#696969', + 'dodgerblue':'#1e90ff', + 'firebrick':'#b22222', + 'floralwhite':'#fffaf0', + 'forestgreen':'#228b22', + 'fuchsia':'#ff00ff', + 'gainsboro':'#dcdcdc', + 'ghostwhite':'#f8f8ff', + 'gold':'#ffd700', + 'goldenrod':'#daa520', + 'gray':'#808080', + 'grey':'#808080', + 'green':'#008000', + 'greenyellow':'#adff2f', + 'honeydew':'#f0fff0', + 'hotpink':'#ff69b4', + 'indianred':'#cd5c5c', + 'indigo':'#4b0082', + 'ivory':'#fffff0', + 'khaki':'#f0e68c', + 'lavender':'#e6e6fa', + 'lavenderblush':'#fff0f5', + 'lawngreen':'#7cfc00', + 'lemonchiffon':'#fffacd', + 'lightblue':'#add8e6', + 'lightcoral':'#f08080', + 'lightcyan':'#e0ffff', + 'lightgoldenrodyellow':'#fafad2', + 'lightgray':'#d3d3d3', + 'lightgrey':'#d3d3d3', + 'lightgreen':'#90ee90', + 'lightpink':'#ffb6c1', + 'lightsalmon':'#ffa07a', + 'lightseagreen':'#20b2aa', + 'lightskyblue':'#87cefa', + 'lightslategray':'#778899', + 'lightslategrey':'#778899', + 'lightsteelblue':'#b0c4de', + 'lightyellow':'#ffffe0', + 'lime':'#00ff00', + 'limegreen':'#32cd32', + 'linen':'#faf0e6', + 'magenta':'#ff00ff', + 'maroon':'#800000', + 'mediumaquamarine':'#66cdaa', + 'mediumblue':'#0000cd', + 'mediumorchid':'#ba55d3', + 'mediumpurple':'#9370d8', + 'mediumseagreen':'#3cb371', + 'mediumslateblue':'#7b68ee', + 'mediumspringgreen':'#00fa9a', + 'mediumturquoise':'#48d1cc', + 'mediumvioletred':'#c71585', + 'midnightblue':'#191970', + 'mintcream':'#f5fffa', + 'mistyrose':'#ffe4e1', + 'moccasin':'#ffe4b5', + 'navajowhite':'#ffdead', + 'navy':'#000080', + 'oldlace':'#fdf5e6', + 'olive':'#808000', + 'olivedrab':'#6b8e23', + 'orange':'#ffa500', + 'orangered':'#ff4500', + 'orchid':'#da70d6', + 'palegoldenrod':'#eee8aa', + 'palegreen':'#98fb98', + 'paleturquoise':'#afeeee', + 'palevioletred':'#d87093', + 'papayawhip':'#ffefd5', + 'peachpuff':'#ffdab9', + 'peru':'#cd853f', + 'pink':'#ffc0cb', + 'plum':'#dda0dd', + 'powderblue':'#b0e0e6', + 'purple':'#800080', + 'red':'#ff0000', + 'rosybrown':'#bc8f8f', + 'royalblue':'#4169e1', + 'saddlebrown':'#8b4513', + 'salmon':'#fa8072', + 'sandybrown':'#f4a460', + 'seagreen':'#2e8b57', + 'seashell':'#fff5ee', + 'sienna':'#a0522d', + 'silver':'#c0c0c0', + 'skyblue':'#87ceeb', + 'slateblue':'#6a5acd', + 'slategray':'#708090', + 'slategrey':'#708090', + 'snow':'#fffafa', + 'springgreen':'#00ff7f', + 'steelblue':'#4682b4', + 'tan':'#d2b48c', + 'teal':'#008080', + 'thistle':'#d8bfd8', + 'tomato':'#ff6347', + 'turquoise':'#40e0d0', + 'violet':'#ee82ee', + 'wheat':'#f5deb3', + 'white':'#ffffff', + 'whitesmoke':'#f5f5f5', + 'yellow':'#ffff00', + 'yellowgreen':'#9acd32' +}; +},{}],4:[function(require,module,exports){ +module.exports = { + colors: require("./colors.js"), + unitConversions: require("./unit-conversions.js") +}; + +},{"./colors.js":3,"./unit-conversions.js":5}],5:[function(require,module,exports){ +module.exports = { + length: { + 'm': 1, + 'cm': 0.01, + 'mm': 0.001, + 'in': 0.0254, + 'px': 0.0254 / 96, + 'pt': 0.0254 / 72, + 'pc': 0.0254 / 72 * 12 + }, + duration: { + 's': 1, + 'ms': 0.001 + }, + angle: { + 'rad': 1/(2*Math.PI), + 'deg': 1/360, + 'grad': 1/400, + 'turn': 1 + } +}; +},{}],6:[function(require,module,exports){ +/*global window, XMLHttpRequest */ + +module.exports = function(options, isFileProtocol, log, logLevel) { + +var fileCache = {}; + +//TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load +// isFileProtocol is global + +function getXMLHttpRequest() { + if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !("ActiveXObject" in window))) { + return new XMLHttpRequest(); + } else { + try { + /*global ActiveXObject */ + return new ActiveXObject("Microsoft.XMLHTTP"); + } catch (e) { + log("browser doesn't support AJAX.", logLevel.errors); + return null; + } + } +} + +return { + // make generic but overriddable + warn: function warn(env, msg) { + console.warn(msg); + }, + // make generic but overriddable + getPath: function getPath(env, filename) { + var j = filename.lastIndexOf('/'); + if (j < 0) { + j = filename.lastIndexOf('\\'); + } + if (j < 0) { + return ""; + } + return filename.slice(0, j + 1); + }, + // make generic but overriddable + isPathAbsolute: function isPathAbsolute(env, filename) { + return /^(?:[a-z-]+:|\/|\\)/i.test(filename); + }, + alwaysMakePathsAbsolute: function alwaysMakePathsAbsolute() { + return true; + }, + getCleanCSS: function () { + }, + supportsDataURI: function() { + return false; + }, + pathDiff: function pathDiff(url, baseUrl) { + // diff between two paths to create a relative path + + var urlParts = this.extractUrlParts(url), + baseUrlParts = this.extractUrlParts(baseUrl), + i, max, urlDirectories, baseUrlDirectories, diff = ""; + if (urlParts.hostPart !== baseUrlParts.hostPart) { + return ""; + } + max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); + for(i = 0; i < max; i++) { + if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } + } + baseUrlDirectories = baseUrlParts.directories.slice(i); + urlDirectories = urlParts.directories.slice(i); + for(i = 0; i < baseUrlDirectories.length-1; i++) { + diff += "../"; + } + for(i = 0; i < urlDirectories.length-1; i++) { + diff += urlDirectories[i] + "/"; + } + return diff; + }, + join: function join(basePath, laterPath) { + if (!basePath) { + return laterPath; + } + return this.extractUrlParts(laterPath, basePath).path; + }, + // helper function, not part of API + extractUrlParts: function extractUrlParts(url, baseUrl) { + // urlParts[1] = protocol&hostname || / + // urlParts[2] = / if path relative to host base + // urlParts[3] = directories + // urlParts[4] = filename + // urlParts[5] = parameters + + var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, + urlParts = url.match(urlPartsRegex), + returner = {}, directories = [], i, baseUrlParts; + + if (!urlParts) { + throw new Error("Could not parse sheet href - '"+url+"'"); + } + + // Stylesheets in IE don't always return the full path + if (!urlParts[1] || urlParts[2]) { + baseUrlParts = baseUrl.match(urlPartsRegex); + if (!baseUrlParts) { + throw new Error("Could not parse page url - '"+baseUrl+"'"); + } + urlParts[1] = urlParts[1] || baseUrlParts[1] || ""; + if (!urlParts[2]) { + urlParts[3] = baseUrlParts[3] + urlParts[3]; + } + } + + if (urlParts[3]) { + directories = urlParts[3].replace(/\\/g, "/").split("/"); + + // extract out . before .. so .. doesn't absorb a non-directory + for(i = 0; i < directories.length; i++) { + if (directories[i] === ".") { + directories.splice(i, 1); + i -= 1; + } + } + + for(i = 0; i < directories.length; i++) { + if (directories[i] === ".." && i > 0) { + directories.splice(i-1, 2); + i -= 2; + } + } + } + + returner.hostPart = urlParts[1]; + returner.directories = directories; + returner.path = urlParts[1] + directories.join("/"); + returner.fileUrl = returner.path + (urlParts[4] || ""); + returner.url = returner.fileUrl + (urlParts[5] || ""); + return returner; + }, + doXHR: function doXHR(url, type, callback, errback) { + + var xhr = getXMLHttpRequest(); + var async = isFileProtocol ? options.fileAsync : options.async; + + if (typeof(xhr.overrideMimeType) === 'function') { + xhr.overrideMimeType('text/css'); + } + log("XHR: Getting '" + url + "'", logLevel.debug); + xhr.open('GET', url, async); + xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); + xhr.send(null); + + function handleResponse(xhr, callback, errback) { + if (xhr.status >= 200 && xhr.status < 300) { + callback(xhr.responseText, + xhr.getResponseHeader("Last-Modified")); + } else if (typeof(errback) === 'function') { + errback(xhr.status, url); + } + } + + if (isFileProtocol && !options.fileAsync) { + if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { + callback(xhr.responseText); + } else { + errback(xhr.status, url); + } + } else if (async) { + xhr.onreadystatechange = function () { + if (xhr.readyState == 4) { + handleResponse(xhr, callback, errback); + } + }; + } else { + handleResponse(xhr, callback, errback); + } + }, + loadFile: function loadFile(env, filename, currentDirectory, callback) { + if (currentDirectory && !this.isPathAbsolute(env, filename)) { + filename = currentDirectory + filename; + } + + // sheet may be set to the stylesheet for the initial load or a collection of properties including + // some env variables for imports + var hrefParts = this.extractUrlParts(filename, window.location.href); + var href = hrefParts.url; + + if (env.useFileCache && fileCache[href]) { + try { + var lessText = fileCache[href]; + callback(null, lessText, href, { lastModified: new Date() }); + } catch (e) { + callback(e, null, href); + } + return; + } + + this.doXHR(href, env.mime, function doXHRCallback(data, lastModified) { + // per file cache + fileCache[href] = data; + + // Use remote copy (re-parse) + callback(null, data, href, { lastModified: lastModified }); + }, function doXHRError(status, url) { + callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href); + }); + + } +}; + +}; + +},{}],7:[function(require,module,exports){ +var Color = require("../tree/color.js"), + functionRegistry = require("./function-registry.js"); + +// Color Blending +// ref: http://www.w3.org/TR/compositing-1 + +function colorBlend(mode, color1, color2) { + var ab = color1.alpha, cb, // backdrop + as = color2.alpha, cs, // source + ar, cr, r = []; // result + + ar = as + ab * (1 - as); + for (var i = 0; i < 3; i++) { + cb = color1.rgb[i] / 255; + cs = color2.rgb[i] / 255; + cr = mode(cb, cs); + if (ar) { + cr = (as * cs + ab * (cb - + as * (cb + cs - cr))) / ar; + } + r[i] = cr * 255; + } + + return new(Color)(r, ar); +} + +var colorBlendModeFunctions = { + multiply: function(cb, cs) { + return cb * cs; + }, + screen: function(cb, cs) { + return cb + cs - cb * cs; + }, + overlay: function(cb, cs) { + cb *= 2; + return (cb <= 1) + ? colorBlendModeFunctions.multiply(cb, cs) + : colorBlendModeFunctions.screen(cb - 1, cs); + }, + softlight: function(cb, cs) { + var d = 1, e = cb; + if (cs > 0.5) { + e = 1; + d = (cb > 0.25) ? Math.sqrt(cb) + : ((16 * cb - 12) * cb + 4) * cb; + } + return cb - (1 - 2 * cs) * e * (d - cb); + }, + hardlight: function(cb, cs) { + return colorBlendModeFunctions.overlay(cs, cb); + }, + difference: function(cb, cs) { + return Math.abs(cb - cs); + }, + exclusion: function(cb, cs) { + return cb + cs - 2 * cb * cs; + }, + + // non-w3c functions: + average: function(cb, cs) { + return (cb + cs) / 2; + }, + negation: function(cb, cs) { + return 1 - Math.abs(cb + cs - 1); + } +}; + +for (var f in colorBlendModeFunctions) { + if (colorBlendModeFunctions.hasOwnProperty(f)) { + colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]); + } +} + +functionRegistry.addMultiple(colorBlend); + +},{"../tree/color.js":31,"./function-registry.js":12}],8:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + functionRegistry = require("./function-registry.js"), + colorFunctions; + +function clamp(val) { + return Math.min(1, Math.max(0, val)); +} +function hsla(color) { + return colorFunctions.hsla(color.h, color.s, color.l, color.a); +} +function number(n) { + if (n instanceof Dimension) { + return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); + } else if (typeof(n) === 'number') { + return n; + } else { + throw { + error: "RuntimeError", + message: "color functions take numbers as parameters" + }; + } +} +function scaled(n, size) { + if (n instanceof Dimension && n.unit.is('%')) { + return parseFloat(n.value * size / 100); + } else { + return number(n); + } +} +colorFunctions = { + rgb: function (r, g, b) { + return colorFunctions.rgba(r, g, b, 1.0); + }, + rgba: function (r, g, b, a) { + var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); + a = number(a); + return new(Color)(rgb, a); + }, + hsl: function (h, s, l) { + return colorFunctions.hsla(h, s, l, 1.0); + }, + hsla: function (h, s, l, a) { + function hue(h) { + h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); + if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } + else if (h * 2 < 1) { return m2; } + else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } + else { return m1; } + } + + h = (number(h) % 360) / 360; + s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); + + var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + var m1 = l * 2 - m2; + + return colorFunctions.rgba(hue(h + 1/3) * 255, + hue(h) * 255, + hue(h - 1/3) * 255, + a); + }, + + hsv: function(h, s, v) { + return colorFunctions.hsva(h, s, v, 1.0); + }, + + hsva: function(h, s, v, a) { + h = ((number(h) % 360) / 360) * 360; + s = number(s); v = number(v); a = number(a); + + var i, f; + i = Math.floor((h / 60) % 6); + f = (h / 60) - i; + + var vs = [v, + v * (1 - s), + v * (1 - f * s), + v * (1 - (1 - f) * s)]; + var perm = [[0, 3, 1], + [2, 0, 1], + [1, 0, 3], + [1, 2, 0], + [3, 1, 0], + [0, 1, 2]]; + + return colorFunctions.rgba(vs[perm[i][0]] * 255, + vs[perm[i][1]] * 255, + vs[perm[i][2]] * 255, + a); + }, + + hue: function (color) { + return new(Dimension)(color.toHSL().h); + }, + saturation: function (color) { + return new(Dimension)(color.toHSL().s * 100, '%'); + }, + lightness: function (color) { + return new(Dimension)(color.toHSL().l * 100, '%'); + }, + hsvhue: function(color) { + return new(Dimension)(color.toHSV().h); + }, + hsvsaturation: function (color) { + return new(Dimension)(color.toHSV().s * 100, '%'); + }, + hsvvalue: function (color) { + return new(Dimension)(color.toHSV().v * 100, '%'); + }, + red: function (color) { + return new(Dimension)(color.rgb[0]); + }, + green: function (color) { + return new(Dimension)(color.rgb[1]); + }, + blue: function (color) { + return new(Dimension)(color.rgb[2]); + }, + alpha: function (color) { + return new(Dimension)(color.toHSL().a); + }, + luma: function (color) { + return new(Dimension)(color.luma() * color.alpha * 100, '%'); + }, + luminance: function (color) { + var luminance = + (0.2126 * color.rgb[0] / 255) + + (0.7152 * color.rgb[1] / 255) + + (0.0722 * color.rgb[2] / 255); + + return new(Dimension)(luminance * color.alpha * 100, '%'); + }, + saturate: function (color, amount) { + // filter: saturate(3.2); + // should be kept as is, so check for color + if (!color.rgb) { + return null; + } + var hsl = color.toHSL(); + + hsl.s += amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + desaturate: function (color, amount) { + var hsl = color.toHSL(); + + hsl.s -= amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + lighten: function (color, amount) { + var hsl = color.toHSL(); + + hsl.l += amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + darken: function (color, amount) { + var hsl = color.toHSL(); + + hsl.l -= amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + fadein: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a += amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + fadeout: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a -= amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + fade: function (color, amount) { + var hsl = color.toHSL(); + + hsl.a = amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + spin: function (color, amount) { + var hsl = color.toHSL(); + var hue = (hsl.h + amount.value) % 360; + + hsl.h = hue < 0 ? 360 + hue : hue; + + return hsla(hsl); + }, + // + // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein + // http://sass-lang.com + // + mix: function (color1, color2, weight) { + if (!weight) { + weight = new(Dimension)(50); + } + var p = weight.value / 100.0; + var w = p * 2 - 1; + var a = color1.toHSL().a - color2.toHSL().a; + + var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, + color1.rgb[1] * w1 + color2.rgb[1] * w2, + color1.rgb[2] * w1 + color2.rgb[2] * w2]; + + var alpha = color1.alpha * p + color2.alpha * (1 - p); + + return new(Color)(rgb, alpha); + }, + greyscale: function (color) { + return colorFunctions.desaturate(color, new(Dimension)(100)); + }, + contrast: function (color, dark, light, threshold) { + // filter: contrast(3.2); + // should be kept as is, so check for color + if (!color.rgb) { + return null; + } + if (typeof light === 'undefined') { + light = colorFunctions.rgba(255, 255, 255, 1.0); + } + if (typeof dark === 'undefined') { + dark = colorFunctions.rgba(0, 0, 0, 1.0); + } + //Figure out which is actually light and dark! + if (dark.luma() > light.luma()) { + var t = light; + light = dark; + dark = t; + } + if (typeof threshold === 'undefined') { + threshold = 0.43; + } else { + threshold = number(threshold); + } + if (color.luma() < threshold) { + return light; + } else { + return dark; + } + }, + argb: function (color) { + return new(Anonymous)(color.toARGB()); + }, + color: function(c) { + if ((c instanceof Quoted) && + (/^#([a-f0-9]{6}|[a-f0-9]{3})$/i.test(c.value))) { + return new(Color)(c.value.slice(1)); + } + if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) { + c.keyword = undefined; + return c; + } + throw { + type: "Argument", + message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" + }; + }, + tint: function(color, amount) { + return colorFunctions.mix(colorFunctions.rgb(255,255,255), color, amount); + }, + shade: function(color, amount) { + return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount); + } +}; +functionRegistry.addMultiple(colorFunctions); + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/quoted.js":54,"./function-registry.js":12}],9:[function(require,module,exports){ +module.exports = function(environment) { + var Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + functionRegistry = require("./function-registry.js"); + + functionRegistry.add("data-uri", function(mimetypeNode, filePathNode) { + + if (!environment.supportsDataURI(this.env)) { + return new URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); + } + + var mimetype = mimetypeNode.value; + var filePath = (filePathNode && filePathNode.value); + + var useBase64 = false; + + if (arguments.length < 2) { + filePath = mimetype; + } + + var fragmentStart = filePath.indexOf('#'); + var fragment = ''; + if (fragmentStart!==-1) { + fragment = filePath.slice(fragmentStart); + filePath = filePath.slice(0, fragmentStart); + } + + if (this.env.isPathRelative(filePath)) { + if (this.currentFileInfo.relativeUrls) { + filePath = environment.join(this.currentFileInfo.currentDirectory, filePath); + } else { + filePath = environment.join(this.currentFileInfo.entryPath, filePath); + } + } + + // detect the mimetype if not given + if (arguments.length < 2) { + + mimetype = environment.mimeLookup(this.env, filePath); + + // use base 64 unless it's an ASCII or UTF-8 format + var charset = environment.charsetLookup(this.env, mimetype); + useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; + if (useBase64) { mimetype += ';base64'; } + } + else { + useBase64 = /;base64$/.test(mimetype); + } + + var buf = environment.readFileSync(filePath); + + // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded + // and the --ieCompat flag is enabled, return a normal url() instead. + var DATA_URI_MAX_KB = 32, + fileSizeInKB = parseInt((buf.length / 1024), 10); + if (fileSizeInKB >= DATA_URI_MAX_KB) { + + if (this.env.ieCompat !== false) { + if (!this.env.silent) { + console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB); + } + + return new URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); + } + } + + buf = useBase64 ? buf.toString('base64') + : encodeURIComponent(buf); + + var uri = "\"data:" + mimetype + ',' + buf + fragment + "\""; + return new(URL)(new(Anonymous)(uri)); + }); +}; + +},{"../tree/anonymous.js":27,"../tree/url.js":61,"./function-registry.js":12}],10:[function(require,module,exports){ +var Keyword = require("../tree/keyword.js"), + functionRegistry = require("./function-registry.js"); + +var defaultFunc = { + eval: function () { + var v = this.value_, e = this.error_; + if (e) { + throw e; + } + if (v != null) { + return v ? Keyword.True : Keyword.False; + } + }, + value: function (v) { + this.value_ = v; + }, + error: function (e) { + this.error_ = e; + }, + reset: function () { + this.value_ = this.error_ = null; + } +}; + +functionRegistry.add("default", defaultFunc.eval.bind(defaultFunc)); + +module.exports = defaultFunc; + +},{"../tree/keyword.js":46,"./function-registry.js":12}],11:[function(require,module,exports){ +var functionRegistry = require("./function-registry.js"); + +var functionCaller = function(name, env, currentFileInfo) { + this.name = name.toLowerCase(); + this.function = functionRegistry.get(this.name); + this.env = env; + this.currentFileInfo = currentFileInfo; +}; +functionCaller.prototype.isValid = function() { + return Boolean(this.function); +}; +functionCaller.prototype.call = function(args) { + return this.function.apply(this, args); +}; + +module.exports = functionCaller; + +},{"./function-registry.js":12}],12:[function(require,module,exports){ +module.exports = { + _data: {}, + add: function(name, func) { + if (this._data.hasOwnProperty(name)) { + //TODO warn + } + this._data[name] = func; + }, + addMultiple: function(functions) { + Object.keys(functions).forEach( + function(name) { + this.add(name, functions[name]); + }.bind(this)); + }, + get: function(name) { + return this._data[name]; + } +}; + +},{}],13:[function(require,module,exports){ +module.exports = function(environment) { + var functions = { + functionRegistry: require("./function-registry.js"), + functionCaller: require("./function-caller.js") + }; + + //register functions + require("./default.js"); + require("./color.js"); + require("./color-blending.js"); + require("./data-uri.js")(environment); + require("./math.js"); + require("./number.js"); + require("./string.js"); + require("./svg.js")(environment); + require("./types.js"); + + return functions; +}; + +},{"./color-blending.js":7,"./color.js":8,"./data-uri.js":9,"./default.js":10,"./function-caller.js":11,"./function-registry.js":12,"./math.js":14,"./number.js":15,"./string.js":16,"./svg.js":17,"./types.js":18}],14:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + functionRegistry = require("./function-registry.js"); + +var mathFunctions = { + // name, unit + ceil: null, + floor: null, + sqrt: null, + abs: null, + tan: "", + sin: "", + cos: "", + atan: "rad", + asin: "rad", + acos: "rad" +}; + +function _math(fn, unit, n) { + if (!(n instanceof Dimension)) { + throw { type: "Argument", message: "argument must be a number" }; + } + if (unit == null) { + unit = n.unit; + } else { + n = n.unify(); + } + return new(Dimension)(fn(parseFloat(n.value)), unit); +} + +for (var f in mathFunctions) { + if (mathFunctions.hasOwnProperty(f)) { + mathFunctions[f] = _math.bind(null, Math[f], mathFunctions[f]); + } +} + +mathFunctions.round = function (n, f) { + var fraction = typeof(f) === "undefined" ? 0 : f.value; + return _math(function(num) { return num.toFixed(fraction); }, null, n); +}; + +functionRegistry.addMultiple(mathFunctions); + +},{"../tree/dimension.js":37,"./function-registry.js":12}],15:[function(require,module,exports){ +var Dimension = require("../tree/dimension.js"), + Anonymous = require("../tree/anonymous.js"), + functionRegistry = require("./function-registry.js"); + +var minMax = function (isMin, args) { + args = Array.prototype.slice.call(args); + switch(args.length) { + case 0: throw { type: "Argument", message: "one or more arguments required" }; + } + var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, + order = [], // elems only contains original argument values. + values = {}; // key is the unit.toString() for unified Dimension values, + // value is the index into the order array. + for (i = 0; i < args.length; i++) { + current = args[i]; + if (!(current instanceof Dimension)) { + if(Array.isArray(args[i].value)) { + Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value)); + } + continue; + } + currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new(Dimension)(current.value, unitClone).unify() : current.unify(); + unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString(); + unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic; + unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone; + j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit]; + if (j === undefined) { + if(unitStatic !== undefined && unit !== unitStatic) { + throw{ type: "Argument", message: "incompatible types" }; + } + values[unit] = order.length; + order.push(current); + continue; + } + referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new(Dimension)(order[j].value, unitClone).unify() : order[j].unify(); + if ( isMin && currentUnified.value < referenceUnified.value || + !isMin && currentUnified.value > referenceUnified.value) { + order[j] = current; + } + } + if (order.length == 1) { + return order[0]; + } + args = order.map(function (a) { return a.toCSS(this.env); }).join(this.env.compress ? "," : ", "); + return new(Anonymous)((isMin ? "min" : "max") + "(" + args + ")"); +}; +functionRegistry.addMultiple({ + min: function () { + return minMax(true, arguments); + }, + max: function () { + return minMax(false, arguments); + }, + convert: function (val, unit) { + return val.convertTo(unit.value); + }, + pi: function () { + return new(Dimension)(Math.PI); + }, + mod: function(a, b) { + return new(Dimension)(a.value % b.value, a.unit); + }, + pow: function(x, y) { + if (typeof x === "number" && typeof y === "number") { + x = new(Dimension)(x); + y = new(Dimension)(y); + } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) { + throw { type: "Argument", message: "arguments must be numbers" }; + } + + return new(Dimension)(Math.pow(x.value, y.value), x.unit); + }, + percentage: function (n) { + return new(Dimension)(n.value * 100, '%'); + } +}); + +},{"../tree/anonymous.js":27,"../tree/dimension.js":37,"./function-registry.js":12}],16:[function(require,module,exports){ +var Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + JavaScript = require("../tree/javascript.js"), + functionRegistry = require("./function-registry.js"); + +functionRegistry.addMultiple({ + e: function (str) { + return new(Anonymous)(str instanceof JavaScript ? str.evaluated : str.value); + }, + escape: function (str) { + return new(Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); + }, + replace: function (string, pattern, replacement, flags) { + var result = string.value; + + result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement.value); + return new(Quoted)(string.quote || '', result, string.escaped); + }, + '%': function (string /* arg, arg, ...*/) { + var args = Array.prototype.slice.call(arguments, 1), + result = string.value; + + for (var i = 0; i < args.length; i++) { + /*jshint loopfunc:true */ + result = result.replace(/%[sda]/i, function(token) { + var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); + return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; + }); + } + result = result.replace(/%%/g, '%'); + return new(Quoted)(string.quote || '', result, string.escaped); + } +}); + +},{"../tree/anonymous.js":27,"../tree/javascript.js":44,"../tree/quoted.js":54,"./function-registry.js":12}],17:[function(require,module,exports){ +module.exports = function(environment) { + var Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + functionRegistry = require("./function-registry.js"); + + functionRegistry.add("svg-gradient", function(direction) { + + function throwArgumentDescriptor() { + throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" }; + } + + if (arguments.length < 3) { + throwArgumentDescriptor(); + } + var stops = Array.prototype.slice.call(arguments, 1), + gradientDirectionSvg, + gradientType = "linear", + rectangleDimension = 'x="0" y="0" width="1" height="1"', + useBase64 = true, + renderEnv = {compress: false}, + returner, + directionValue = direction.toCSS(renderEnv), + i, color, position, positionValue, alpha; + + switch (directionValue) { + case "to bottom": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; + break; + case "to right": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; + break; + case "to bottom right": + gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; + break; + case "to top right": + gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; + break; + case "ellipse": + case "ellipse at center": + gradientType = "radial"; + gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; + rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; + break; + default: + throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" }; + } + returner = '' + + '' + + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; + + for (i = 0; i < stops.length; i+= 1) { + if (stops[i].value) { + color = stops[i].value[0]; + position = stops[i].value[1]; + } else { + color = stops[i]; + position = undefined; + } + + if (!(color instanceof Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof Dimension))) { + throwArgumentDescriptor(); + } + positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%"; + alpha = color.alpha; + returner += ''; + } + returner += '' + + ''; + + if (useBase64) { + try { + returner = environment.encodeBase64(this.env, returner); + } catch(e) { + useBase64 = false; + } + } + + returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'"; + return new(URL)(new(Anonymous)(returner)); + }); +}; + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/url.js":61,"./function-registry.js":12}],18:[function(require,module,exports){ +var Keyword = require("../tree/keyword.js"), + Dimension = require("../tree/dimension.js"), + Color = require("../tree/color.js"), + Quoted = require("../tree/quoted.js"), + Anonymous = require("../tree/anonymous.js"), + URL = require("../tree/url.js"), + Operation = require("../tree/operation.js"), + functionRegistry = require("./function-registry.js"); + +var isa = function (n, Type) { + return (n instanceof Type) ? Keyword.True : Keyword.False; + }, + isunit = function (n, unit) { + return (n instanceof Dimension) && n.unit.is(unit.value || unit) ? Keyword.True : Keyword.False; + }; +functionRegistry.addMultiple({ + iscolor: function (n) { + return isa(n, Color); + }, + isnumber: function (n) { + return isa(n, Dimension); + }, + isstring: function (n) { + return isa(n, Quoted); + }, + iskeyword: function (n) { + return isa(n, Keyword); + }, + isurl: function (n) { + return isa(n, URL); + }, + ispixel: function (n) { + return isunit(n, 'px'); + }, + ispercentage: function (n) { + return isunit(n, '%'); + }, + isem: function (n) { + return isunit(n, 'em'); + }, + isunit: isunit, + unit: function (val, unit) { + if(!(val instanceof Dimension)) { + throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof Operation ? ". Have you forgotten parenthesis?" : "") }; + } + if (unit) { + if (unit instanceof Keyword) { + unit = unit.value; + } else { + unit = unit.toCSS(); + } + } else { + unit = ""; + } + return new(Dimension)(val.value, unit); + }, + "get-unit": function (n) { + return new(Anonymous)(n.unit); + }, + extract: function(values, index) { + index = index.value - 1; // (1-based index) + // handle non-array values as an array of length 1 + // return 'undefined' if index is invalid + return Array.isArray(values.value) ? + values.value[index] : Array(values)[index]; + }, + length: function(values) { + var n = Array.isArray(values.value) ? values.value.length : 1; + return new Dimension(n); + } +}); + +},{"../tree/anonymous.js":27,"../tree/color.js":31,"../tree/dimension.js":37,"../tree/keyword.js":46,"../tree/operation.js":52,"../tree/quoted.js":54,"../tree/url.js":61,"./function-registry.js":12}],19:[function(require,module,exports){ + +var LessError = module.exports = function LessError(parser, e, env) { + var input = parser.getInput(e, env), + loc = parser.getLocation(e.index, input), + line = loc.line, + col = loc.column, + callLine = e.call && parser.getLocation(e.call, input).line, + lines = input.split('\n'); + + this.type = e.type || 'Syntax'; + this.message = e.message; + this.filename = e.filename || env.currentFileInfo.filename; + this.index = e.index; + this.line = typeof(line) === 'number' ? line + 1 : null; + this.callLine = callLine + 1; + this.callExtract = lines[callLine]; + this.stack = e.stack; + this.column = col; + this.extract = [ + lines[line - 1], + lines[line], + lines[line + 1] + ]; +}; + +LessError.prototype = new Error(); +LessError.prototype.constructor = LessError; + +},{}],20:[function(require,module,exports){ +module.exports = function(environment) { + var less = { + version: [2, 0, 0], + data: require('./data/index.js'), + tree: require('./tree/index.js'), + visitor: require('./visitor/index.js'), + Parser: require('./parser/parser.js')(environment), + functions: require('./functions/index.js')(environment), + contexts: require("./contexts.js"), + environment: environment + }; + + return less; +}; + +},{"./contexts.js":2,"./data/index.js":4,"./functions/index.js":13,"./parser/parser.js":24,"./tree/index.js":43,"./visitor/index.js":66}],21:[function(require,module,exports){ +// Split the input into chunks. +module.exports = function (input, fail) { + var len = input.length, level = 0, parenLevel = 0, + lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, + chunks = [], emitFrom = 0, + chunkerCurrentIndex, currentChunkStartIndex, cc, cc2, matched; + + function emitChunk(force) { + var len = chunkerCurrentIndex - emitFrom; + if (((len < 512) && !force) || !len) { + return; + } + chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1)); + emitFrom = chunkerCurrentIndex + 1; + } + + for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc = input.charCodeAt(chunkerCurrentIndex); + if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { + // a-z or whitespace + continue; + } + + switch (cc) { + case 40: // ( + parenLevel++; + lastOpeningParen = chunkerCurrentIndex; + continue; + case 41: // ) + if (--parenLevel < 0) { + return fail("missing opening `(`", chunkerCurrentIndex); + } + continue; + case 59: // ; + if (!parenLevel) { emitChunk(); } + continue; + case 123: // { + level++; + lastOpening = chunkerCurrentIndex; + continue; + case 125: // } + if (--level < 0) { + return fail("missing opening `{`", chunkerCurrentIndex); + } + if (!level && !parenLevel) { emitChunk(); } + continue; + case 92: // \ + if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; } + return fail("unescaped `\\`", chunkerCurrentIndex); + case 34: + case 39: + case 96: // ", ' and ` + matched = 0; + currentChunkStartIndex = chunkerCurrentIndex; + for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if (cc2 > 96) { continue; } + if (cc2 == cc) { matched = 1; break; } + if (cc2 == 92) { // \ + if (chunkerCurrentIndex == len - 1) { + return fail("unescaped `\\`", chunkerCurrentIndex); + } + chunkerCurrentIndex++; + } + } + if (matched) { continue; } + return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); + case 47: // /, check for comment + if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; } + cc2 = input.charCodeAt(chunkerCurrentIndex + 1); + if (cc2 == 47) { + // //, find lnfeed + for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } + } + } else if (cc2 == 42) { + // /*, find */ + lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex; + for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) { + cc2 = input.charCodeAt(chunkerCurrentIndex); + if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; } + if (cc2 != 42) { continue; } + if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; } + } + if (chunkerCurrentIndex == len - 1) { + return fail("missing closing `*/`", currentChunkStartIndex); + } + chunkerCurrentIndex++; + } + continue; + case 42: // *, check for unmatched */ + if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) { + return fail("unmatched `/*`", chunkerCurrentIndex); + } + continue; + } + } + + if (level !== 0) { + if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { + return fail("missing closing `}` or `*/`", lastOpening); + } else { + return fail("missing closing `}`", lastOpening); + } + } else if (parenLevel !== 0) { + return fail("missing closing `)`", lastOpeningParen); + } + + emitChunk(true); + return chunks; +}; + +},{}],22:[function(require,module,exports){ +var contexts = require("../contexts.js"); +module.exports = function(environment, env, Parser) { + var rootFilename = env && env.filename; + return { + paths: env.paths || [], // Search paths, when importing + queue: [], // Files which haven't been imported yet + files: env.files, // Holds the imported parse trees + contents: env.contents, // Holds the imported file contents + contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less + mime: env.mime, // MIME type of .less files + error: null, // Error in parsing/evaluating an import + push: function (path, currentFileInfo, importOptions, callback) { + var parserImports = this; + this.queue.push(path); + + var fileParsedFunc = function (e, root, fullPath) { + parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue + + var importedPreviously = fullPath === rootFilename; + + parserImports.files[fullPath] = root; // Store the root + + if (e && !parserImports.error) { parserImports.error = e; } + + callback(e, root, importedPreviously, fullPath); + }; + + var newFileInfo = { + relativeUrls: env.relativeUrls, + entryPath: currentFileInfo.entryPath, + rootpath: currentFileInfo.rootpath, + rootFilename: currentFileInfo.rootFilename + }; + + environment.loadFile(env, path, currentFileInfo.currentDirectory, function loadFileCallback(e, contents, resolvedFilename) { + if (e) { + fileParsedFunc(e); + return; + } + + // Pass on an updated rootpath if path of imported file is relative and file + // is in a (sub|sup) directory + // + // Examples: + // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/', + // then rootpath should become 'less/module/nav/' + // - If path of imported file is '../mixins.less' and rootpath is 'less/', + // then rootpath should become 'less/../' + newFileInfo.currentDirectory = environment.getPath(env, resolvedFilename); + if(newFileInfo.relativeUrls) { + newFileInfo.rootpath = environment.join((env.rootpath || ""), environment.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath)); + if (!environment.isPathAbsolute(env, newFileInfo.rootpath) && environment.alwaysMakePathsAbsolute()) { + newFileInfo.rootpath = environment.join(newFileInfo.entryPath, newFileInfo.rootpath); + } + } + newFileInfo.filename = resolvedFilename; + + var newEnv = new contexts.parseEnv(env); + + newEnv.currentFileInfo = newFileInfo; + newEnv.processImports = false; + newEnv.contents[resolvedFilename] = contents; + + if (currentFileInfo.reference || importOptions.reference) { + newFileInfo.reference = true; + } + + if (importOptions.inline) { + fileParsedFunc(null, contents, resolvedFilename); + } else { + new(Parser)(newEnv).parse(contents, function (e, root) { + fileParsedFunc(e, root, resolvedFilename); + }); + } + }); + } + }; +}; + +},{"../contexts.js":2}],23:[function(require,module,exports){ +var chunker = require('./chunker.js'), + LessError = require('../less-error.js'); +module.exports = function() { + var input, // LeSS input string + j, // current chunk + saveStack = [], // holds state for backtracking + furthest, // furthest index the parser has gone to + furthestPossibleErrorMessage,// if this is furthest we got to, this is the probably cause + chunks, // chunkified input + current, // current chunk + currentPos, // index of current chunk, in `input` + parserInput = {}; + + parserInput.save = function() { + currentPos = parserInput.i; + saveStack.push( { current: current, i: parserInput.i, j: j }); + }; + parserInput.restore = function(possibleErrorMessage) { + if (parserInput.i > furthest) { + furthest = parserInput.i; + furthestPossibleErrorMessage = possibleErrorMessage; + } + var state = saveStack.pop(); + current = state.current; + currentPos = parserInput.i = state.i; + j = state.j; + }; + parserInput.forget = function() { + saveStack.pop(); + }; + function sync() { + if (parserInput.i > currentPos) { + current = current.slice(parserInput.i - currentPos); + currentPos = parserInput.i; + } + } + parserInput.isWhitespace = function (offset) { + var pos = parserInput.i + (offset || 0), + code = input.charCodeAt(pos); + return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF); + }; + // + // Parse from a token, regexp or string, and move forward if match + // + parserInput.$ = function(tok) { + var tokType = typeof tok, + match, length; + + // Either match a single character in the input, + // or match a regexp in the current chunk (`current`). + // + if (tokType === "string") { + if (input.charAt(parserInput.i) !== tok) { + return null; + } + skipWhitespace(1); + return tok; + } + + // regexp + sync(); + if (! (match = tok.exec(current))) { + return null; + } + + length = match[0].length; + + // The match is confirmed, add the match length to `i`, + // and consume any extra white-space characters (' ' || '\n') + // which come after that. The reason for this is that LeSS's + // grammar is mostly white-space insensitive. + // + skipWhitespace(length); + + if(typeof(match) === 'string') { + return match; + } else { + return match.length === 1 ? match[0] : match; + } + }; + + // Specialization of $(tok) + parserInput.$re = function(tok) { + if (parserInput.i > currentPos) { + current = current.slice(parserInput.i - currentPos); + currentPos = parserInput.i; + } + var m = tok.exec(current); + if (!m) { + return null; + } + + skipWhitespace(m[0].length); + if(typeof m === "string") { + return m; + } + + return m.length === 1 ? m[0] : m; + }; + + // Specialization of $(tok) + parserInput.$char = function(tok) { + if (input.charAt(parserInput.i) !== tok) { + return null; + } + skipWhitespace(1); + return tok; + }; + + var CHARCODE_SPACE = 32, + CHARCODE_TAB = 9, + CHARCODE_LF = 10, + CHARCODE_CR = 13, + CHARCODE_PLUS = 43, + CHARCODE_COMMA = 44, + CHARCODE_FORWARD_SLASH = 47, + CHARCODE_9 = 57; + + parserInput.autoCommentAbsorb = true; + parserInput.commentStore = []; + parserInput.finished = false; + + var skipWhitespace = function(length) { + var oldi = parserInput.i, oldj = j, + curr = parserInput.i - currentPos, + endIndex = parserInput.i + current.length - curr, + mem = (parserInput.i += length), + inp = input, + c, nextChar, comment; + + for (; parserInput.i < endIndex; parserInput.i++) { + c = inp.charCodeAt(parserInput.i); + + if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) { + nextChar = inp[parserInput.i + 1]; + if (nextChar === '/') { + comment = {index: parserInput.i, isLineComment: true}; + var nextNewLine = inp.indexOf("\n", parserInput.i + 1); + if (nextNewLine < 0) { + nextNewLine = endIndex; + } + parserInput.i = nextNewLine; + comment.text = inp.substr(comment.i, parserInput.i - comment.i); + parserInput.commentStore.push(comment); + continue; + } else if (nextChar === '*') { + var haystack = inp.substr(parserInput.i); + var comment_search_result = haystack.match(/^\/\*(?:[^*]|\*+[^\/*])*\*+\//); + if (comment_search_result) { + comment = { + index: parserInput.i, + text: comment_search_result[0], + isLineComment: false + }; + parserInput.i += comment.text.length - 1; + parserInput.commentStore.push(comment); + continue; + } + } + break; + } + + if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) { + break; + } + } + + current = current.slice(length + parserInput.i - mem + curr); + currentPos = parserInput.i; + + if (!current.length) { + if (j < chunks.length - 1) + { + current = chunks[++j]; + skipWhitespace(0); // skip space at the beginning of a chunk + return true; // things changed + } + parserInput.finished = true; + } + + return oldi !== parserInput.i || oldj !== j; + }; + + // Same as $(), but don't change the state of the parser, + // just return the match. + parserInput.peek = function(tok) { + if (typeof(tok) === 'string') { + return input.charAt(parserInput.i) === tok; + } else { + return tok.test(current); + } + }; + + // Specialization of peek() + // TODO remove or change some currentChar calls to peekChar + parserInput.peekChar = function(tok) { + return input.charAt(parserInput.i) === tok; + }; + + parserInput.currentChar = function() { + return input.charAt(parserInput.i); + }; + + parserInput.getInput = function() { + return input; + }; + + parserInput.peekNotNumeric = function() { + var c = input.charCodeAt(parserInput.i); + //Is the first char of the dimension 0-9, '.', '+' or '-' + return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA; + }; + + parserInput.getLocation = function(index, inputStream) { + inputStream = inputStream == null ? input : inputStream; + + var n = index + 1, + line = null, + column = -1; + + while (--n >= 0 && inputStream.charAt(n) !== '\n') { + column++; + } + + if (typeof index === 'number') { + line = (inputStream.slice(0, index).match(/\n/g) || "").length; + } + + return { + line: line, + column: column + }; + }; + + parserInput.start = function(str, chunkInput, parser, env) { + input = str; + parserInput.i = j = currentPos = furthest = 0; + + // chunking apparantly makes things quicker (but my tests indicate + // it might actually make things slower in node at least) + // and it is a non-perfect parse - it can't recognise + // unquoted urls, meaning it can't distinguish comments + // meaning comments with quotes or {}() in them get 'counted' + // and then lead to parse errors. + // In addition if the chunking chunks in the wrong place we might + // not be able to parse a parser statement in one go + // this is officially deprecated but can be switched on via an option + // in the case it causes too much performance issues. + if (chunkInput) { + chunks = chunker(str, function fail(msg, index) { + throw new(LessError)(parser, { + index: index, + type: 'Parse', + message: msg, + filename: env.currentFileInfo.filename + }, env); + }); + } else { + chunks = [str]; + } + + current = chunks[0]; + + skipWhitespace(0); + }; + + parserInput.end = function() { + var message, + isFinished = parserInput.i >= input.length - 1; + + if (parserInput.i < furthest) { + message = furthestPossibleErrorMessage; + parserInput.i = furthest; + } + return { + isFinished: isFinished, + furthest: parserInput.i, + furthestPossibleErrorMessage: message, + furthestReachedEnd: parserInput.i >= input.length - 1, + furthestChar: input[parserInput.i] + }; + }; + + return parserInput; +}; + +},{"../less-error.js":19,"./chunker.js":21}],24:[function(require,module,exports){ +var LessError = require('../less-error.js'), + tree = require("../tree/index.js"), + visitor = require("../visitor/index.js"), + contexts = require("../contexts.js"), + getImportManager = require("./imports.js"), + getParserInput = require("./parser-input.js"); + +module.exports = function(environment) { +var SourceMapOutput = require("../source-map-output")(environment); +// +// less.js - parser +// +// A relatively straight-forward predictive parser. +// There is no tokenization/lexing stage, the input is parsed +// in one sweep. +// +// To make the parser fast enough to run in the browser, several +// optimization had to be made: +// +// - Matching and slicing on a huge input is often cause of slowdowns. +// The solution is to chunkify the input into smaller strings. +// The chunks are stored in the `chunks` var, +// `j` holds the current chunk index, and `currentPos` holds +// the index of the current chunk in relation to `input`. +// This gives us an almost 4x speed-up. +// +// - In many cases, we don't need to match individual tokens; +// for example, if a value doesn't hold any variables, operations +// or dynamic references, the parser can effectively 'skip' it, +// treating it as a literal. +// An example would be '1px solid #000' - which evaluates to itself, +// we don't need to know what the individual components are. +// The drawback, of course is that you don't get the benefits of +// syntax-checking on the CSS. This gives us a 50% speed-up in the parser, +// and a smaller speed-up in the code-gen. +// +// +// Token matching is done with the `$` function, which either takes +// a terminal string or regexp, or a non-terminal function to call. +// It also takes care of moving all the indices forwards. +// +// +var Parser = function Parser(env) { + var parser, + parsers, + parserInput = getParserInput(); + + // Top parser on an import tree must be sure there is one "env" + // which will then be passed around by reference. + if (!(env instanceof contexts.parseEnv)) { + env = new contexts.parseEnv(env); + } + this.env = env; + + var imports = this.imports = getImportManager(environment, env, Parser); + + function expect(arg, msg, index) { + // some older browsers return typeof 'function' for RegExp + var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : parserInput.$(arg); + if (result) { + return result; + } + error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'" + : "unexpected token")); + } + + // Specialization of expect() + function expectChar(arg, msg) { + if (parserInput.$char(arg)) { + return arg; + } + error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'"); + } + + function error(msg, type) { + var e = new Error(msg); + e.index = parserInput.i; + e.type = type || 'Syntax'; + throw e; + } + + function getInput(e, env) { + if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) { + return parser.imports.contents[e.filename]; + } else { + return parserInput.getInput(); + } + } + + function getDebugInfo(index) { + var filename = env.currentFileInfo.filename; + filename = environment.getAbsolutePath(env, filename); + + return { + lineNumber: parserInput.getLocation(index).line + 1, + fileName: filename + }; + } + + // + // The Parser + // + parser = { + + imports: imports, + // + // Parse an input string into an abstract syntax tree, + // @param str A string containing 'less' markup + // @param callback call `callback` when done. + // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply + // + parse: function (str, callback, additionalData) { + var root, error = null, globalVars, modifyVars, preText = ""; + + globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : ''; + modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : ''; + + if (globalVars || (additionalData && additionalData.banner)) { + preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars; + parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length; + } + + str = str.replace(/\r\n/g, '\n'); + // Remove potential UTF Byte Order Mark + str = preText + str.replace(/^\uFEFF/, '') + modifyVars; + parser.imports.contents[env.currentFileInfo.filename] = str; + + // Start with the primary rule. + // The whole syntax tree is held under a Ruleset node, + // with the `root` property set to true, so no `{}` are + // output. The callback is called when the input is parsed. + try { + parserInput.start(str, env.chunkInput, parser, env); + + root = new(tree.Ruleset)(null, this.parsers.primary()); + root.root = true; + root.firstRoot = true; + } catch (e) { + return callback(new LessError(parser, e, env)); + } + + root.toCSS = (function (evaluate) { + return function (options, variables) { + options = options || {}; + var evaldRoot, + css, + evalEnv = new contexts.evalEnv(options); + + // + // Allows setting variables with a hash, so: + // + // `{ color: new(tree.Color)('#f01') }` will become: + // + // new(tree.Rule)('@color', + // new(tree.Value)([ + // new(tree.Expression)([ + // new(tree.Color)('#f01') + // ]) + // ]) + // ) + // + if (typeof(variables) === 'object' && !Array.isArray(variables)) { + variables = Object.keys(variables).map(function (k) { + var value = variables[k]; + + if (! (value instanceof tree.Value)) { + if (! (value instanceof tree.Expression)) { + value = new(tree.Expression)([value]); + } + value = new(tree.Value)([value]); + } + return new(tree.Rule)('@' + k, value, false, null, 0); + }); + evalEnv.frames = [new(tree.Ruleset)(null, variables)]; + } + + try { + var preEvalVisitors = [], + visitors = [ + new(visitor.JoinSelectorVisitor)(), + new(visitor.ExtendVisitor)(), + new(visitor.ToCSSVisitor)({compress: Boolean(options.compress)}) + ], i, root = this; + + if (options.plugins) { + for(i =0; i < options.plugins.length; i++) { + if (options.plugins[i].isPreEvalVisitor) { + preEvalVisitors.push(options.plugins[i]); + } else { + if (options.plugins[i].isPreVisitor) { + visitors.splice(0, 0, options.plugins[i]); + } else { + visitors.push(options.plugins[i]); + } + } + } + } + + for(i = 0; i < preEvalVisitors.length; i++) { + preEvalVisitors[i].run(root); + } + + evaldRoot = evaluate.call(root, evalEnv); + + for(i = 0; i < visitors.length; i++) { + visitors[i].run(evaldRoot); + } + + if (options.sourceMap) { + evaldRoot = new SourceMapOutput( + { + contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars, + writeSourceMap: options.writeSourceMap, + rootNode: evaldRoot, + contentsMap: parser.imports.contents, + sourceMapFilename: options.sourceMapFilename, + sourceMapURL: options.sourceMapURL, + outputFilename: options.sourceMapOutputFilename, + sourceMapBasepath: options.sourceMapBasepath, + sourceMapRootpath: options.sourceMapRootpath, + outputSourceFiles: options.outputSourceFiles, + sourceMapGenerator: options.sourceMapGenerator + }); + } + + css = evaldRoot.toCSS({ + compress: Boolean(options.compress), + dumpLineNumbers: env.dumpLineNumbers, + strictUnits: Boolean(options.strictUnits), + numPrecision: 8}); + } catch (e) { + throw new LessError(parser, e, env); + } + + var CleanCSS = environment.getCleanCSS(); + if (options.cleancss && CleanCSS) { + var cleancssOptions = options.cleancssOptions || {}; + + if (cleancssOptions.keepSpecialComments === undefined) { + cleancssOptions.keepSpecialComments = "*"; + } + cleancssOptions.processImport = false; + cleancssOptions.noRebase = true; + if (cleancssOptions.noAdvanced === undefined) { + cleancssOptions.noAdvanced = true; + } + + return new CleanCSS(cleancssOptions).minify(css); + } else if (options.compress) { + return css.replace(/(^(\s)+)|((\s)+$)/g, ""); + } else { + return css; + } + }; + })(root.eval); + + // If `i` is smaller than the `input.length - 1`, + // it means the parser wasn't able to parse the whole + // string, so we've got a parsing error. + // + // We try to extract a \n delimited string, + // showing the line where the parse error occurred. + // We split it up into two parts (the part which parsed, + // and the part which didn't), so we can color them differently. + var endInfo = parserInput.end(); + if (!endInfo.isFinished) { + + var message = endInfo.furthestPossibleErrorMessage; + + if (!message) { + message = "Unrecognised input"; + if (endInfo.furthestChar === '}') { + message += ". Possibly missing opening '{'"; + } else if (endInfo.furthestChar === ')') { + message += ". Possibly missing opening '('"; + } else if (endInfo.furthestReachedEnd) { + message += ". Possibly missing something"; + } + } + + error = new LessError(parser, { + type: "Parse", + message: message, + index: endInfo.furthest, + filename: env.currentFileInfo.filename + }, env); + } + + var finish = function (e) { + e = error || e || parser.imports.error; + + if (e) { + if (!(e instanceof LessError)) { + e = new LessError(parser, e, env); + } + + return callback(e); + } + else { + return callback(null, root); + } + }; + + if (env.processImports !== false) { + new visitor.ImportVisitor(this.imports, finish) + .run(root); + } else { + return finish(); + } + }, + + // + // Here in, the parsing rules/functions + // + // The basic structure of the syntax tree generated is as follows: + // + // Ruleset -> Rule -> Value -> Expression -> Entity + // + // Here's some Less code: + // + // .class { + // color: #fff; + // border: 1px solid #000; + // width: @w + 4px; + // > .child {...} + // } + // + // And here's what the parse tree might look like: + // + // Ruleset (Selector '.class', [ + // Rule ("color", Value ([Expression [Color #fff]])) + // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) + // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) + // Ruleset (Selector [Element '>', '.child'], [...]) + // ]) + // + // In general, most rules will try to parse a token with the `$()` function, and if the return + // value is truly, will return a new node, of the relevant type. Sometimes, we need to check + // first, before parsing, that's when we use `peek()`. + // + parsers: parsers = { + // + // The `primary` rule is the *entry* and *exit* point of the parser. + // The rules here can appear at any level of the parse tree. + // + // The recursive nature of the grammar is an interplay between the `block` + // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, + // as represented by this simplified grammar: + // + // primary → (ruleset | rule)+ + // ruleset → selector+ block + // block → '{' primary '}' + // + // Only at one point is the primary rule not called from the + // block rule: at the root level. + // + primary: function () { + var mixin = this.mixin, root = [], node; + + while (!parserInput.finished) + { + while(true) { + node = this.comment(); + if (!node) { break; } + root.push(node); + } + if (parserInput.peek('}')) { + break; + } + node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() || + mixin.call() || this.rulesetCall() || this.directive(); + if (node) { + root.push(node); + } else { + if (!(parserInput.$re(/^[\s\n]+/) || parserInput.$re(/^;+/))) { + break; + } + } + } + + return root; + }, + + // comments are collected by the main parsing mechanism and then assigned to nodes + // where the current structure allows it + comment: function () { + if (parserInput.commentStore.length) { + var comment = parserInput.commentStore.shift(); + return new(tree.Comment)(comment.text, comment.isLineComment, comment.index, env.currentFileInfo); + } + }, + + // + // Entities are tokens which can be found inside an Expression + // + entities: { + // + // A string, which supports escaping " and ' + // + // "milky way" 'he\'s the one!' + // + quoted: function () { + var str, index = parserInput.i; + + str = parserInput.$re(/^(~)?("((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)')/); + if (str) { + return new(tree.Quoted)(str[2], str[3] || str[4], Boolean(str[1]), index, env.currentFileInfo); + } + }, + + // + // A catch-all word, such as: + // + // black border-collapse + // + keyword: function () { + var k = parserInput.$re(/^%|^[_A-Za-z-][_A-Za-z0-9-]*/); + if (k) { + return tree.Color.fromKeyword(k) || new(tree.Keyword)(k); + } + }, + + // + // A function call + // + // rgb(255, 0, 255) + // + // We also try to catch IE's `alpha()`, but let the `alpha` parser + // deal with the details. + // + // The arguments are parsed with the `entities.arguments` parser. + // + call: function () { + var name, nameLC, args, alpha, index = parserInput.i; + + if (parserInput.peek(/^url\(/i)) { + return; + } + + parserInput.save(); + + name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/); + if (!name) { parserInput.forget(); return; } + + name = name[1]; + nameLC = name.toLowerCase(); + + if (nameLC === 'alpha') { + alpha = parsers.alpha(); + if(alpha) { + return alpha; + } + } + + args = this.arguments(); + + if (! parserInput.$char(')')) { + parserInput.restore("Could not parse call arguments or missing ')'"); + return; + } + + parserInput.forget(); + return new(tree.Call)(name, args, index, env.currentFileInfo); + }, + arguments: function () { + var args = [], arg; + + while (true) { + arg = this.assignment() || parsers.expression(); + if (!arg) { + break; + } + args.push(arg); + if (! parserInput.$char(',')) { + break; + } + } + return args; + }, + literal: function () { + return this.dimension() || + this.color() || + this.quoted() || + this.unicodeDescriptor(); + }, + + // Assignments are argument entities for calls. + // They are present in ie filter properties as shown below. + // + // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) + // + + assignment: function () { + var key, value; + key = parserInput.$re(/^\w+(?=\s?=)/i); + if (!key) { + return; + } + if (!parserInput.$char('=')) { + return; + } + value = parsers.entity(); + if (value) { + return new(tree.Assignment)(key, value); + } + }, + + // + // Parse url() tokens + // + // We use a specific rule for urls, because they don't really behave like + // standard function calls. The difference is that the argument doesn't have + // to be enclosed within a string, so it can't be parsed as an Expression. + // + url: function () { + var value; + + if (parserInput.currentChar() !== 'u' || !parserInput.$re(/^url\(/)) { + return; + } + + parserInput.autoCommentAbsorb = false; + + value = this.quoted() || this.variable() || + parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; + + parserInput.autoCommentAbsorb = true; + + expectChar(')'); + + return new(tree.URL)((value.value != null || value instanceof tree.Variable) + ? value : new(tree.Anonymous)(value), env.currentFileInfo); + }, + + // + // A Variable entity, such as `@fink`, in + // + // width: @fink + 2px + // + // We use a different parser for variable definitions, + // see `parsers.variable`. + // + variable: function () { + var name, index = parserInput.i; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) { + return new(tree.Variable)(name, index, env.currentFileInfo); + } + }, + + // A variable entity useing the protective {} e.g. @{var} + variableCurly: function () { + var curly, index = parserInput.i; + + if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) { + return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo); + } + }, + + // + // A Hexadecimal color + // + // #4F3C2F + // + // `rgb` and `hsl` colors are parsed through the `entities.call` parser. + // + color: function () { + var rgb; + + if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { + var colorCandidateString = rgb.input.match(/^#([\w]+).*/); // strip colons, brackets, whitespaces and other characters that should not definitely be part of color string + colorCandidateString = colorCandidateString[1]; + if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characters + error("Invalid HEX color code"); + } + return new(tree.Color)(rgb[1]); + } + }, + + // + // A Dimension, that is, a number and a unit + // + // 0.5em 95% + // + dimension: function () { + if (parserInput.peekNotNumeric()) { + return; + } + + var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/); + if (value) { + return new(tree.Dimension)(value[1], value[2]); + } + }, + + // + // A unicode descriptor, as is used in unicode-range + // + // U+0?? or U+00A1-00A9 + // + unicodeDescriptor: function () { + var ud; + + ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); + if (ud) { + return new(tree.UnicodeDescriptor)(ud[0]); + } + }, + + // + // JavaScript code to be evaluated + // + // `window.location.href` + // + javascript: function () { + var js, index = parserInput.i; + + js = parserInput.$re(/^(~)?`([^`]*)`/); + if (js) { + return new(tree.JavaScript)(js[2], index, Boolean(js[1])); + } + } + }, + + // + // The variable part of a variable definition. Used in the `rule` parser + // + // @fink: + // + variable: function () { + var name; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; } + }, + + // + // The variable part of a variable definition. Used in the `rule` parser + // + // @fink(); + // + rulesetCall: function () { + var name; + + if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*\(\s*\)\s*;/))) { + return new tree.RulesetCall(name[1]); + } + }, + + // + // extend syntax - used to extend selectors + // + extend: function(isRule) { + var elements, e, index = parserInput.i, option, extendList, extend; + + if (!(isRule ? parserInput.$re(/^&:extend\(/) : parserInput.$re(/^:extend\(/))) { return; } + + do { + option = null; + elements = null; + while (! (option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) { + e = this.element(); + if (!e) { break; } + if (elements) { elements.push(e); } else { elements = [ e ]; } + } + + option = option && option[1]; + if (!elements) + error("Missing target selector for :extend()."); + extend = new(tree.Extend)(new(tree.Selector)(elements), option, index); + if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } + + } while(parserInput.$char(",")); + + expect(/^\)/); + + if (isRule) { + expect(/^;/); + } + + return extendList; + }, + + // + // extendRule - used in a rule to extend all the parent selectors + // + extendRule: function() { + return this.extend(true); + }, + + // + // Mixins + // + mixin: { + // + // A Mixin call, with an optional argument list + // + // #mixins > .square(#fff); + // .rounded(4px, black); + // .button; + // + // The `while` loop is there because mixins can be + // namespaced, but we only support the child and descendant + // selector for now. + // + call: function () { + var s = parserInput.currentChar(), important = false, index = parserInput.i, elemIndex, + elements, elem, e, c, args; + + if (s !== '.' && s !== '#') { return; } + + parserInput.save(); // stop us absorbing part of an invalid selector + + while (true) { + elemIndex = parserInput.i; + e = parserInput.$re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/); + if (!e) { + break; + } + elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo); + if (elements) { elements.push(elem); } else { elements = [ elem ]; } + c = parserInput.$char('>'); + } + + if (elements) { + if (parserInput.$char('(')) { + args = this.args(true).args; + expectChar(')'); + } + + if (parsers.important()) { + important = true; + } + + if (parsers.end()) { + parserInput.forget(); + return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important); + } + } + + parserInput.restore(); + }, + args: function (isCall) { + var parsers = parser.parsers, entities = parsers.entities, + returner = { args:null, variadic: false }, + expressions = [], argsSemiColon = [], argsComma = [], + isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg; + + parserInput.save(); + + while (true) { + if (isCall) { + arg = parsers.detachedRuleset() || parsers.expression(); + } else { + parserInput.commentStore.length = 0; + if (parserInput.currentChar() === '.' && parserInput.$re(/^\.{3}/)) { + returner.variadic = true; + if (parserInput.$char(";") && !isSemiColonSeperated) { + isSemiColonSeperated = true; + } + (isSemiColonSeperated ? argsSemiColon : argsComma) + .push({ variadic: true }); + break; + } + arg = entities.variable() || entities.literal() || entities.keyword(); + } + + if (!arg) { + break; + } + + nameLoop = null; + if (arg.throwAwayComments) { + arg.throwAwayComments(); + } + value = arg; + var val = null; + + if (isCall) { + // Variable + if (arg.value && arg.value.length == 1) { + val = arg.value[0]; + } + } else { + val = arg; + } + + if (val && val instanceof tree.Variable) { + if (parserInput.$char(':')) { + if (expressions.length > 0) { + if (isSemiColonSeperated) { + error("Cannot mix ; and , as delimiter types"); + } + expressionContainsNamed = true; + } + + // we do not support setting a ruleset as a default variable - it doesn't make sense + // However if we do want to add it, there is nothing blocking it, just don't error + // and remove isCall dependency below + value = (isCall && parsers.detachedRuleset()) || parsers.expression(); + + if (!value) { + if (isCall) { + error("could not understand value for named argument"); + } else { + parserInput.restore(); + returner.args = []; + return returner; + } + } + nameLoop = (name = val.name); + } else if (!isCall && parserInput.$re(/^\.{3}/)) { + returner.variadic = true; + if (parserInput.$char(";") && !isSemiColonSeperated) { + isSemiColonSeperated = true; + } + (isSemiColonSeperated ? argsSemiColon : argsComma) + .push({ name: arg.name, variadic: true }); + break; + } else if (!isCall) { + name = nameLoop = val.name; + value = null; + } + } + + if (value) { + expressions.push(value); + } + + argsComma.push({ name:nameLoop, value:value }); + + if (parserInput.$char(',')) { + continue; + } + + if (parserInput.$char(';') || isSemiColonSeperated) { + + if (expressionContainsNamed) { + error("Cannot mix ; and , as delimiter types"); + } + + isSemiColonSeperated = true; + + if (expressions.length > 1) { + value = new(tree.Value)(expressions); + } + argsSemiColon.push({ name:name, value:value }); + + name = null; + expressions = []; + expressionContainsNamed = false; + } + } + + parserInput.forget(); + returner.args = isSemiColonSeperated ? argsSemiColon : argsComma; + return returner; + }, + // + // A Mixin definition, with a list of parameters + // + // .rounded (@radius: 2px, @color) { + // ... + // } + // + // Until we have a finer grained state-machine, we have to + // do a look-ahead, to make sure we don't have a mixin call. + // See the `rule` function for more information. + // + // We start by matching `.rounded (`, and then proceed on to + // the argument list, which has optional default values. + // We store the parameters in `params`, with a `value` key, + // if there is a value, such as in the case of `@radius`. + // + // Once we've got our params list, and a closing `)`, we parse + // the `{...}` block. + // + definition: function () { + var name, params = [], match, ruleset, cond, variadic = false; + if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') || + parserInput.peek(/^[^{]*\}/)) { + return; + } + + parserInput.save(); + + match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); + if (match) { + name = match[1]; + + var argInfo = this.args(false); + params = argInfo.args; + variadic = argInfo.variadic; + + // .mixincall("@{a}"); + // looks a bit like a mixin definition.. + // also + // .mixincall(@a: {rule: set;}); + // so we have to be nice and restore + if (!parserInput.$char(')')) { + parserInput.restore("Missing closing ')'"); + return; + } + + parserInput.commentStore.length = 0; + + if (parserInput.$re(/^when/)) { // Guard + cond = expect(parsers.conditions, 'expected condition'); + } + + ruleset = parsers.block(); + + if (ruleset) { + parserInput.forget(); + return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); + } else { + parserInput.restore(); + } + } else { + parserInput.forget(); + } + } + }, + + // + // Entities are the smallest recognized token, + // and can be found inside a rule's value. + // + entity: function () { + var entities = this.entities; + + return this.comment() || entities.literal() || entities.variable() || entities.url() || + entities.call() || entities.keyword() || entities.javascript(); + }, + + // + // A Rule terminator. Note that we use `peek()` to check for '}', + // because the `block` rule will be expecting it, but we still need to make sure + // it's there, if ';' was ommitted. + // + end: function () { + return parserInput.$char(';') || parserInput.peek('}'); + }, + + // + // IE's alpha function + // + // alpha(opacity=88) + // + alpha: function () { + var value; + + if (! parserInput.$re(/^opacity=/i)) { return; } + value = parserInput.$re(/^\d+/); + if (!value) { + value = expect(this.entities.variable, "Could not parse alpha"); + } + expectChar(')'); + return new(tree.Alpha)(value); + }, + + // + // A Selector Element + // + // div + // + h1 + // #socks + // input[type="text"] + // + // Elements are the building blocks for Selectors, + // they are made out of a `Combinator` (see combinator rule), + // and an element name, such as a tag a class, or `*`. + // + element: function () { + var e, c, v, index = parserInput.i; + + c = this.combinator(); + + e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || + parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^()@]+\)/) || parserInput.$re(/^[\.#](?=@)/) || + this.entities.variableCurly(); + + if (! e) { + parserInput.save(); + if (parserInput.$char('(')) { + if ((v = this.selector()) && parserInput.$char(')')) { + e = new(tree.Paren)(v); + parserInput.forget(); + } else { + parserInput.restore("Missing closing ')'"); + } + } else { + parserInput.forget(); + } + } + + if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); } + }, + + // + // Combinators combine elements together, in a Selector. + // + // Because our parser isn't white-space sensitive, special care + // has to be taken, when parsing the descendant combinator, ` `, + // as it's an empty space. We have to check the previous character + // in the input, to see if it's a ` ` character. More info on how + // we deal with this in *combinator.js*. + // + combinator: function () { + var c = parserInput.currentChar(); + + if (c === '/') { + parserInput.save(); + var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i); + if (slashedCombinator) { + parserInput.forget(); + return new(tree.Combinator)(slashedCombinator); + } + parserInput.restore(); + } + + if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { + parserInput.i++; + if (c === '^' && parserInput.currentChar() === '^') { + c = '^^'; + parserInput.i++; + } + while (parserInput.isWhitespace()) { parserInput.i++; } + return new(tree.Combinator)(c); + } else if (parserInput.isWhitespace(-1)) { + return new(tree.Combinator)(" "); + } else { + return new(tree.Combinator)(null); + } + }, + // + // A CSS selector (see selector below) + // with less extensions e.g. the ability to extend and guard + // + lessSelector: function () { + return this.selector(true); + }, + // + // A CSS Selector + // + // .class > div + h1 + // li a:hover + // + // Selectors are made out of one or more Elements, see above. + // + selector: function (isLess) { + var index = parserInput.i, elements, extendList, c, e, extend, when, condition; + + while ((isLess && (extend = this.extend())) || (isLess && (when = parserInput.$re(/^when/))) || (e = this.element())) { + if (when) { + condition = expect(this.conditions, 'expected condition'); + } else if (condition) { + error("CSS guard can only be used at the end of selector"); + } else if (extend) { + if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } + } else { + if (extendList) { error("Extend can only be used at the end of selector"); } + c = parserInput.currentChar(); + if (elements) { elements.push(e); } else { elements = [ e ]; } + e = null; + } + if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { + break; + } + } + + if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); } + if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); } + }, + attribute: function () { + if (! parserInput.$char('[')) { return; } + + var entities = this.entities, + key, val, op; + + if (!(key = entities.variableCurly())) { + key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); + } + + op = parserInput.$re(/^[|~*$^]?=/); + if (op) { + val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly(); + } + + expectChar(']'); + + return new(tree.Attribute)(key, op, val); + }, + + // + // The `block` rule is used by `ruleset` and `mixin.definition`. + // It's a wrapper around the `primary` rule, with added `{}`. + // + block: function () { + var content; + if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) { + return content; + } + }, + + blockRuleset: function() { + var block = this.block(); + + if (block) { + block = new tree.Ruleset(null, block); + } + return block; + }, + + detachedRuleset: function() { + var blockRuleset = this.blockRuleset(); + if (blockRuleset) { + return new tree.DetachedRuleset(blockRuleset); + } + }, + + // + // div, .class, body > p {...} + // + ruleset: function () { + var selectors, s, rules, debugInfo; + + parserInput.save(); + + if (env.dumpLineNumbers) { + debugInfo = getDebugInfo(parserInput.i); + } + + while (true) { + s = this.lessSelector(); + if (!s) { + break; + } + if (selectors) { selectors.push(s); } else { selectors = [ s ]; } + parserInput.commentStore.length = 0; + if (s.condition && selectors.length > 1) { + error("Guards are only currently allowed on a single selector."); + } + if (! parserInput.$char(',')) { break; } + if (s.condition) { + error("Guards are only currently allowed on a single selector."); + } + parserInput.commentStore.length = 0; + } + + if (selectors && (rules = this.block())) { + parserInput.forget(); + var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); + if (env.dumpLineNumbers) { + ruleset.debugInfo = debugInfo; + } + return ruleset; + } else { + parserInput.restore(); + } + }, + rule: function (tryAnonymous) { + var name, value, startOfRule = parserInput.i, c = parserInput.currentChar(), important, merge, isVariable; + + if (c === '.' || c === '#' || c === '&') { return; } + + parserInput.save(); + + name = this.variable() || this.ruleProperty(); + if (name) { + isVariable = typeof name === "string"; + + if (isVariable) { + value = this.detachedRuleset(); + } + + parserInput.commentStore.length = 0; + if (!value) { + // a name returned by this.ruleProperty() is always an array of the form: + // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] + // where each item is a tree.Keyword or tree.Variable + merge = !isVariable && name.pop().value; + + // prefer to try to parse first if its a variable or we are compressing + // but always fallback on the other one + var tryValueFirst = !tryAnonymous && (env.compress || isVariable); + + if (tryValueFirst) { + value = this.value(); + } + if (!value) { + value = this.anonymousValue(); + if (value) { + parserInput.forget(); + // anonymous values absorb the end ';' which is reequired for them to work + return new (tree.Rule)(name, value, false, merge, startOfRule, env.currentFileInfo); + } + } + if (!tryValueFirst && !value) { + value = this.value(); + } + + important = this.important(); + } + + if (value && this.end()) { + parserInput.forget(); + return new (tree.Rule)(name, value, important, merge, startOfRule, env.currentFileInfo); + } else { + parserInput.restore(); + if (value && !tryAnonymous) { + return this.rule(true); + } + } + } else { + parserInput.forget(); + } + }, + anonymousValue: function () { + var match = parserInput.$re(/^([^@+\/'"*`(;{}-]*);/); + if (match) { + return new(tree.Anonymous)(match[1]); + } + }, + + // + // An @import directive + // + // @import "lib"; + // + // Depending on our environment, importing is done differently: + // In the browser, it's an XHR request, in Node, it would be a + // file-system operation. The function used for importing is + // stored in `import`, which we pass to the Import constructor. + // + "import": function () { + var path, features, index = parserInput.i; + + var dir = parserInput.$re(/^@import?\s+/); + + if (dir) { + var options = (dir ? this.importOptions() : null) || {}; + + if ((path = this.entities.quoted() || this.entities.url())) { + features = this.mediaFeatures(); + + if (!parserInput.$(';')) { + parserInput.i = index; + error("missing semi-colon or unrecognised media features on import"); + } + features = features && new(tree.Value)(features); + return new(tree.Import)(path, features, options, index, env.currentFileInfo); + } + else + { + parserInput.i = index; + error("malformed import statement"); + } + } + }, + + importOptions: function() { + var o, options = {}, optionName, value; + + // list of options, surrounded by parens + if (! parserInput.$char('(')) { return null; } + do { + o = this.importOption(); + if (o) { + optionName = o; + value = true; + switch(optionName) { + case "css": + optionName = "less"; + value = false; + break; + case "once": + optionName = "multiple"; + value = false; + break; + } + options[optionName] = value; + if (! parserInput.$char(',')) { break; } + } + } while (o); + expectChar(')'); + return options; + }, + + importOption: function() { + var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference)/); + if (opt) { + return opt[1]; + } + }, + + mediaFeature: function () { + var entities = this.entities, nodes = [], e, p; + parserInput.save(); + do { + e = entities.keyword() || entities.variable(); + if (e) { + nodes.push(e); + } else if (parserInput.$char('(')) { + p = this.property(); + e = this.value(); + if (parserInput.$char(')')) { + if (p && e) { + nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, parserInput.i, env.currentFileInfo, true))); + } else if (e) { + nodes.push(new(tree.Paren)(e)); + } else { + parserInput.restore("badly formed media feature definition"); + return null; + } + } else { + parserInput.restore("Missing closing ')'"); + return null; + } + } + } while (e); + + parserInput.forget(); + if (nodes.length > 0) { + return new(tree.Expression)(nodes); + } + }, + + mediaFeatures: function () { + var entities = this.entities, features = [], e; + do { + e = this.mediaFeature(); + if (e) { + features.push(e); + if (! parserInput.$char(',')) { break; } + } else { + e = entities.variable(); + if (e) { + features.push(e); + if (! parserInput.$char(',')) { break; } + } + } + } while (e); + + return features.length > 0 ? features : null; + }, + + media: function () { + var features, rules, media, debugInfo; + + if (env.dumpLineNumbers) { + debugInfo = getDebugInfo(parserInput.i); + } + + if (parserInput.$re(/^@media/)) { + features = this.mediaFeatures(); + + rules = this.block(); + if (rules) { + media = new(tree.Media)(rules, features, parserInput.i, env.currentFileInfo); + if (env.dumpLineNumbers) { + media.debugInfo = debugInfo; + } + return media; + } + } + }, + + // + // A CSS Directive + // + // @charset "utf-8"; + // + directive: function () { + var index = parserInput.i, name, value, rules, nonVendorSpecificName, + hasIdentifier, hasExpression, hasUnknown, hasBlock = true; + + if (parserInput.currentChar() !== '@') { return; } + + value = this['import']() || this.media(); + if (value) { + return value; + } + + parserInput.save(); + + name = parserInput.$re(/^@[a-z-]+/); + + if (!name) { return; } + + nonVendorSpecificName = name; + if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { + nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); + } + + switch(nonVendorSpecificName) { + /* + case "@font-face": + case "@viewport": + case "@top-left": + case "@top-left-corner": + case "@top-center": + case "@top-right": + case "@top-right-corner": + case "@bottom-left": + case "@bottom-left-corner": + case "@bottom-center": + case "@bottom-right": + case "@bottom-right-corner": + case "@left-top": + case "@left-middle": + case "@left-bottom": + case "@right-top": + case "@right-middle": + case "@right-bottom": + hasBlock = true; + break; + */ + case "@charset": + hasIdentifier = true; + hasBlock = false; + break; + case "@namespace": + hasExpression = true; + hasBlock = false; + break; + case "@keyframes": + hasIdentifier = true; + break; + case "@host": + case "@page": + case "@document": + case "@supports": + hasUnknown = true; + break; + } + + parserInput.commentStore.length = 0; + + if (hasIdentifier) { + value = this.entity(); + if (!value) { + error("expected " + name + " identifier"); + } + } else if (hasExpression) { + value = this.expression(); + if (!value) { + error("expected " + name + " expression"); + } + } else if (hasUnknown) { + value = (parserInput.$re(/^[^{;]+/) || '').trim(); + if (value) { + value = new(tree.Anonymous)(value); + } + } + + if (hasBlock) { + rules = this.blockRuleset(); + } + + if (rules || (!hasBlock && value && parserInput.$char(';'))) { + parserInput.forget(); + return new(tree.Directive)(name, value, rules, index, env.currentFileInfo, + env.dumpLineNumbers ? getDebugInfo(index) : null); + } + + parserInput.restore("directive options not recognised"); + }, + + // + // A Value is a comma-delimited list of Expressions + // + // font-family: Baskerville, Georgia, serif; + // + // In a Rule, a Value represents everything after the `:`, + // and before the `;`. + // + value: function () { + var e, expressions = []; + + do { + e = this.expression(); + if (e) { + expressions.push(e); + if (! parserInput.$char(',')) { break; } + } + } while(e); + + if (expressions.length > 0) { + return new(tree.Value)(expressions); + } + }, + important: function () { + if (parserInput.currentChar() === '!') { + return parserInput.$re(/^! *important/); + } + }, + sub: function () { + var a, e; + + if (parserInput.$char('(')) { + a = this.addition(); + if (a) { + e = new(tree.Expression)([a]); + expectChar(')'); + e.parens = true; + return e; + } + } + }, + multiplication: function () { + var m, a, op, operation, isSpaced; + m = this.operand(); + if (m) { + isSpaced = parserInput.isWhitespace(-1); + while (true) { + if (parserInput.peek(/^\/[*\/]/)) { + break; + } + + parserInput.save(); + + op = parserInput.$char('/') || parserInput.$char('*'); + + if (!op) { parserInput.forget(); break; } + + a = this.operand(); + + if (!a) { parserInput.restore(); break; } + parserInput.forget(); + + m.parensInOp = true; + a.parensInOp = true; + operation = new(tree.Operation)(op, [operation || m, a], isSpaced); + isSpaced = parserInput.isWhitespace(-1); + } + return operation || m; + } + }, + addition: function () { + var m, a, op, operation, isSpaced; + m = this.multiplication(); + if (m) { + isSpaced = parserInput.isWhitespace(-1); + while (true) { + op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-'))); + if (!op) { + break; + } + a = this.multiplication(); + if (!a) { + break; + } + + m.parensInOp = true; + a.parensInOp = true; + operation = new(tree.Operation)(op, [operation || m, a], isSpaced); + isSpaced = parserInput.isWhitespace(-1); + } + return operation || m; + } + }, + conditions: function () { + var a, b, index = parserInput.i, condition; + + a = this.condition(); + if (a) { + while (true) { + if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) { + break; + } + b = this.condition(); + if (!b) { + break; + } + condition = new(tree.Condition)('or', condition || a, b, index); + } + return condition || a; + } + }, + condition: function () { + var entities = this.entities, index = parserInput.i, negate = false, + a, b, c, op; + + if (parserInput.$re(/^not/)) { negate = true; } + expectChar('('); + a = this.addition() || entities.keyword() || entities.quoted(); + if (a) { + op = parserInput.$re(/^(?:>=|<=|=<|[<=>])/); + if (op) { + b = this.addition() || entities.keyword() || entities.quoted(); + if (b) { + c = new(tree.Condition)(op, a, b, index, negate); + } else { + error('expected expression'); + } + } else { + c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); + } + expectChar(')'); + return parserInput.$re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c; + } + }, + + // + // An operand is anything that can be part of an operation, + // such as a Color, or a Variable + // + operand: function () { + var entities = this.entities, negate; + + if (parserInput.peek(/^-[@\(]/)) { + negate = parserInput.$char('-'); + } + + var o = this.sub() || entities.dimension() || + entities.color() || entities.variable() || + entities.call(); + + if (negate) { + o.parensInOp = true; + o = new(tree.Negative)(o); + } + + return o; + }, + + // + // Expressions either represent mathematical operations, + // or white-space delimited Entities. + // + // 1px solid black + // @var * 2 + // + expression: function () { + var entities = [], e, delim; + + do { + e = this.comment(); + if (e) { + entities.push(e); + continue; + } + e = this.addition() || this.entity(); + if (e) { + entities.push(e); + // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here + if (!parserInput.peek(/^\/[\/*]/)) { + delim = parserInput.$char('/'); + if (delim) { + entities.push(new(tree.Anonymous)(delim)); + } + } + } + } while (e); + if (entities.length > 0) { + return new(tree.Expression)(entities); + } + }, + property: function () { + var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); + if (name) { + return name[1]; + } + }, + ruleProperty: function () { + var name = [], index = [], s, k; + + parserInput.save(); + + function match(re) { + var i = parserInput.i, + chunk = parserInput.$re(re); + if (chunk) { + index.push(i); + return name.push(chunk[1]); + } + } + + match(/^(\*?)/); + while (true) { + if (!match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)) { + break; + } + } + + if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) { + parserInput.forget(); + + // at last, we have the complete match now. move forward, + // convert name particles to tree objects and return: + if (name[0] === '') { + name.shift(); + index.shift(); + } + for (k = 0; k < name.length; k++) { + s = name[k]; + name[k] = (s.charAt(0) !== '@') ? + new(tree.Keyword)(s) : + new(tree.Variable)('@' + s.slice(2, -1), + index[k], env.currentFileInfo); + } + return name; + } + parserInput.restore(); + } + } + }; + + parser.getInput = getInput; + parser.getLocation = parserInput.getLocation; + + return parser; +}; +Parser.serializeVars = function(vars) { + var s = ''; + + for (var name in vars) { + if (Object.hasOwnProperty.call(vars, name)) { + var value = vars[name]; + s += ((name[0] === '@') ? '' : '@') + name +': '+ value + + ((('' + value).slice(-1) === ';') ? '' : ';'); + } + } + + return s; +}; + +return Parser; +}; + +},{"../contexts.js":2,"../less-error.js":19,"../source-map-output":25,"../tree/index.js":43,"../visitor/index.js":66,"./imports.js":22,"./parser-input.js":23}],25:[function(require,module,exports){ +module.exports = function (environment) { + + var SourceMapOutput = function (options) { + this._css = []; + this._rootNode = options.rootNode; + this._writeSourceMap = options.writeSourceMap; + this._contentsMap = options.contentsMap; + this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; + this._sourceMapFilename = options.sourceMapFilename; + this._outputFilename = options.outputFilename; + this._sourceMapURL = options.sourceMapURL; + if (options.sourceMapBasepath) { + this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); + } + this._sourceMapRootpath = options.sourceMapRootpath; + this._outputSourceFiles = options.outputSourceFiles; + this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator(); + + if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') { + this._sourceMapRootpath += '/'; + } + + this._lineNumber = 0; + this._column = 0; + }; + + SourceMapOutput.prototype.normalizeFilename = function(filename) { + filename = filename.replace(/\\/g, '/'); + + if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) { + filename = filename.substring(this._sourceMapBasepath.length); + if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') { + filename = filename.substring(1); + } + } + return (this._sourceMapRootpath || "") + filename; + }; + + SourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { + + //ignore adding empty strings + if (!chunk) { + return; + } + + var lines, + sourceLines, + columns, + sourceColumns, + i; + + if (fileInfo) { + var inputSource = this._contentsMap[fileInfo.filename]; + + // remove vars/banner added to the top of the file + if (this._contentsIgnoredCharsMap[fileInfo.filename]) { + // adjust the index + index -= this._contentsIgnoredCharsMap[fileInfo.filename]; + if (index < 0) { index = 0; } + // adjust the source + inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); + } + inputSource = inputSource.substring(0, index); + sourceLines = inputSource.split("\n"); + sourceColumns = sourceLines[sourceLines.length-1]; + } + + lines = chunk.split("\n"); + columns = lines[lines.length-1]; + + if (fileInfo) { + if (!mapLines) { + this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, + original: { line: sourceLines.length, column: sourceColumns.length}, + source: this.normalizeFilename(fileInfo.filename)}); + } else { + for(i = 0; i < lines.length; i++) { + this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, + original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, + source: this.normalizeFilename(fileInfo.filename)}); + } + } + } + + if (lines.length === 1) { + this._column += columns.length; + } else { + this._lineNumber += lines.length - 1; + this._column = columns.length; + } + + this._css.push(chunk); + }; + + SourceMapOutput.prototype.isEmpty = function() { + return this._css.length === 0; + }; + + SourceMapOutput.prototype.toCSS = function(env) { + this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); + + if (this._outputSourceFiles) { + for(var filename in this._contentsMap) { + if (this._contentsMap.hasOwnProperty(filename)) + { + var source = this._contentsMap[filename]; + if (this._contentsIgnoredCharsMap[filename]) { + source = source.slice(this._contentsIgnoredCharsMap[filename]); + } + this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); + } + } + } + + this._rootNode.genCSS(env, this); + + if (this._css.length > 0) { + var sourceMapURL, + sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); + + if (this._sourceMapURL) { + sourceMapURL = this._sourceMapURL; + } else if (this._sourceMapFilename) { + sourceMapURL = this.normalizeFilename(this._sourceMapFilename); + } + + if (this._writeSourceMap) { + this._writeSourceMap(sourceMapContent); + } else { + sourceMapURL = "data:application/json;base64," + environment.encodeBase64(sourceMapContent); + } + + if (sourceMapURL) { + this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */"); + } + } + + return this._css.join(''); + }; + + return SourceMapOutput; +}; + +},{}],26:[function(require,module,exports){ +var Node = require("./node.js"); + +var Alpha = function (val) { + this.value = val; +}; +Alpha.prototype = new Node(); +Alpha.prototype.type = "Alpha"; + +Alpha.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Alpha.prototype.eval = function (env) { + if (this.value.eval) { return new Alpha(this.value.eval(env)); } + return this; +}; +Alpha.prototype.genCSS = function (env, output) { + output.add("alpha(opacity="); + + if (this.value.genCSS) { + this.value.genCSS(env, output); + } else { + output.add(this.value); + } + + output.add(")"); +}; + +module.exports = Alpha; + +},{"./node.js":51}],27:[function(require,module,exports){ +var Node = require("./node.js"); + +var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike) { + this.value = value; + this.index = index; + this.mapLines = mapLines; + this.currentFileInfo = currentFileInfo; + this.rulesetLike = (typeof rulesetLike === 'undefined')? false : rulesetLike; +}; +Anonymous.prototype = new Node(); +Anonymous.prototype.type = "Anonymous"; +Anonymous.prototype.eval = function () { + return new Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines, this.rulesetLike); +}; +Anonymous.prototype.compare = function (x) { + if (!x.toCSS) { + return -1; + } + + var left = this.toCSS(), + right = x.toCSS(); + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; +}; +Anonymous.prototype.isRulesetLike = function() { + return this.rulesetLike; +}; +Anonymous.prototype.genCSS = function (env, output) { + output.add(this.value, this.currentFileInfo, this.index, this.mapLines); +}; +module.exports = Anonymous; + +},{"./node.js":51}],28:[function(require,module,exports){ +var Node = require("./node.js"); + +var Assignment = function (key, val) { + this.key = key; + this.value = val; +}; + +Assignment.prototype = new Node(); +Assignment.prototype.type = "Assignment"; +Assignment.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Assignment.prototype.eval = function (env) { + if (this.value.eval) { + return new(Assignment)(this.key, this.value.eval(env)); + } + return this; +}; +Assignment.prototype.genCSS = function (env, output) { + output.add(this.key + '='); + if (this.value.genCSS) { + this.value.genCSS(env, output); + } else { + output.add(this.value); + } +}; +module.exports = Assignment; + + +},{"./node.js":51}],29:[function(require,module,exports){ +var Node = require("./node.js"); + +var Attribute = function (key, op, value) { + this.key = key; + this.op = op; + this.value = value; +}; +Attribute.prototype = new Node(); +Attribute.prototype.type = "Attribute"; +Attribute.prototype.eval = function (env) { + return new(Attribute)(this.key.eval ? this.key.eval(env) : this.key, + this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value); +}; +Attribute.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env)); +}; +Attribute.prototype.toCSS = function (env) { + var value = this.key.toCSS ? this.key.toCSS(env) : this.key; + + if (this.op) { + value += this.op; + value += (this.value.toCSS ? this.value.toCSS(env) : this.value); + } + + return '[' + value + ']'; +}; +module.exports = Attribute; + +},{"./node.js":51}],30:[function(require,module,exports){ +var Node = require("./node.js"), + FunctionCaller = require("../functions/function-caller.js"); +// +// A function call node. +// +var Call = function (name, args, index, currentFileInfo) { + this.name = name; + this.args = args; + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Call.prototype = new Node(); +Call.prototype.type = "Call"; +Call.prototype.accept = function (visitor) { + if (this.args) { + this.args = visitor.visitArray(this.args); + } +}; +// +// When evaluating a function call, +// we either find the function in `less.functions` [1], +// in which case we call it, passing the evaluated arguments, +// if this returns null or we cannot find the function, we +// simply print it out as it appeared originally [2]. +// +// The *functions.js* file contains the built-in functions. +// +// The reason why we evaluate the arguments, is in the case where +// we try to pass a variable to a function, like: `saturate(@color)`. +// The function should receive the value, not the variable. +// +Call.prototype.eval = function (env) { + var args = this.args.map(function (a) { return a.eval(env); }), + result, funcCaller = new FunctionCaller(this.name, env, this.currentFileInfo); + + if (funcCaller.isValid()) { // 1. + try { + result = funcCaller.call(args); + if (result != null) { + return result; + } + } catch (e) { + throw { type: e.type || "Runtime", + message: "error evaluating function `" + this.name + "`" + + (e.message ? ': ' + e.message : ''), + index: this.index, filename: this.currentFileInfo.filename }; + } + } + + return new Call(this.name, args, this.index, this.currentFileInfo); +}; +Call.prototype.genCSS = function (env, output) { + output.add(this.name + "(", this.currentFileInfo, this.index); + + for(var i = 0; i < this.args.length; i++) { + this.args[i].genCSS(env, output); + if (i + 1 < this.args.length) { + output.add(", "); + } + } + + output.add(")"); +}; +module.exports = Call; + +},{"../functions/function-caller.js":11,"./node.js":51}],31:[function(require,module,exports){ +var Node = require("./node.js"), + colors = require("../data/colors.js"); + +// +// RGB Colors - #ff0014, #eee +// +var Color = function (rgb, a) { + // + // The end goal here, is to parse the arguments + // into an integer triplet, such as `128, 255, 0` + // + // This facilitates operations and conversions. + // + if (Array.isArray(rgb)) { + this.rgb = rgb; + } else if (rgb.length == 6) { + this.rgb = rgb.match(/.{2}/g).map(function (c) { + return parseInt(c, 16); + }); + } else { + this.rgb = rgb.split('').map(function (c) { + return parseInt(c + c, 16); + }); + } + this.alpha = typeof(a) === 'number' ? a : 1; +}; + +Color.prototype = new Node(); +Color.prototype.type = "Color"; + +function clamp(v, max) { + return Math.min(Math.max(v, 0), max); +} + +function toHex(v) { + return '#' + v.map(function (c) { + c = clamp(Math.round(c), 255); + return (c < 16 ? '0' : '') + c.toString(16); + }).join(''); +} + +Color.prototype.luma = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255; + + r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4); + g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4); + b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4); + + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +}; +Color.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env)); +}; +Color.prototype.toCSS = function (env, doNotCompress) { + var compress = env && env.compress && !doNotCompress, color, alpha; + + // `keyword` is set if this color was originally + // converted from a named color string so we need + // to respect this and try to output named color too. + if (this.keyword) { + return this.keyword; + } + + // If we have some transparency, the only way to represent it + // is via `rgba`. Otherwise, we use the hex representation, + // which has better compatibility with older browsers. + // Values are capped between `0` and `255`, rounded and zero-padded. + alpha = this.fround(env, this.alpha); + if (alpha < 1) { + return "rgba(" + this.rgb.map(function (c) { + return clamp(Math.round(c), 255); + }).concat(clamp(alpha, 1)) + .join(',' + (compress ? '' : ' ')) + ")"; + } + + color = this.toRGB(); + + if (compress) { + var splitcolor = color.split(''); + + // Convert color to short format + if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { + color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; + } + } + + return color; +}; + +// +// Operations have to be done per-channel, if not, +// channels will spill onto each other. Once we have +// our result, in the form of an integer triplet, +// we create a new Color node to hold the result. +// +Color.prototype.operate = function (env, op, other) { + var rgb = []; + var alpha = this.alpha * (1 - other.alpha) + other.alpha; + for (var c = 0; c < 3; c++) { + rgb[c] = this._operate(env, op, this.rgb[c], other.rgb[c]); + } + return new(Color)(rgb, alpha); +}; +Color.prototype.toRGB = function () { + return toHex(this.rgb); +}; +Color.prototype.toHSL = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255, + a = this.alpha; + + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, l = (max + min) / 2, d = max - min; + + if (max === min) { + h = s = 0; + } else { + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h * 360, s: s, l: l, a: a }; +}; +//Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript +Color.prototype.toHSV = function () { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255, + a = this.alpha; + + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, v = max; + + var d = max - min; + if (max === 0) { + s = 0; + } else { + s = d / max; + } + + if (max === min) { + h = 0; + } else { + switch(max){ + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h * 360, s: s, v: v, a: a }; +}; +Color.prototype.toARGB = function () { + return toHex([this.alpha * 255].concat(this.rgb)); +}; +Color.prototype.compare = function (x) { + if (!x.rgb) { + return -1; + } + + return (x.rgb[0] === this.rgb[0] && + x.rgb[1] === this.rgb[1] && + x.rgb[2] === this.rgb[2] && + x.alpha === this.alpha) ? 0 : -1; +}; + +Color.fromKeyword = function(keyword) { + var c, key = keyword.toLowerCase(); + if (colors.hasOwnProperty(key)) { + c = new(Color)(colors[key].slice(1)); + } + else if (key === "transparent") { + c = new(Color)([0, 0, 0], 0); + } + + if (c) { + c.keyword = keyword; + return c; + } +}; +module.exports = Color; + +},{"../data/colors.js":3,"./node.js":51}],32:[function(require,module,exports){ +var Node = require("./node.js"); + +var Combinator = function (value) { + if (value === ' ') { + this.value = ' '; + } else { + this.value = value ? value.trim() : ""; + } +}; +Combinator.prototype = new Node(); +Combinator.prototype.type = "Combinator"; +var _noSpaceCombinators = { + '': true, + ' ': true, + '|': true +}; +Combinator.prototype.genCSS = function (env, output) { + var spaceOrEmpty = (env.compress || _noSpaceCombinators[this.value]) ? '' : ' '; + output.add(spaceOrEmpty + this.value + spaceOrEmpty); +}; +module.exports = Combinator; + +},{"./node.js":51}],33:[function(require,module,exports){ +var Node = require("./node.js"), + getDebugInfo = require("./debug-info.js"); + +var Comment = function (value, isLineComment, index, currentFileInfo) { + this.value = value; + this.isLineComment = isLineComment; + this.currentFileInfo = currentFileInfo; +}; +Comment.prototype = new Node(); +Comment.prototype.type = "Comment"; +Comment.prototype.genCSS = function (env, output) { + if (this.debugInfo) { + output.add(getDebugInfo(env, this), this.currentFileInfo, this.index); + } + output.add(this.value); +}; +Comment.prototype.isSilent = function(env) { + var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced), + isCompressed = env.compress && this.value[2] !== "!"; + return this.isLineComment || isReference || isCompressed; +}; +Comment.prototype.markReferenced = function () { + this.isReferenced = true; +}; +Comment.prototype.isRulesetLike = function(root) { + return Boolean(root); +}; +module.exports = Comment; + +},{"./debug-info.js":35,"./node.js":51}],34:[function(require,module,exports){ +var Node = require("./node.js"); + +var Condition = function (op, l, r, i, negate) { + this.op = op.trim(); + this.lvalue = l; + this.rvalue = r; + this.index = i; + this.negate = negate; +}; +Condition.prototype = new Node(); +Condition.prototype.type = "Condition"; +Condition.prototype.accept = function (visitor) { + this.lvalue = visitor.visit(this.lvalue); + this.rvalue = visitor.visit(this.rvalue); +}; +Condition.prototype.eval = function (env) { + var a = this.lvalue.eval(env), + b = this.rvalue.eval(env); + + var i = this.index, result; + + result = (function (op) { + switch (op) { + case 'and': + return a && b; + case 'or': + return a || b; + default: + if (a.compare) { + result = a.compare(b); + } else if (b.compare) { + result = b.compare(a); + } else { + throw { type: "Type", + message: "Unable to perform comparison", + index: i }; + } + switch (result) { + case -1: return op === '<' || op === '=<' || op === '<='; + case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; + case 1: return op === '>' || op === '>='; + } + } + })(this.op); + return this.negate ? !result : result; +}; +module.exports = Condition; + +},{"./node.js":51}],35:[function(require,module,exports){ +var debugInfo = function(env, ctx, lineSeperator) { + var result=""; + if (env.dumpLineNumbers && !env.compress) { + switch(env.dumpLineNumbers) { + case 'comments': + result = debugInfo.asComment(ctx); + break; + case 'mediaquery': + result = debugInfo.asMediaQuery(ctx); + break; + case 'all': + result = debugInfo.asComment(ctx) + (lineSeperator || "") + debugInfo.asMediaQuery(ctx); + break; + } + } + return result; +}; + +debugInfo.asComment = function(ctx) { + return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; +}; + +debugInfo.asMediaQuery = function(ctx) { + return '@media -sass-debug-info{filename{font-family:' + + ('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) { + if (a == '\\') { + a = '\/'; + } + return '\\' + a; + }) + + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; +}; + +module.exports = debugInfo; + +},{}],36:[function(require,module,exports){ +var Node = require("./node.js"), + contexts = require("../contexts.js"); + +var DetachedRuleset = function (ruleset, frames) { + this.ruleset = ruleset; + this.frames = frames; +}; +DetachedRuleset.prototype = new Node(); +DetachedRuleset.prototype.type = "DetachedRuleset"; +DetachedRuleset.prototype.evalFirst = true; +DetachedRuleset.prototype.accept = function (visitor) { + this.ruleset = visitor.visit(this.ruleset); +}; +DetachedRuleset.prototype.eval = function (env) { + var frames = this.frames || env.frames.slice(0); + return new DetachedRuleset(this.ruleset, frames); +}; +DetachedRuleset.prototype.callEval = function (env) { + return this.ruleset.eval(this.frames ? new(contexts.evalEnv)(env, this.frames.concat(env.frames)) : env); +}; +module.exports = DetachedRuleset; + +},{"../contexts.js":2,"./node.js":51}],37:[function(require,module,exports){ +var Node = require("./node.js"), + unitConversions = require("../data/unit-conversions.js"), + Unit = require("./unit.js"), + Color = require("./color.js"); + +// +// A number with a unit +// +var Dimension = function (value, unit) { + this.value = parseFloat(value); + this.unit = (unit && unit instanceof Unit) ? unit : + new(Unit)(unit ? [unit] : undefined); +}; + +Dimension.prototype = new Node(); +Dimension.prototype.type = "Dimension"; +Dimension.prototype.accept = function (visitor) { + this.unit = visitor.visit(this.unit); +}; +Dimension.prototype.eval = function (env) { + return this; +}; +Dimension.prototype.toColor = function () { + return new(Color)([this.value, this.value, this.value]); +}; +Dimension.prototype.genCSS = function (env, output) { + if ((env && env.strictUnits) && !this.unit.isSingular()) { + throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString()); + } + + var value = this.fround(env, this.value), + strValue = String(value); + + if (value !== 0 && value < 0.000001 && value > -0.000001) { + // would be output 1e-6 etc. + strValue = value.toFixed(20).replace(/0+$/, ""); + } + + if (env && env.compress) { + // Zero values doesn't need a unit + if (value === 0 && this.unit.isLength()) { + output.add(strValue); + return; + } + + // Float values doesn't need a leading zero + if (value > 0 && value < 1) { + strValue = (strValue).substr(1); + } + } + + output.add(strValue); + this.unit.genCSS(env, output); +}; + +// In an operation between two Dimensions, +// we default to the first Dimension's unit, +// so `1px + 2` will yield `3px`. +Dimension.prototype.operate = function (env, op, other) { + /*jshint noempty:false */ + var value = this._operate(env, op, this.value, other.value), + unit = this.unit.clone(); + + if (op === '+' || op === '-') { + if (unit.numerator.length === 0 && unit.denominator.length === 0) { + unit.numerator = other.unit.numerator.slice(0); + unit.denominator = other.unit.denominator.slice(0); + } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { + // do nothing + } else { + other = other.convertTo(this.unit.usedUnits()); + + if(env.strictUnits && other.unit.toString() !== unit.toString()) { + throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() + + "' and '" + other.unit.toString() + "'."); + } + + value = this._operate(env, op, this.value, other.value); + } + } else if (op === '*') { + unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); + unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); + unit.cancel(); + } else if (op === '/') { + unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); + unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); + unit.cancel(); + } + return new(Dimension)(value, unit); +}; +Dimension.prototype.compare = function (other) { + if (other instanceof Dimension) { + var a, b, + aValue, bValue; + + if (this.unit.isEmpty() || other.unit.isEmpty()) { + a = this; + b = other; + } else { + a = this.unify(); + b = other.unify(); + if (a.unit.compare(b.unit) !== 0) { + return -1; + } + } + aValue = a.value; + bValue = b.value; + + if (bValue > aValue) { + return -1; + } else if (bValue < aValue) { + return 1; + } else { + return 0; + } + } else { + return -1; + } +}; +Dimension.prototype.unify = function () { + return this.convertTo({ length: 'px', duration: 's', angle: 'rad' }); +}; +Dimension.prototype.convertTo = function (conversions) { + var value = this.value, unit = this.unit.clone(), + i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; + + if (typeof conversions === 'string') { + for(i in unitConversions) { + if (unitConversions[i].hasOwnProperty(conversions)) { + derivedConversions = {}; + derivedConversions[i] = conversions; + } + } + conversions = derivedConversions; + } + applyUnit = function (atomicUnit, denominator) { + /*jshint loopfunc:true */ + if (group.hasOwnProperty(atomicUnit)) { + if (denominator) { + value = value / (group[atomicUnit] / group[targetUnit]); + } else { + value = value * (group[atomicUnit] / group[targetUnit]); + } + + return targetUnit; + } + + return atomicUnit; + }; + + for (groupName in conversions) { + if (conversions.hasOwnProperty(groupName)) { + targetUnit = conversions[groupName]; + group = unitConversions[groupName]; + + unit.map(applyUnit); + } + } + + unit.cancel(); + + return new(Dimension)(value, unit); +}; +module.exports = Dimension; + +},{"../data/unit-conversions.js":5,"./color.js":31,"./node.js":51,"./unit.js":60}],38:[function(require,module,exports){ +var Node = require("./node.js"), + Ruleset = require("./ruleset.js"); + +var Directive = function (name, value, rules, index, currentFileInfo, debugInfo) { + this.name = name; + this.value = value; + if (rules) { + this.rules = rules; + this.rules.allowImports = true; + } + this.index = index; + this.currentFileInfo = currentFileInfo; + this.debugInfo = debugInfo; +}; + +Directive.prototype = new Node(); +Directive.prototype.type = "Directive"; +Directive.prototype.accept = function (visitor) { + var value = this.value, rules = this.rules; + if (rules) { + rules = visitor.visit(rules); + } + if (value) { + value = visitor.visit(value); + } +}; +Directive.prototype.isRulesetLike = function() { + return this.rules || !this.isCharset(); +}; +Directive.prototype.isCharset = function() { + return "@charset" === this.name; +}; +Directive.prototype.genCSS = function (env, output) { + var value = this.value, rules = this.rules; + output.add(this.name, this.currentFileInfo, this.index); + if (value) { + output.add(' '); + value.genCSS(env, output); + } + if (rules) { + this.outputRuleset(env, output, [rules]); + } else { + output.add(';'); + } +}; +Directive.prototype.eval = function (env) { + var value = this.value, rules = this.rules; + if (value) { + value = value.eval(env); + } + if (rules) { + rules = rules.eval(env); + rules.root = true; + } + return new(Directive)(this.name, value, rules, + this.index, this.currentFileInfo, this.debugInfo); +}; +Directive.prototype.variable = function (name) { if (this.rules) return Ruleset.prototype.variable.call(this.rules, name); }; +Directive.prototype.find = function () { if (this.rules) return Ruleset.prototype.find.apply(this.rules, arguments); }; +Directive.prototype.rulesets = function () { if (this.rules) return Ruleset.prototype.rulesets.apply(this.rules); }; +Directive.prototype.markReferenced = function () { + var i, rules; + this.isReferenced = true; + if (this.rules) { + rules = this.rules.rules; + for (i = 0; i < rules.length; i++) { + if (rules[i].markReferenced) { + rules[i].markReferenced(); + } + } + } +}; +Directive.prototype.outputRuleset = function (env, output, rules) { + var ruleCnt = rules.length, i; + env.tabLevel = (env.tabLevel | 0) + 1; + + // Compressed + if (env.compress) { + output.add('{'); + for (i = 0; i < ruleCnt; i++) { + rules[i].genCSS(env, output); + } + output.add('}'); + env.tabLevel--; + return; + } + + // Non-compressed + var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " "; + if (!ruleCnt) { + output.add(" {" + tabSetStr + '}'); + } else { + output.add(" {" + tabRuleStr); + rules[0].genCSS(env, output); + for (i = 1; i < ruleCnt; i++) { + output.add(tabRuleStr); + rules[i].genCSS(env, output); + } + output.add(tabSetStr + '}'); + } + + env.tabLevel--; +}; +module.exports = Directive; + +},{"./node.js":51,"./ruleset.js":57}],39:[function(require,module,exports){ +var Node = require("./node.js"), + Combinator = require("./combinator.js"); + +var Element = function (combinator, value, index, currentFileInfo) { + this.combinator = combinator instanceof Combinator ? + combinator : new(Combinator)(combinator); + + if (typeof(value) === 'string') { + this.value = value.trim(); + } else if (value) { + this.value = value; + } else { + this.value = ""; + } + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Element.prototype = new Node(); +Element.prototype.type = "Element"; +Element.prototype.accept = function (visitor) { + var value = this.value; + this.combinator = visitor.visit(this.combinator); + if (typeof value === "object") { + this.value = visitor.visit(value); + } +}; +Element.prototype.eval = function (env) { + return new(Element)(this.combinator, + this.value.eval ? this.value.eval(env) : this.value, + this.index, + this.currentFileInfo); +}; +Element.prototype.genCSS = function (env, output) { + output.add(this.toCSS(env), this.currentFileInfo, this.index); +}; +Element.prototype.toCSS = function (env) { + var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); + if (value === '' && this.combinator.value.charAt(0) === '&') { + return ''; + } else { + return this.combinator.toCSS(env || {}) + value; + } +}; +module.exports = Element; + +},{"./combinator.js":32,"./node.js":51}],40:[function(require,module,exports){ +var Node = require("./node.js"), + Paren = require("./paren.js"), + Comment = require("./comment.js"); + +var Expression = function (value) { this.value = value; }; +Expression.prototype = new Node(); +Expression.prototype.type = "Expression"; +Expression.prototype.accept = function (visitor) { + if (this.value) { + this.value = visitor.visitArray(this.value); + } +}; +Expression.prototype.eval = function (env) { + var returnValue, + inParenthesis = this.parens && !this.parensInOp, + doubleParen = false; + if (inParenthesis) { + env.inParenthesis(); + } + if (this.value.length > 1) { + returnValue = new(Expression)(this.value.map(function (e) { + return e.eval(env); + })); + } else if (this.value.length === 1) { + if (this.value[0].parens && !this.value[0].parensInOp) { + doubleParen = true; + } + returnValue = this.value[0].eval(env); + } else { + returnValue = this; + } + if (inParenthesis) { + env.outOfParenthesis(); + } + if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) { + returnValue = new(Paren)(returnValue); + } + return returnValue; +}; +Expression.prototype.genCSS = function (env, output) { + for(var i = 0; i < this.value.length; i++) { + this.value[i].genCSS(env, output); + if (i + 1 < this.value.length) { + output.add(" "); + } + } +}; +Expression.prototype.throwAwayComments = function () { + this.value = this.value.filter(function(v) { + return !(v instanceof Comment); + }); +}; +module.exports = Expression; + +},{"./comment.js":33,"./node.js":51,"./paren.js":53}],41:[function(require,module,exports){ +var Node = require("./node.js"); + +var Extend = function Extend(selector, option, index) { + this.selector = selector; + this.option = option; + this.index = index; + this.object_id = Extend.next_id++; + this.parent_ids = [this.object_id]; + + switch(option) { + case "all": + this.allowBefore = true; + this.allowAfter = true; + break; + default: + this.allowBefore = false; + this.allowAfter = false; + break; + } +}; +Extend.next_id = 0; + +Extend.prototype = new Node(); +Extend.prototype.type = "Extend"; +Extend.prototype.accept = function (visitor) { + this.selector = visitor.visit(this.selector); +}; +Extend.prototype.eval = function (env) { + return new(Extend)(this.selector.eval(env), this.option, this.index); +}; +Extend.prototype.clone = function (env) { + return new(Extend)(this.selector, this.option, this.index); +}; +Extend.prototype.findSelfSelectors = function (selectors) { + var selfElements = [], + i, + selectorElements; + + for(i = 0; i < selectors.length; i++) { + selectorElements = selectors[i].elements; + // duplicate the logic in genCSS function inside the selector node. + // future TODO - move both logics into the selector joiner visitor + if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { + selectorElements[0].combinator.value = ' '; + } + selfElements = selfElements.concat(selectors[i].elements); + } + + this.selfSelectors = [{ elements: selfElements }]; +}; +module.exports = Extend; + +},{"./node.js":51}],42:[function(require,module,exports){ +var Node = require("./node.js"), + Media = require("./media.js"), + URL = require("./url.js"), + Quoted = require("./quoted.js"), + Ruleset = require("./ruleset.js"), + Anonymous = require("./anonymous.js"); + +// +// CSS @import node +// +// The general strategy here is that we don't want to wait +// for the parsing to be completed, before we start importing +// the file. That's because in the context of a browser, +// most of the time will be spent waiting for the server to respond. +// +// On creation, we push the import path to our import queue, though +// `import,push`, we also pass it a callback, which it'll call once +// the file has been fetched, and parsed. +// +var Import = function (path, features, options, index, currentFileInfo) { + this.options = options; + this.index = index; + this.path = path; + this.features = features; + this.currentFileInfo = currentFileInfo; + + if (this.options.less !== undefined || this.options.inline) { + this.css = !this.options.less || this.options.inline; + } else { + var pathValue = this.getPath(); + if (pathValue && /css([\?;].*)?$/.test(pathValue)) { + this.css = true; + } + } +}; + +// +// The actual import node doesn't return anything, when converted to CSS. +// The reason is that it's used at the evaluation stage, so that the rules +// it imports can be treated like any other rules. +// +// In `eval`, we make sure all Import nodes get evaluated, recursively, so +// we end up with a flat structure, which can easily be imported in the parent +// ruleset. +// +Import.prototype = new Node(); +Import.prototype.type = "Import"; +Import.prototype.accept = function (visitor) { + if (this.features) { + this.features = visitor.visit(this.features); + } + this.path = visitor.visit(this.path); + if (!this.options.inline && this.root) { + this.root = visitor.visit(this.root); + } +}; +Import.prototype.genCSS = function (env, output) { + if (this.css) { + output.add("@import ", this.currentFileInfo, this.index); + this.path.genCSS(env, output); + if (this.features) { + output.add(" "); + this.features.genCSS(env, output); + } + output.add(';'); + } +}; +Import.prototype.getPath = function () { + if (this.path instanceof Quoted) { + var path = this.path.value; + return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less'; + } else if (this.path instanceof URL) { + return this.path.value.value; + } + return null; +}; +Import.prototype.evalForImport = function (env) { + return new(Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo); +}; +Import.prototype.evalPath = function (env) { + var path = this.path.eval(env); + var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; + + if (!(path instanceof URL)) { + if (rootpath) { + var pathValue = path.value; + // Add the base path if the import is relative + if (pathValue && env.isPathRelative(pathValue)) { + path.value = rootpath +pathValue; + } + } + path.value = env.normalizePath(path.value); + } + + return path; +}; +Import.prototype.eval = function (env) { + var ruleset, features = this.features && this.features.eval(env); + + if (this.skip) { + if (typeof this.skip === "function") { + this.skip = this.skip(); + } + if (this.skip) { + return []; + } + } + + if (this.options.inline) { + //todo needs to reference css file not import + var contents = new(Anonymous)(this.root, 0, {filename: this.importedFilename}, true, true); + return this.features ? new(Media)([contents], this.features.value) : [contents]; + } else if (this.css) { + var newImport = new(Import)(this.evalPath(env), features, this.options, this.index); + if (!newImport.css && this.error) { + throw this.error; + } + return newImport; + } else { + ruleset = new(Ruleset)(null, this.root.rules.slice(0)); + + ruleset.evalImports(env); + + return this.features ? new(Media)(ruleset.rules, this.features.value) : ruleset.rules; + } +}; +module.exports = Import; + +},{"./anonymous.js":27,"./media.js":47,"./node.js":51,"./quoted.js":54,"./ruleset.js":57,"./url.js":61}],43:[function(require,module,exports){ +var tree = {}; + +tree.Alpha = require('./alpha'); +tree.Color = require('./color'); +tree.Directive = require('./directive'); +tree.DetachedRuleset = require('./detached-ruleset'); +tree.Operation = require('./operation'); +tree.Dimension = require('./dimension'); +tree.Unit = require('./unit'); +tree.Keyword = require('./keyword'); +tree.Variable = require('./variable'); +tree.Ruleset = require('./ruleset'); +tree.Element = require('./element'); +tree.Attribute = require('./attribute'); +tree.Combinator = require('./combinator'); +tree.Selector = require('./selector'); +tree.Quoted = require('./quoted'); +tree.Expression = require('./expression'); +tree.Rule = require('./rule'); +tree.Call = require('./call'); +tree.URL = require('./url'); +tree.Import = require('./import'); +tree.mixin = { + Call: require('./mixin-call'), + Definition: require('./mixin-definition') +}; +tree.Comment = require('./comment'); +tree.Anonymous = require('./anonymous'); +tree.Value = require('./value'); +tree.JavaScript = require('./javascript'); +tree.Assignment = require('./assignment'); +tree.Condition = require('./condition'); +tree.Paren = require('./paren'); +tree.Media = require('./media'); +tree.UnicodeDescriptor = require('./unicode-descriptor'); +tree.Negative = require('./negative'); +tree.Extend = require('./extend'); +tree.RulesetCall = require('./ruleset-call'); + +module.exports = tree; + +},{"./alpha":26,"./anonymous":27,"./assignment":28,"./attribute":29,"./call":30,"./color":31,"./combinator":32,"./comment":33,"./condition":34,"./detached-ruleset":36,"./dimension":37,"./directive":38,"./element":39,"./expression":40,"./extend":41,"./import":42,"./javascript":44,"./keyword":46,"./media":47,"./mixin-call":48,"./mixin-definition":49,"./negative":50,"./operation":52,"./paren":53,"./quoted":54,"./rule":55,"./ruleset":57,"./ruleset-call":56,"./selector":58,"./unicode-descriptor":59,"./unit":60,"./url":61,"./value":62,"./variable":63}],44:[function(require,module,exports){ +var JsEvalNode = require("./js-eval-node.js"), + Dimension = require("./dimension.js"), + Quoted = require("./quoted.js"), + Anonymous = require("./anonymous.js"); + +var JavaScript = function (string, index, escaped) { + this.escaped = escaped; + this.expression = string; + this.index = index; +}; +JavaScript.prototype = new JsEvalNode(); +JavaScript.prototype.type = "JavaScript"; +JavaScript.prototype.eval = function(env) { + var result = this.evaluateJavaScript(this.expression, env); + + if (typeof(result) === 'number') { + return new(Dimension)(result); + } else if (typeof(result) === 'string') { + return new(Quoted)('"' + result + '"', result, this.escaped, this.index); + } else if (Array.isArray(result)) { + return new(Anonymous)(result.join(', ')); + } else { + return new(Anonymous)(result); + } +}; + +module.exports = JavaScript; + +},{"./anonymous.js":27,"./dimension.js":37,"./js-eval-node.js":45,"./quoted.js":54}],45:[function(require,module,exports){ +var Node = require("./node.js"), + Variable = require("./variable.js"); + +var jsEvalNode = function() { +}; +jsEvalNode.prototype = new Node(); + +jsEvalNode.prototype.evaluateJavaScript = function (expression, env) { + var result, + that = this, + context = {}; + + if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) { + throw { message: "You are using JavaScript, which has been disabled." , + index: this.index }; + } + + expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { + return that.jsify(new(Variable)('@' + name, that.index).eval(env)); + }); + + try { + expression = new(Function)('return (' + expression + ')'); + } catch (e) { + throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" , + index: this.index }; + } + + var variables = env.frames[0].variables(); + for (var k in variables) { + if (variables.hasOwnProperty(k)) { + /*jshint loopfunc:true */ + context[k.slice(1)] = { + value: variables[k].value, + toJS: function () { + return this.value.eval(env).toCSS(); + } + }; + } + } + + try { + result = expression.call(context); + } catch (e) { + throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" , + index: this.index }; + } + return result; +}; +jsEvalNode.prototype.jsify = function (obj) { + if (Array.isArray(obj.value) && (obj.value.length > 1)) { + return '[' + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + ']'; + } else { + return obj.toCSS(); + } +}; + +module.exports = jsEvalNode; + +},{"./node.js":51,"./variable.js":63}],46:[function(require,module,exports){ +var Node = require("./node.js"); + +var Keyword = function (value) { this.value = value; }; +Keyword.prototype = new Node(); +Keyword.prototype.type = "Keyword"; +Keyword.prototype.genCSS = function (env, output) { + if (this.value === '%') { throw { type: "Syntax", message: "Invalid % without number" }; } + output.add(this.value); +}; +Keyword.prototype.compare = function (other) { + if (other instanceof Keyword) { + return other.value === this.value ? 0 : 1; + } else { + return -1; + } +}; + +Keyword.True = new(Keyword)('true'); +Keyword.False = new(Keyword)('false'); + +module.exports = Keyword; + +},{"./node.js":51}],47:[function(require,module,exports){ +var Ruleset = require("./ruleset.js"), + Value = require("./value.js"), + Element = require("./element.js"), + Selector = require("./selector.js"), + Anonymous = require("./anonymous.js"), + Expression = require("./expression.js"), + Directive = require("./directive.js"); + +var Media = function (value, features, index, currentFileInfo) { + this.index = index; + this.currentFileInfo = currentFileInfo; + + var selectors = this.emptySelectors(); + + this.features = new(Value)(features); + this.rules = [new(Ruleset)(selectors, value)]; + this.rules[0].allowImports = true; +}; +Media.prototype = new Directive(); +Media.prototype.type = "Media"; +Media.prototype.isRulesetLike = true; +Media.prototype.accept = function (visitor) { + if (this.features) { + this.features = visitor.visit(this.features); + } + if (this.rules) { + this.rules = visitor.visitArray(this.rules); + } +}; +Media.prototype.genCSS = function (env, output) { + output.add('@media ', this.currentFileInfo, this.index); + this.features.genCSS(env, output); + this.outputRuleset(env, output, this.rules); +}; +Media.prototype.eval = function (env) { + if (!env.mediaBlocks) { + env.mediaBlocks = []; + env.mediaPath = []; + } + + var media = new(Media)(null, [], this.index, this.currentFileInfo); + if(this.debugInfo) { + this.rules[0].debugInfo = this.debugInfo; + media.debugInfo = this.debugInfo; + } + var strictMathBypass = false; + if (!env.strictMath) { + strictMathBypass = true; + env.strictMath = true; + } + try { + media.features = this.features.eval(env); + } + finally { + if (strictMathBypass) { + env.strictMath = false; + } + } + + env.mediaPath.push(media); + env.mediaBlocks.push(media); + + env.frames.unshift(this.rules[0]); + media.rules = [this.rules[0].eval(env)]; + env.frames.shift(); + + env.mediaPath.pop(); + + return env.mediaPath.length === 0 ? media.evalTop(env) : + media.evalNested(env); +}; +//TODO merge with directive +Media.prototype.variable = function (name) { return Ruleset.prototype.variable.call(this.rules[0], name); }; +Media.prototype.find = function () { return Ruleset.prototype.find.apply(this.rules[0], arguments); }; +Media.prototype.rulesets = function () { return Ruleset.prototype.rulesets.apply(this.rules[0]); }; +Media.prototype.emptySelectors = function() { + var el = new(Element)('', '&', this.index, this.currentFileInfo), + sels = [new(Selector)([el], null, null, this.index, this.currentFileInfo)]; + sels[0].mediaEmpty = true; + return sels; +}; +Media.prototype.markReferenced = function () { + var i, rules = this.rules[0].rules; + this.rules[0].markReferenced(); + this.isReferenced = true; + for (i = 0; i < rules.length; i++) { + if (rules[i].markReferenced) { + rules[i].markReferenced(); + } + } +}; +Media.prototype.evalTop = function (env) { + var result = this; + + // Render all dependent Media blocks. + if (env.mediaBlocks.length > 1) { + var selectors = this.emptySelectors(); + result = new(Ruleset)(selectors, env.mediaBlocks); + result.multiMedia = true; + } + + delete env.mediaBlocks; + delete env.mediaPath; + + return result; +}; +Media.prototype.evalNested = function (env) { + var i, value, + path = env.mediaPath.concat([this]); + + // Extract the media-query conditions separated with `,` (OR). + for (i = 0; i < path.length; i++) { + value = path[i].features instanceof Value ? + path[i].features.value : path[i].features; + path[i] = Array.isArray(value) ? value : [value]; + } + + // Trace all permutations to generate the resulting media-query. + // + // (a, b and c) with nested (d, e) -> + // a and d + // a and e + // b and c and d + // b and c and e + this.features = new(Value)(this.permute(path).map(function (path) { + path = path.map(function (fragment) { + return fragment.toCSS ? fragment : new(Anonymous)(fragment); + }); + + for(i = path.length - 1; i > 0; i--) { + path.splice(i, 0, new(Anonymous)("and")); + } + + return new(Expression)(path); + })); + + // Fake a tree-node that doesn't output anything. + return new(Ruleset)([], []); +}; +Media.prototype.permute = function (arr) { + if (arr.length === 0) { + return []; + } else if (arr.length === 1) { + return arr[0]; + } else { + var result = []; + var rest = this.permute(arr.slice(1)); + for (var i = 0; i < rest.length; i++) { + for (var j = 0; j < arr[0].length; j++) { + result.push([arr[0][j]].concat(rest[i])); + } + } + return result; + } +}; +Media.prototype.bubbleSelectors = function (selectors) { + if (!selectors) + return; + this.rules = [new(Ruleset)(selectors.slice(0), [this.rules[0]])]; +}; +module.exports = Media; + +},{"./anonymous.js":27,"./directive.js":38,"./element.js":39,"./expression.js":40,"./ruleset.js":57,"./selector.js":58,"./value.js":62}],48:[function(require,module,exports){ +var Node = require("./node.js"), + Selector = require("./selector.js"), + MixinDefinition = require("./mixin-definition.js"), + defaultFunc = require("../functions/default.js"); + +var MixinCall = function (elements, args, index, currentFileInfo, important) { + this.selector = new(Selector)(elements); + this.arguments = (args && args.length) ? args : null; + this.index = index; + this.currentFileInfo = currentFileInfo; + this.important = important; +}; +MixinCall.prototype = new Node(); +MixinCall.prototype.type = "MixinCall"; +MixinCall.prototype.accept = function (visitor) { + if (this.selector) { + this.selector = visitor.visit(this.selector); + } + if (this.arguments) { + this.arguments = visitor.visitArray(this.arguments); + } +}; +MixinCall.prototype.eval = function (env) { + var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule, + candidates = [], candidate, conditionResult = [], + defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count, originalRuleset; + + args = this.arguments && this.arguments.map(function (a) { + return { name: a.name, value: a.value.eval(env) }; + }); + + for (i = 0; i < env.frames.length; i++) { + if ((mixins = env.frames[i].find(this.selector)).length > 0) { + isOneFound = true; + + // To make `default()` function independent of definition order we have two "subpasses" here. + // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), + // and build candidate list with corresponding flags. Then, when we know all possible matches, + // we make a final decision. + + for (m = 0; m < mixins.length; m++) { + mixin = mixins[m]; + isRecursive = false; + for(f = 0; f < env.frames.length; f++) { + if ((!(mixin instanceof MixinDefinition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { + isRecursive = true; + break; + } + } + if (isRecursive) { + continue; + } + + if (mixin.matchArgs(args, env)) { + candidate = {mixin: mixin, group: defNone}; + + if (mixin.matchCondition) { + for (f = 0; f < 2; f++) { + defaultFunc.value(f); + conditionResult[f] = mixin.matchCondition(args, env); + } + if (conditionResult[0] || conditionResult[1]) { + if (conditionResult[0] != conditionResult[1]) { + candidate.group = conditionResult[1] ? + defTrue : defFalse; + } + + candidates.push(candidate); + } + } + else { + candidates.push(candidate); + } + + match = true; + } + } + + defaultFunc.reset(); + + count = [0, 0, 0]; + for (m = 0; m < candidates.length; m++) { + count[candidates[m].group]++; + } + + if (count[defNone] > 0) { + defaultResult = defFalse; + } else { + defaultResult = defTrue; + if ((count[defTrue] + count[defFalse]) > 1) { + throw { type: 'Runtime', + message: 'Ambiguous use of `default()` found when matching for `' + + this.format(args) + '`', + index: this.index, filename: this.currentFileInfo.filename }; + } + } + + for (m = 0; m < candidates.length; m++) { + candidate = candidates[m].group; + if ((candidate === defNone) || (candidate === defaultResult)) { + try { + mixin = candidates[m].mixin; + if (!(mixin instanceof MixinDefinition)) { + originalRuleset = mixin.originalRuleset || mixin; + mixin = new MixinDefinition("", [], mixin.rules, null, false); + mixin.originalRuleset = originalRuleset; + } + Array.prototype.push.apply( + rules, mixin.evalCall(env, args, this.important).rules); + } catch (e) { + throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack }; + } + } + } + + if (match) { + if (!this.currentFileInfo || !this.currentFileInfo.reference) { + for (i = 0; i < rules.length; i++) { + rule = rules[i]; + if (rule.markReferenced) { + rule.markReferenced(); + } + } + } + return rules; + } + } + } + if (isOneFound) { + throw { type: 'Runtime', + message: 'No matching definition was found for `' + this.format(args) + '`', + index: this.index, filename: this.currentFileInfo.filename }; + } else { + throw { type: 'Name', + message: this.selector.toCSS().trim() + " is undefined", + index: this.index, filename: this.currentFileInfo.filename }; + } +}; +MixinCall.prototype.format = function (args) { + return this.selector.toCSS().trim() + '(' + + (args ? args.map(function (a) { + var argValue = ""; + if (a.name) { + argValue += a.name + ":"; + } + if (a.value.toCSS) { + argValue += a.value.toCSS(); + } else { + argValue += "???"; + } + return argValue; + }).join(', ') : "") + ")"; +}; +module.exports = MixinCall; + +},{"../functions/default.js":10,"./mixin-definition.js":49,"./node.js":51,"./selector.js":58}],49:[function(require,module,exports){ +var Selector = require("./selector.js"), + Element = require("./element.js"), + Ruleset = require("./ruleset.js"), + Rule = require("./rule.js"), + Expression = require("./expression.js"), + contexts = require("../contexts.js"); + +var Definition = function (name, params, rules, condition, variadic, frames) { + this.name = name; + this.selectors = [new(Selector)([new(Element)(null, name, this.index, this.currentFileInfo)])]; + this.params = params; + this.condition = condition; + this.variadic = variadic; + this.arity = params.length; + this.rules = rules; + this._lookups = {}; + this.required = params.reduce(function (count, p) { + if (!p.name || (p.name && !p.value)) { return count + 1; } + else { return count; } + }, 0); + this.frames = frames; +}; +Definition.prototype = new Ruleset(); +Definition.prototype.type = "MixinDefinition"; +Definition.prototype.evalFirst = true; +Definition.prototype.accept = function (visitor) { + if (this.params && this.params.length) { + this.params = visitor.visitArray(this.params); + } + this.rules = visitor.visitArray(this.rules); + if (this.condition) { + this.condition = visitor.visit(this.condition); + } +}; +Definition.prototype.evalParams = function (env, mixinEnv, args, evaldArguments) { + /*jshint boss:true */ + var frame = new(Ruleset)(null, null), + varargs, arg, + params = this.params.slice(0), + i, j, val, name, isNamedFound, argIndex, argsLength = 0; + + mixinEnv = new contexts.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames)); + + if (args) { + args = args.slice(0); + argsLength = args.length; + + for(i = 0; i < argsLength; i++) { + arg = args[i]; + if (name = (arg && arg.name)) { + isNamedFound = false; + for(j = 0; j < params.length; j++) { + if (!evaldArguments[j] && name === params[j].name) { + evaldArguments[j] = arg.value.eval(env); + frame.prependRule(new(Rule)(name, arg.value.eval(env))); + isNamedFound = true; + break; + } + } + if (isNamedFound) { + args.splice(i, 1); + i--; + continue; + } else { + throw { type: 'Runtime', message: "Named argument for " + this.name + + ' ' + args[i].name + ' not found' }; + } + } + } + } + argIndex = 0; + for (i = 0; i < params.length; i++) { + if (evaldArguments[i]) { continue; } + + arg = args && args[argIndex]; + + if (name = params[i].name) { + if (params[i].variadic) { + varargs = []; + for (j = argIndex; j < argsLength; j++) { + varargs.push(args[j].value.eval(env)); + } + frame.prependRule(new(Rule)(name, new(Expression)(varargs).eval(env))); + } else { + val = arg && arg.value; + if (val) { + val = val.eval(env); + } else if (params[i].value) { + val = params[i].value.eval(mixinEnv); + frame.resetCache(); + } else { + throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + + ' (' + argsLength + ' for ' + this.arity + ')' }; + } + + frame.prependRule(new(Rule)(name, val)); + evaldArguments[i] = val; + } + } + + if (params[i].variadic && args) { + for (j = argIndex; j < argsLength; j++) { + evaldArguments[j] = args[j].value.eval(env); + } + } + argIndex++; + } + + return frame; +}; +Definition.prototype.eval = function (env) { + return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || env.frames.slice(0)); +}; +Definition.prototype.evalCall = function (env, args, important) { + var _arguments = [], + mixinFrames = this.frames ? this.frames.concat(env.frames) : env.frames, + frame = this.evalParams(env, new(contexts.evalEnv)(env, mixinFrames), args, _arguments), + rules, ruleset; + + frame.prependRule(new(Rule)('@arguments', new(Expression)(_arguments).eval(env))); + + rules = this.rules.slice(0); + + ruleset = new(Ruleset)(null, rules); + ruleset.originalRuleset = this; + ruleset = ruleset.eval(new(contexts.evalEnv)(env, [this, frame].concat(mixinFrames))); + if (important) { + ruleset = this.makeImportant.apply(ruleset); + } + return ruleset; +}; +Definition.prototype.matchCondition = function (args, env) { + if (this.condition && !this.condition.eval( + new(contexts.evalEnv)(env, + [this.evalParams(env, new(contexts.evalEnv)(env, this.frames ? this.frames.concat(env.frames) : env.frames), args, [])] // the parameter variables + .concat(this.frames) // the parent namespace/mixin frames + .concat(env.frames)))) { // the current environment frames + return false; + } + return true; +}; +Definition.prototype.matchArgs = function (args, env) { + var argsLength = (args && args.length) || 0, len; + + if (! this.variadic) { + if (argsLength < this.required) { return false; } + if (argsLength > this.params.length) { return false; } + } else { + if (argsLength < (this.required - 1)) { return false; } + } + + len = Math.min(argsLength, this.arity); + + for (var i = 0; i < len; i++) { + if (!this.params[i].name && !this.params[i].variadic) { + if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { + return false; + } + } + } + return true; +}; +module.exports = Definition; + +},{"../contexts.js":2,"./element.js":39,"./expression.js":40,"./rule.js":55,"./ruleset.js":57,"./selector.js":58}],50:[function(require,module,exports){ +var Node = require("./node.js"), + Operation = require("./operation.js"), + Dimension = require("./dimension.js"); + +var Negative = function (node) { + this.value = node; +}; +Negative.prototype = new Node(); +Negative.prototype.type = "Negative"; +Negative.prototype.genCSS = function (env, output) { + output.add('-'); + this.value.genCSS(env, output); +}; +Negative.prototype.eval = function (env) { + if (env.isMathOn()) { + return (new(Operation)('*', [new(Dimension)(-1), this.value])).eval(env); + } + return new(Negative)(this.value.eval(env)); +}; +module.exports = Negative; + +},{"./dimension.js":37,"./node.js":51,"./operation.js":52}],51:[function(require,module,exports){ +var Node = function() { +}; +Node.prototype.toCSS = function (env) { + var strs = []; + this.genCSS(env, { + add: function(chunk, fileInfo, index) { + strs.push(chunk); + }, + isEmpty: function () { + return strs.length === 0; + } + }); + return strs.join(''); +}; +Node.prototype.genCSS = function (env, output) { + output.add(this.value); +}; +Node.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +Node.prototype.eval = function () { return this; }; +Node.prototype._operate = function (env, op, a, b) { + switch (op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': return a / b; + } +}; +Node.prototype.fround = function(env, value) { + var precision = env && env.numPrecision; + //add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999....) are properly rounded... + return (precision == null) ? value : Number((value + 2e-16).toFixed(precision)); +}; +module.exports = Node; + +},{}],52:[function(require,module,exports){ +var Node = require("./node.js"), + Color = require("./color.js"), + Dimension = require("./dimension.js"); + +var Operation = function (op, operands, isSpaced) { + this.op = op.trim(); + this.operands = operands; + this.isSpaced = isSpaced; +}; +Operation.prototype = new Node(); +Operation.prototype.type = "Operation"; +Operation.prototype.accept = function (visitor) { + this.operands = visitor.visit(this.operands); +}; +Operation.prototype.eval = function (env) { + var a = this.operands[0].eval(env), + b = this.operands[1].eval(env); + + if (env.isMathOn()) { + if (a instanceof Dimension && b instanceof Color) { + a = a.toColor(); + } + if (b instanceof Dimension && a instanceof Color) { + b = b.toColor(); + } + if (!a.operate) { + throw { type: "Operation", + message: "Operation on an invalid type" }; + } + + return a.operate(env, this.op, b); + } else { + return new(Operation)(this.op, [a, b], this.isSpaced); + } +}; +Operation.prototype.genCSS = function (env, output) { + this.operands[0].genCSS(env, output); + if (this.isSpaced) { + output.add(" "); + } + output.add(this.op); + if (this.isSpaced) { + output.add(" "); + } + this.operands[1].genCSS(env, output); +}; + +module.exports = Operation; + +},{"./color.js":31,"./dimension.js":37,"./node.js":51}],53:[function(require,module,exports){ +var Node = require("./node.js"); + +var Paren = function (node) { + this.value = node; +}; +Paren.prototype = new Node(); +Paren.prototype.type = "Paren"; +Paren.prototype.genCSS = function (env, output) { + output.add('('); + this.value.genCSS(env, output); + output.add(')'); +}; +Paren.prototype.eval = function (env) { + return new(Paren)(this.value.eval(env)); +}; +module.exports = Paren; + +},{"./node.js":51}],54:[function(require,module,exports){ +var JsEvalNode = require("./js-eval-node.js"), + Variable = require("./variable.js"); + +var Quoted = function (str, content, escaped, index, currentFileInfo) { + this.escaped = escaped; + this.value = content || ''; + this.quote = str.charAt(0); + this.index = index; + this.currentFileInfo = currentFileInfo; +}; +Quoted.prototype = new JsEvalNode(); +Quoted.prototype.type = "Quoted"; +Quoted.prototype.genCSS = function (env, output) { + if (!this.escaped) { + output.add(this.quote, this.currentFileInfo, this.index); + } + output.add(this.value); + if (!this.escaped) { + output.add(this.quote); + } +}; +Quoted.prototype.eval = function (env) { + var that = this; + var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { + return String(that.evaluateJavaScript(exp, env)); + }).replace(/@\{([\w-]+)\}/g, function (_, name) { + var v = new(Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true); + return (v instanceof Quoted) ? v.value : v.toCSS(); + }); + return new(Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo); +}; +Quoted.prototype.compare = function (x) { + if (!x.toCSS) { + return -1; + } + + var left, right; + + // when comparing quoted strings allow the quote to differ + if (x.type === "Quoted" && !this.escaped && !x.escaped) { + left = x.value; + right = this.value; + } else { + left = this.toCSS(); + right = x.toCSS(); + } + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; +}; +module.exports = Quoted; + +},{"./js-eval-node.js":45,"./variable.js":63}],55:[function(require,module,exports){ +var Node = require("./node.js"), + Value = require("./value.js"), + Keyword = require("./keyword.js"); + +var Rule = function (name, value, important, merge, index, currentFileInfo, inline, variable) { + this.name = name; + this.value = (value instanceof Node) ? value : new(Value)([value]); //value instanceof tree.Value || value instanceof tree.Ruleset ?? + this.important = important ? ' ' + important.trim() : ''; + this.merge = merge; + this.index = index; + this.currentFileInfo = currentFileInfo; + this.inline = inline || false; + this.variable = (variable !== undefined) ? variable + : (name.charAt && (name.charAt(0) === '@')); +}; + +function evalName(env, name) { + var value = "", i, n = name.length, + output = {add: function (s) {value += s;}}; + for (i = 0; i < n; i++) { + name[i].eval(env).genCSS(env, output); + } + return value; +} + +Rule.prototype = new Node(); +Rule.prototype.type = "Rule"; +Rule.prototype.genCSS = function (env, output) { + output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index); + try { + this.value.genCSS(env, output); + } + catch(e) { + e.index = this.index; + e.filename = this.currentFileInfo.filename; + throw e; + } + output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index); +}; +Rule.prototype.eval = function (env) { + var strictMathBypass = false, name = this.name, evaldValue, variable = this.variable; + if (typeof name !== "string") { + // expand 'primitive' name directly to get + // things faster (~10% for benchmark.less): + name = (name.length === 1) + && (name[0] instanceof Keyword) + ? name[0].value : evalName(env, name); + variable = false; // never treat expanded interpolation as new variable name + } + if (name === "font" && !env.strictMath) { + strictMathBypass = true; + env.strictMath = true; + } + try { + evaldValue = this.value.eval(env); + + if (!this.variable && evaldValue.type === "DetachedRuleset") { + throw { message: "Rulesets cannot be evaluated on a property.", + index: this.index, filename: this.currentFileInfo.filename }; + } + + return new(Rule)(name, + evaldValue, + this.important, + this.merge, + this.index, this.currentFileInfo, this.inline, + variable); + } + catch(e) { + if (typeof e.index !== 'number') { + e.index = this.index; + e.filename = this.currentFileInfo.filename; + } + throw e; + } + finally { + if (strictMathBypass) { + env.strictMath = false; + } + } +}; +Rule.prototype.makeImportant = function () { + return new(Rule)(this.name, + this.value, + "!important", + this.merge, + this.index, this.currentFileInfo, this.inline); +}; + +module.exports = Rule; + +},{"./keyword.js":46,"./node.js":51,"./value.js":62}],56:[function(require,module,exports){ +var Node = require("./node.js"), + Variable = require("./variable.js"); + +var RulesetCall = function (variable) { + this.variable = variable; +}; +RulesetCall.prototype = new Node(); +RulesetCall.prototype.type = "RulesetCall"; +RulesetCall.prototype.eval = function (env) { + var detachedRuleset = new(Variable)(this.variable).eval(env); + return detachedRuleset.callEval(env); +}; +module.exports = RulesetCall; + +},{"./node.js":51,"./variable.js":63}],57:[function(require,module,exports){ +var Node = require("./node.js"), + Rule = require("./rule.js"), + Selector = require("./selector.js"), + Element = require("./element.js"), + contexts = require("../contexts.js"), + defaultFunc = require("../functions/default.js"), + getDebugInfo = require("./debug-info.js"); + +var Ruleset = function (selectors, rules, strictImports) { + this.selectors = selectors; + this.rules = rules; + this._lookups = {}; + this.strictImports = strictImports; +}; +Ruleset.prototype = new Node(); +Ruleset.prototype.type = "Ruleset"; +Ruleset.prototype.isRuleset = true; +Ruleset.prototype.isRulesetLike = true; +Ruleset.prototype.accept = function (visitor) { + if (this.paths) { + visitor.visitArray(this.paths, true); + } else if (this.selectors) { + this.selectors = visitor.visitArray(this.selectors); + } + if (this.rules && this.rules.length) { + this.rules = visitor.visitArray(this.rules); + } +}; +Ruleset.prototype.eval = function (env) { + var thisSelectors = this.selectors, selectors, + selCnt, selector, i, hasOnePassingSelector = false; + + if (thisSelectors && (selCnt = thisSelectors.length)) { + selectors = []; + defaultFunc.error({ + type: "Syntax", + message: "it is currently only allowed in parametric mixin guards," + }); + for (i = 0; i < selCnt; i++) { + selector = thisSelectors[i].eval(env); + selectors.push(selector); + if (selector.evaldCondition) { + hasOnePassingSelector = true; + } + } + defaultFunc.reset(); + } else { + hasOnePassingSelector = true; + } + + var rules = this.rules ? this.rules.slice(0) : null, + ruleset = new(Ruleset)(selectors, rules, this.strictImports), + rule, subRule; + + ruleset.originalRuleset = this; + ruleset.root = this.root; + ruleset.firstRoot = this.firstRoot; + ruleset.allowImports = this.allowImports; + + if(this.debugInfo) { + ruleset.debugInfo = this.debugInfo; + } + + if (!hasOnePassingSelector) { + rules.length = 0; + } + + // push the current ruleset to the frames stack + var envFrames = env.frames; + envFrames.unshift(ruleset); + + // currrent selectors + var envSelectors = env.selectors; + if (!envSelectors) { + env.selectors = envSelectors = []; + } + envSelectors.unshift(this.selectors); + + // Evaluate imports + if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { + ruleset.evalImports(env); + } + + // Store the frames around mixin definitions, + // so they can be evaluated like closures when the time comes. + var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0; + for (i = 0; i < rsRuleCnt; i++) { + if (rsRules[i].evalFirst) { + rsRules[i] = rsRules[i].eval(env); + } + } + + var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; + + // Evaluate mixin calls. + for (i = 0; i < rsRuleCnt; i++) { + if (rsRules[i].type === "MixinCall") { + /*jshint loopfunc:true */ + rules = rsRules[i].eval(env).filter(function(r) { + if ((r instanceof Rule) && r.variable) { + // do not pollute the scope if the variable is + // already there. consider returning false here + // but we need a way to "return" variable from mixins + return !(ruleset.variable(r.name)); + } + return true; + }); + rsRules.splice.apply(rsRules, [i, 1].concat(rules)); + rsRuleCnt += rules.length - 1; + i += rules.length-1; + ruleset.resetCache(); + } else if (rsRules[i].type === "RulesetCall") { + /*jshint loopfunc:true */ + rules = rsRules[i].eval(env).rules.filter(function(r) { + if ((r instanceof Rule) && r.variable) { + // do not pollute the scope at all + return false; + } + return true; + }); + rsRules.splice.apply(rsRules, [i, 1].concat(rules)); + rsRuleCnt += rules.length - 1; + i += rules.length-1; + ruleset.resetCache(); + } + } + + // Evaluate everything else + for (i = 0; i < rsRules.length; i++) { + rule = rsRules[i]; + if (!rule.evalFirst) { + rsRules[i] = rule = rule.eval ? rule.eval(env) : rule; + } + } + + // Evaluate everything else + for (i = 0; i < rsRules.length; i++) { + rule = rsRules[i]; + // for rulesets, check if it is a css guard and can be removed + if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) { + // check if it can be folded in (e.g. & where) + if (rule.selectors[0].isJustParentSelector()) { + rsRules.splice(i--, 1); + + for(var j = 0; j < rule.rules.length; j++) { + subRule = rule.rules[j]; + if (!(subRule instanceof Rule) || !subRule.variable) { + rsRules.splice(++i, 0, subRule); + } + } + } + } + } + + // Pop the stack + envFrames.shift(); + envSelectors.shift(); + + if (env.mediaBlocks) { + for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) { + env.mediaBlocks[i].bubbleSelectors(selectors); + } + } + + return ruleset; +}; +Ruleset.prototype.evalImports = function(env) { + var rules = this.rules, i, importRules; + if (!rules) { return; } + + for (i = 0; i < rules.length; i++) { + if (rules[i].type === "Import") { + importRules = rules[i].eval(env); + if (importRules && importRules.length) { + rules.splice.apply(rules, [i, 1].concat(importRules)); + i+= importRules.length-1; + } else { + rules.splice(i, 1, importRules); + } + this.resetCache(); + } + } +}; +Ruleset.prototype.makeImportant = function() { + return new Ruleset(this.selectors, this.rules.map(function (r) { + if (r.makeImportant) { + return r.makeImportant(); + } else { + return r; + } + }), this.strictImports); +}; +Ruleset.prototype.matchArgs = function (args) { + return !args || args.length === 0; +}; +// lets you call a css selector with a guard +Ruleset.prototype.matchCondition = function (args, env) { + var lastSelector = this.selectors[this.selectors.length-1]; + if (!lastSelector.evaldCondition) { + return false; + } + if (lastSelector.condition && + !lastSelector.condition.eval( + new(contexts.evalEnv)(env, + env.frames))) { + return false; + } + return true; +}; +Ruleset.prototype.resetCache = function () { + this._rulesets = null; + this._variables = null; + this._lookups = {}; +}; +Ruleset.prototype.variables = function () { + if (!this._variables) { + this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { + if (r instanceof Rule && r.variable === true) { + hash[r.name] = r; + } + return hash; + }, {}); + } + return this._variables; +}; +Ruleset.prototype.variable = function (name) { + return this.variables()[name]; +}; +Ruleset.prototype.rulesets = function () { + if (!this.rules) { return null; } + + var filtRules = [], rules = this.rules, cnt = rules.length, + i, rule; + + for (i = 0; i < cnt; i++) { + rule = rules[i]; + if (rule.isRuleset) { + filtRules.push(rule); + } + } + + return filtRules; +}; +Ruleset.prototype.prependRule = function (rule) { + var rules = this.rules; + if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } +}; +Ruleset.prototype.find = function (selector, self) { + self = self || this; + var rules = [], match, + key = selector.toCSS(); + + if (key in this._lookups) { return this._lookups[key]; } + + this.rulesets().forEach(function (rule) { + if (rule !== self) { + for (var j = 0; j < rule.selectors.length; j++) { + match = selector.match(rule.selectors[j]); + if (match) { + if (selector.elements.length > match) { + Array.prototype.push.apply(rules, rule.find( + new(Selector)(selector.elements.slice(match)), self)); + } else { + rules.push(rule); + } + break; + } + } + } + }); + this._lookups[key] = rules; + return rules; +}; +Ruleset.prototype.genCSS = function (env, output) { + var i, j, + charsetRuleNodes = [], + ruleNodes = [], + rulesetNodes = [], + rulesetNodeCnt, + debugInfo, // Line number debugging + rule, + path; + + env.tabLevel = (env.tabLevel || 0); + + if (!this.root) { + env.tabLevel++; + } + + var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "), + tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "), + sep; + + function isRulesetLikeNode(rule, root) { + // if it has nested rules, then it should be treated like a ruleset + // medias and comments do not have nested rules, but should be treated like rulesets anyway + // some directives and anonymous nodes are ruleset like, others are not + if (typeof rule.isRulesetLike === "boolean") + { + return rule.isRulesetLike; + } else if (typeof rule.isRulesetLike === "function") + { + return rule.isRulesetLike(root); + } + + //anything else is assumed to be a rule + return false; + } + + for (i = 0; i < this.rules.length; i++) { + rule = this.rules[i]; + if (isRulesetLikeNode(rule, this.root)) { + rulesetNodes.push(rule); + } else { + //charsets should float on top of everything + if (rule.isCharset && rule.isCharset()) { + charsetRuleNodes.push(rule); + } else { + ruleNodes.push(rule); + } + } + } + ruleNodes = charsetRuleNodes.concat(ruleNodes); + + // If this is the root node, we don't render + // a selector, or {}. + if (!this.root) { + debugInfo = getDebugInfo(env, this, tabSetStr); + + if (debugInfo) { + output.add(debugInfo); + output.add(tabSetStr); + } + + var paths = this.paths, pathCnt = paths.length, + pathSubCnt; + + sep = env.compress ? ',' : (',\n' + tabSetStr); + + for (i = 0; i < pathCnt; i++) { + path = paths[i]; + if (!(pathSubCnt = path.length)) { continue; } + if (i > 0) { output.add(sep); } + + env.firstSelector = true; + path[0].genCSS(env, output); + + env.firstSelector = false; + for (j = 1; j < pathSubCnt; j++) { + path[j].genCSS(env, output); + } + } + + output.add((env.compress ? '{' : ' {\n') + tabRuleStr); + } + + // Compile rules and rulesets + for (i = 0; i < ruleNodes.length; i++) { + rule = ruleNodes[i]; + + // @page{ directive ends up with root elements inside it, a mix of rules and rulesets + // In this instance we do not know whether it is the last property + if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) { + env.lastRule = true; + } + + if (rule.genCSS) { + rule.genCSS(env, output); + } else if (rule.value) { + output.add(rule.value.toString()); + } + + if (!env.lastRule) { + output.add(env.compress ? '' : ('\n' + tabRuleStr)); + } else { + env.lastRule = false; + } + } + + if (!this.root) { + output.add((env.compress ? '}' : '\n' + tabSetStr + '}')); + env.tabLevel--; + } + + sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr); + rulesetNodeCnt = rulesetNodes.length; + if (rulesetNodeCnt) { + if (ruleNodes.length && sep) { output.add(sep); } + rulesetNodes[0].genCSS(env, output); + for (i = 1; i < rulesetNodeCnt; i++) { + if (sep) { output.add(sep); } + rulesetNodes[i].genCSS(env, output); + } + } + + if (!output.isEmpty() && !env.compress && this.firstRoot) { + output.add('\n'); + } +}; +Ruleset.prototype.markReferenced = function () { + if (!this.selectors) { + return; + } + for (var s = 0; s < this.selectors.length; s++) { + this.selectors[s].markReferenced(); + } +}; +Ruleset.prototype.joinSelectors = function (paths, context, selectors) { + for (var s = 0; s < selectors.length; s++) { + this.joinSelector(paths, context, selectors[s]); + } +}; +Ruleset.prototype.joinSelector = function (paths, context, selector) { + + var i, j, k, + hasParentSelector, newSelectors, el, sel, parentSel, + newSelectorPath, afterParentJoin, newJoinedSelector, + newJoinedSelectorEmpty, lastSelector, currentElements, + selectorsMultiplied; + + for (i = 0; i < selector.elements.length; i++) { + el = selector.elements[i]; + if (el.value === '&') { + hasParentSelector = true; + } + } + + if (!hasParentSelector) { + if (context.length > 0) { + for (i = 0; i < context.length; i++) { + paths.push(context[i].concat(selector)); + } + } + else { + paths.push([selector]); + } + return; + } + + // The paths are [[Selector]] + // The first list is a list of comma seperated selectors + // The inner list is a list of inheritance seperated selectors + // e.g. + // .a, .b { + // .c { + // } + // } + // == [[.a] [.c]] [[.b] [.c]] + // + + // the elements from the current selector so far + currentElements = []; + // the current list of new selectors to add to the path. + // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors + // by the parents + newSelectors = [[]]; + + for (i = 0; i < selector.elements.length; i++) { + el = selector.elements[i]; + // non parent reference elements just get added + if (el.value !== "&") { + currentElements.push(el); + } else { + // the new list of selectors to add + selectorsMultiplied = []; + + // merge the current list of non parent selector elements + // on to the current list of selectors to add + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); + } + + // loop through our current selectors + for (j = 0; j < newSelectors.length; j++) { + sel = newSelectors[j]; + // if we don't have any parent paths, the & might be in a mixin so that it can be used + // whether there are parents or not + if (context.length === 0) { + // the combinator used on el should now be applied to the next element instead so that + // it is not lost + if (sel.length > 0) { + sel[0].elements = sel[0].elements.slice(0); + sel[0].elements.push(new(Element)(el.combinator, '', el.index, el.currentFileInfo)); + } + selectorsMultiplied.push(sel); + } + else { + // and the parent selectors + for (k = 0; k < context.length; k++) { + parentSel = context[k]; + // We need to put the current selectors + // then join the last selector's elements on to the parents selectors + + // our new selector path + newSelectorPath = []; + // selectors from the parent after the join + afterParentJoin = []; + newJoinedSelectorEmpty = true; + + //construct the joined selector - if & is the first thing this will be empty, + // if not newJoinedSelector will be the last set of elements in the selector + if (sel.length > 0) { + newSelectorPath = sel.slice(0); + lastSelector = newSelectorPath.pop(); + newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0)); + newJoinedSelectorEmpty = false; + } + else { + newJoinedSelector = selector.createDerived([]); + } + + //put together the parent selectors after the join + if (parentSel.length > 1) { + afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); + } + + if (parentSel.length > 0) { + newJoinedSelectorEmpty = false; + + // join the elements so far with the first part of the parent + newJoinedSelector.elements.push(new(Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo)); + newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); + } + + if (!newJoinedSelectorEmpty) { + // now add the joined selector + newSelectorPath.push(newJoinedSelector); + } + + // and the rest of the parent + newSelectorPath = newSelectorPath.concat(afterParentJoin); + + // add that to our new set of selectors + selectorsMultiplied.push(newSelectorPath); + } + } + } + + // our new selectors has been multiplied, so reset the state + newSelectors = selectorsMultiplied; + currentElements = []; + } + } + + // if we have any elements left over (e.g. .a& .b == .b) + // add them on to all the current selectors + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); + } + + for (i = 0; i < newSelectors.length; i++) { + if (newSelectors[i].length > 0) { + paths.push(newSelectors[i]); + } + } +}; +Ruleset.prototype.mergeElementsOnToSelectors = function(elements, selectors) { + var i, sel; + + if (selectors.length === 0) { + selectors.push([ new(Selector)(elements) ]); + return; + } + + for (i = 0; i < selectors.length; i++) { + sel = selectors[i]; + + // if the previous thing in sel is a parent this needs to join on to it + if (sel.length > 0) { + sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); + } + else { + sel.push(new(Selector)(elements)); + } + } +}; +module.exports = Ruleset; + +},{"../contexts.js":2,"../functions/default.js":10,"./debug-info.js":35,"./element.js":39,"./node.js":51,"./rule.js":55,"./selector.js":58}],58:[function(require,module,exports){ +var Node = require("./node.js"); + +var Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) { + this.elements = elements; + this.extendList = extendList; + this.condition = condition; + this.currentFileInfo = currentFileInfo || {}; + this.isReferenced = isReferenced; + if (!condition) { + this.evaldCondition = true; + } +}; +Selector.prototype = new Node(); +Selector.prototype.type = "Selector"; +Selector.prototype.accept = function (visitor) { + if (this.elements) { + this.elements = visitor.visitArray(this.elements); + } + if (this.extendList) { + this.extendList = visitor.visitArray(this.extendList); + } + if (this.condition) { + this.condition = visitor.visit(this.condition); + } +}; +Selector.prototype.createDerived = function(elements, extendList, evaldCondition) { + evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; + var newSelector = new(Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced); + newSelector.evaldCondition = evaldCondition; + newSelector.mediaEmpty = this.mediaEmpty; + return newSelector; +}; +Selector.prototype.match = function (other) { + var elements = this.elements, + len = elements.length, + olen, i; + + other.CacheElements(); + + olen = other._elements.length; + if (olen === 0 || len < olen) { + return 0; + } else { + for (i = 0; i < olen; i++) { + if (elements[i].value !== other._elements[i]) { + return 0; + } + } + } + + return olen; // return number of matched elements +}; +Selector.prototype.CacheElements = function(){ + var css = '', len, v, i; + + if( !this._elements ){ + + len = this.elements.length; + for(i = 0; i < len; i++){ + + v = this.elements[i]; + css += v.combinator.value; + + if( !v.value.value ){ + css += v.value; + continue; + } + + if( typeof v.value.value !== "string" ){ + css = ''; + break; + } + css += v.value.value; + } + + this._elements = css.match(/[,&#\*\.\w-]([\w-]|(\\.))*/g); + + if (this._elements) { + if (this._elements[0] === "&") { + this._elements.shift(); + } + + } else { + this._elements = []; + } + + } +}; +Selector.prototype.isJustParentSelector = function() { + return !this.mediaEmpty && + this.elements.length === 1 && + this.elements[0].value === '&' && + (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); +}; +Selector.prototype.eval = function (env) { + var evaldCondition = this.condition && this.condition.eval(env), + elements = this.elements, extendList = this.extendList; + + elements = elements && elements.map(function (e) { return e.eval(env); }); + extendList = extendList && extendList.map(function(extend) { return extend.eval(env); }); + + return this.createDerived(elements, extendList, evaldCondition); +}; +Selector.prototype.genCSS = function (env, output) { + var i, element; + if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") { + output.add(' ', this.currentFileInfo, this.index); + } + if (!this._css) { + //TODO caching? speed comparison? + for(i = 0; i < this.elements.length; i++) { + element = this.elements[i]; + element.genCSS(env, output); + } + } +}; +Selector.prototype.markReferenced = function () { + this.isReferenced = true; +}; +Selector.prototype.getIsReferenced = function() { + return !this.currentFileInfo.reference || this.isReferenced; +}; +Selector.prototype.getIsOutput = function() { + return this.evaldCondition; +}; +module.exports = Selector; + +},{"./node.js":51}],59:[function(require,module,exports){ +var Node = require("./node.js"); + +var UnicodeDescriptor = function (value) { + this.value = value; +}; +UnicodeDescriptor.prototype = new Node(); +UnicodeDescriptor.prototype.type = "UnicodeDescriptor"; + +module.exports = UnicodeDescriptor; + +},{"./node.js":51}],60:[function(require,module,exports){ +var Node = require("./node.js"), + unitConversions = require("../data/unit-conversions.js"); + +var Unit = function (numerator, denominator, backupUnit) { + this.numerator = numerator ? numerator.slice(0).sort() : []; + this.denominator = denominator ? denominator.slice(0).sort() : []; + this.backupUnit = backupUnit; +}; + +Unit.prototype = new Node(); +Unit.prototype.type = "Unit"; +Unit.prototype.clone = function () { + return new Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit); +}; +Unit.prototype.genCSS = function (env, output) { + if (this.numerator.length >= 1) { + output.add(this.numerator[0]); + } else + if (this.denominator.length >= 1) { + output.add(this.denominator[0]); + } else + if ((!env || !env.strictUnits) && this.backupUnit) { + output.add(this.backupUnit); + } +}; +Unit.prototype.toString = function () { + var i, returnStr = this.numerator.join("*"); + for (i = 0; i < this.denominator.length; i++) { + returnStr += "/" + this.denominator[i]; + } + return returnStr; +}; +Unit.prototype.compare = function (other) { + return this.is(other.toString()) ? 0 : -1; +}; +Unit.prototype.is = function (unitString) { + return this.toString() === unitString; +}; +Unit.prototype.isLength = function () { + return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/)); +}; +Unit.prototype.isEmpty = function () { + return this.numerator.length === 0 && this.denominator.length === 0; +}; +Unit.prototype.isSingular = function() { + return this.numerator.length <= 1 && this.denominator.length === 0; +}; +Unit.prototype.map = function(callback) { + var i; + + for (i = 0; i < this.numerator.length; i++) { + this.numerator[i] = callback(this.numerator[i], false); + } + + for (i = 0; i < this.denominator.length; i++) { + this.denominator[i] = callback(this.denominator[i], true); + } +}; +Unit.prototype.usedUnits = function() { + var group, result = {}, mapUnit; + + mapUnit = function (atomicUnit) { + /*jshint loopfunc:true */ + if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { + result[groupName] = atomicUnit; + } + + return atomicUnit; + }; + + for (var groupName in unitConversions) { + if (unitConversions.hasOwnProperty(groupName)) { + group = unitConversions[groupName]; + + this.map(mapUnit); + } + } + + return result; +}; +Unit.prototype.cancel = function () { + var counter = {}, atomicUnit, i, backup; + + for (i = 0; i < this.numerator.length; i++) { + atomicUnit = this.numerator[i]; + if (!backup) { + backup = atomicUnit; + } + counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; + } + + for (i = 0; i < this.denominator.length; i++) { + atomicUnit = this.denominator[i]; + if (!backup) { + backup = atomicUnit; + } + counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; + } + + this.numerator = []; + this.denominator = []; + + for (atomicUnit in counter) { + if (counter.hasOwnProperty(atomicUnit)) { + var count = counter[atomicUnit]; + + if (count > 0) { + for (i = 0; i < count; i++) { + this.numerator.push(atomicUnit); + } + } else if (count < 0) { + for (i = 0; i < -count; i++) { + this.denominator.push(atomicUnit); + } + } + } + } + + if (this.numerator.length === 0 && this.denominator.length === 0 && backup) { + this.backupUnit = backup; + } + + this.numerator.sort(); + this.denominator.sort(); +}; +module.exports = Unit; + +},{"../data/unit-conversions.js":5,"./node.js":51}],61:[function(require,module,exports){ +var Node = require("./node.js"); + +var URL = function (val, currentFileInfo, isEvald) { + this.value = val; + this.currentFileInfo = currentFileInfo; + this.isEvald = isEvald; +}; +URL.prototype = new Node(); +URL.prototype.type = "Url"; +URL.prototype.accept = function (visitor) { + this.value = visitor.visit(this.value); +}; +URL.prototype.genCSS = function (env, output) { + output.add("url("); + this.value.genCSS(env, output); + output.add(")"); +}; +URL.prototype.eval = function (ctx) { + var val = this.value.eval(ctx), + rootpath; + + if (!this.isEvald) { + // Add the base path if the URL is relative + rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; + if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) { + if (!val.quote) { + rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); + } + val.value = rootpath + val.value; + } + + val.value = ctx.normalizePath(val.value); + + // Add url args if enabled + if (ctx.urlArgs) { + if (!val.value.match(/^\s*data:/)) { + var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; + var urlArgs = delimiter + ctx.urlArgs; + if (val.value.indexOf('#') !== -1) { + val.value = val.value.replace('#', urlArgs + '#'); + } else { + val.value += urlArgs; + } + } + } + } + + return new(URL)(val, this.currentFileInfo, true); +}; +module.exports = URL; + +},{"./node.js":51}],62:[function(require,module,exports){ +var Node = require("./node.js"); + +var Value = function (value) { + this.value = value; +}; +Value.prototype = new Node(); +Value.prototype.type = "Value"; +Value.prototype.accept = function (visitor) { + if (this.value) { + this.value = visitor.visitArray(this.value); + } +}; +Value.prototype.eval = function (env) { + if (this.value.length === 1) { + return this.value[0].eval(env); + } else { + return new(Value)(this.value.map(function (v) { + return v.eval(env); + })); + } +}; +Value.prototype.genCSS = function (env, output) { + var i; + for(i = 0; i < this.value.length; i++) { + this.value[i].genCSS(env, output); + if (i+1 < this.value.length) { + output.add((env && env.compress) ? ',' : ', '); + } + } +}; +module.exports = Value; + +},{"./node.js":51}],63:[function(require,module,exports){ +var Node = require("./node.js"); + +var Variable = function (name, index, currentFileInfo) { + this.name = name; + this.index = index; + this.currentFileInfo = currentFileInfo || {}; +}; +Variable.prototype = new Node(); +Variable.prototype.type = "Variable"; +Variable.prototype.eval = function (env) { + var variable, name = this.name; + + if (name.indexOf('@@') === 0) { + name = '@' + new(Variable)(name.slice(1)).eval(env).value; + } + + if (this.evaluating) { + throw { type: 'Name', + message: "Recursive variable definition for " + name, + filename: this.currentFileInfo.file, + index: this.index }; + } + + this.evaluating = true; + + variable = this.find(env.frames, function (frame) { + var v = frame.variable(name); + if (v) { + return v.value.eval(env); + } + }); + if (variable) { + this.evaluating = false; + return variable; + } else { + throw { type: 'Name', + message: "variable " + name + " is undefined", + filename: this.currentFileInfo.filename, + index: this.index }; + } +}; +Variable.prototype.find = function (obj, fun) { + for (var i = 0, r; i < obj.length; i++) { + r = fun.call(obj, obj[i]); + if (r) { return r; } + } + return null; +}; +module.exports = Variable; + +},{"./node.js":51}],64:[function(require,module,exports){ +var tree = require("../tree/index.js"), + Visitor = require("./visitor.js"); + +/*jshint loopfunc:true */ + +var ExtendFinderVisitor = function() { + this._visitor = new Visitor(this); + this.contexts = []; + this.allExtendsStack = [[]]; +}; + +ExtendFinderVisitor.prototype = { + run: function (root) { + root = this._visitor.visit(root); + root.allExtends = this.allExtendsStack[0]; + return root; + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitRuleset: function (rulesetNode, visitArgs) { + if (rulesetNode.root) { + return; + } + + var i, j, extend, allSelectorsExtendList = [], extendList; + + // get &:extend(.a); rules which apply to all selectors in this ruleset + var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; + for(i = 0; i < ruleCnt; i++) { + if (rulesetNode.rules[i] instanceof tree.Extend) { + allSelectorsExtendList.push(rules[i]); + rulesetNode.extendOnEveryPath = true; + } + } + + // now find every selector and apply the extends that apply to all extends + // and the ones which apply to an individual extend + var paths = rulesetNode.paths; + for(i = 0; i < paths.length; i++) { + var selectorPath = paths[i], + selector = selectorPath[selectorPath.length - 1], + selExtendList = selector.extendList; + + extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList) + : allSelectorsExtendList; + + if (extendList) { + extendList = extendList.map(function(allSelectorsExtend) { + return allSelectorsExtend.clone(); + }); + } + + for(j = 0; j < extendList.length; j++) { + this.foundExtends = true; + extend = extendList[j]; + extend.findSelfSelectors(selectorPath); + extend.ruleset = rulesetNode; + if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } + this.allExtendsStack[this.allExtendsStack.length-1].push(extend); + } + } + + this.contexts.push(rulesetNode.selectors); + }, + visitRulesetOut: function (rulesetNode) { + if (!rulesetNode.root) { + this.contexts.length = this.contexts.length - 1; + } + }, + visitMedia: function (mediaNode, visitArgs) { + mediaNode.allExtends = []; + this.allExtendsStack.push(mediaNode.allExtends); + }, + visitMediaOut: function (mediaNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + }, + visitDirective: function (directiveNode, visitArgs) { + directiveNode.allExtends = []; + this.allExtendsStack.push(directiveNode.allExtends); + }, + visitDirectiveOut: function (directiveNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + } +}; + +var ProcessExtendsVisitor = function() { + this._visitor = new Visitor(this); +}; + +ProcessExtendsVisitor.prototype = { + run: function(root) { + var extendFinder = new ExtendFinderVisitor(); + extendFinder.run(root); + if (!extendFinder.foundExtends) { return root; } + root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); + this.allExtendsStack = [root.allExtends]; + return this._visitor.visit(root); + }, + doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { + // + // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting + // the selector we would do normally, but we are also adding an extend with the same target selector + // this means this new extend can then go and alter other extends + // + // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors + // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if + // we look at each selector at a time, as is done in visitRuleset + + var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; + + iterationCount = iterationCount || 0; + + //loop through comparing every extend with every target extend. + // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place + // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one + // and the second is the target. + // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the + // case when processing media queries + for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){ + for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){ + + extend = extendsList[extendIndex]; + targetExtend = extendsListTarget[targetExtendIndex]; + + // look for circular references + if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; } + + // find a match in the target extends self selector (the bit before :extend) + selectorPath = [targetExtend.selfSelectors[0]]; + matches = extendVisitor.findMatch(extend, selectorPath); + + if (matches.length) { + + // we found a match, so for each self selector.. + extend.selfSelectors.forEach(function(selfSelector) { + + // process the extend as usual + newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector); + + // but now we create a new extend from it + newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0); + newExtend.selfSelectors = newSelector; + + // add the extend onto the list of extends for that selector + newSelector[newSelector.length-1].extendList = [newExtend]; + + // record that we need to add it. + extendsToAdd.push(newExtend); + newExtend.ruleset = targetExtend.ruleset; + + //remember its parents for circular references + newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); + + // only process the selector once.. if we have :extend(.a,.b) then multiple + // extends will look at the same selector path, so when extending + // we know that any others will be duplicates in terms of what is added to the css + if (targetExtend.firstExtendOnThisSelectorPath) { + newExtend.firstExtendOnThisSelectorPath = true; + targetExtend.ruleset.paths.push(newSelector); + } + }); + } + } + } + + if (extendsToAdd.length) { + // try to detect circular references to stop a stack overflow. + // may no longer be needed. + this.extendChainCount++; + if (iterationCount > 100) { + var selectorOne = "{unable to calculate}"; + var selectorTwo = "{unable to calculate}"; + try + { + selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); + selectorTwo = extendsToAdd[0].selector.toCSS(); + } + catch(e) {} + throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"}; + } + + // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... + return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1)); + } else { + return extendsToAdd; + } + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitSelector: function (selectorNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitRuleset: function (rulesetNode, visitArgs) { + if (rulesetNode.root) { + return; + } + var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath; + + // look at each selector path in the ruleset, find any extend matches and then copy, find and replace + + for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { + for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { + selectorPath = rulesetNode.paths[pathIndex]; + + // extending extends happens initially, before the main pass + if (rulesetNode.extendOnEveryPath) { continue; } + var extendList = selectorPath[selectorPath.length-1].extendList; + if (extendList && extendList.length) { continue; } + + matches = this.findMatch(allExtends[extendIndex], selectorPath); + + if (matches.length) { + + allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { + selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector)); + }); + } + } + } + rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); + }, + findMatch: function (extend, haystackSelectorPath) { + // + // look through the haystack selector path to try and find the needle - extend.selector + // returns an array of selector matches that can then be replaced + // + var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, + targetCombinator, i, + extendVisitor = this, + needleElements = extend.selector.elements, + potentialMatches = [], potentialMatch, matches = []; + + // loop through the haystack elements + for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { + hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; + + for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { + + haystackElement = hackstackSelector.elements[hackstackElementIndex]; + + // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. + if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { + potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); + } + + for(i = 0; i < potentialMatches.length; i++) { + potentialMatch = potentialMatches[i]; + + // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't + // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out + // what the resulting combinator will be + targetCombinator = haystackElement.combinator.value; + if (targetCombinator === '' && hackstackElementIndex === 0) { + targetCombinator = ' '; + } + + // if we don't match, null our match to indicate failure + if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || + (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { + potentialMatch = null; + } else { + potentialMatch.matched++; + } + + // if we are still valid and have finished, test whether we have elements after and whether these are allowed + if (potentialMatch) { + potentialMatch.finished = potentialMatch.matched === needleElements.length; + if (potentialMatch.finished && + (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) { + potentialMatch = null; + } + } + // if null we remove, if not, we are still valid, so either push as a valid match or continue + if (potentialMatch) { + if (potentialMatch.finished) { + potentialMatch.length = needleElements.length; + potentialMatch.endPathIndex = haystackSelectorIndex; + potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match + potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again + matches.push(potentialMatch); + } + } else { + potentialMatches.splice(i, 1); + i--; + } + } + } + } + return matches; + }, + isElementValuesEqual: function(elementValue1, elementValue2) { + if (typeof elementValue1 === "string" || typeof elementValue2 === "string") { + return elementValue1 === elementValue2; + } + if (elementValue1 instanceof tree.Attribute) { + if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { + return false; + } + if (!elementValue1.value || !elementValue2.value) { + if (elementValue1.value || elementValue2.value) { + return false; + } + return true; + } + elementValue1 = elementValue1.value.value || elementValue1.value; + elementValue2 = elementValue2.value.value || elementValue2.value; + return elementValue1 === elementValue2; + } + elementValue1 = elementValue1.value; + elementValue2 = elementValue2.value; + if (elementValue1 instanceof tree.Selector) { + if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { + return false; + } + for(var i = 0; i currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { + path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); + currentSelectorPathElementIndex = 0; + currentSelectorPathIndex++; + } + + newElements = selector.elements + .slice(currentSelectorPathElementIndex, match.index) + .concat([firstElement]) + .concat(replacementSelector.elements.slice(1)); + + if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { + path[path.length - 1].elements = + path[path.length - 1].elements.concat(newElements); + } else { + path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); + + path.push(new tree.Selector( + newElements + )); + } + currentSelectorPathIndex = match.endPathIndex; + currentSelectorPathElementIndex = match.endPathElementIndex; + if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { + currentSelectorPathElementIndex = 0; + currentSelectorPathIndex++; + } + } + + if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { + path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); + currentSelectorPathIndex++; + } + + path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); + + return path; + }, + visitRulesetOut: function (rulesetNode) { + }, + visitMedia: function (mediaNode, visitArgs) { + var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); + newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); + this.allExtendsStack.push(newAllExtends); + }, + visitMediaOut: function (mediaNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + }, + visitDirective: function (directiveNode, visitArgs) { + var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); + newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends)); + this.allExtendsStack.push(newAllExtends); + }, + visitDirectiveOut: function (directiveNode) { + this.allExtendsStack.length = this.allExtendsStack.length - 1; + } +}; + +module.exports = ProcessExtendsVisitor; + +},{"../tree/index.js":43,"./visitor.js":69}],65:[function(require,module,exports){ +var contexts = require("../contexts.js"), + Visitor = require("./visitor.js"); + +var ImportVisitor = function(importer, finish, evalEnv, onceFileDetectionMap, recursionDetector) { + this._visitor = new Visitor(this); + this._importer = importer; + this._finish = finish; + this.env = evalEnv || new contexts.evalEnv(); + this.importCount = 0; + this.onceFileDetectionMap = onceFileDetectionMap || {}; + this.recursionDetector = {}; + if (recursionDetector) { + for(var fullFilename in recursionDetector) { + if (recursionDetector.hasOwnProperty(fullFilename)) { + this.recursionDetector[fullFilename] = true; + } + } + } +}; + +ImportVisitor.prototype = { + isReplacing: true, + run: function (root) { + var error; + try { + // process the contents + this._visitor.visit(root); + } + catch(e) { + error = e; + } + + this.isFinished = true; + + if (this.importCount === 0) { + this._finish(error); + } + }, + visitImport: function (importNode, visitArgs) { + var importVisitor = this, + evaldImportNode, + inlineCSS = importNode.options.inline; + + if (!importNode.css || inlineCSS) { + + try { + evaldImportNode = importNode.evalForImport(this.env); + } catch(e){ + if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } + // attempt to eval properly and treat as css + importNode.css = true; + // if that fails, this error will be thrown + importNode.error = e; + } + + if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { + importNode = evaldImportNode; + this.importCount++; + var env = new contexts.evalEnv(this.env, this.env.frames.slice(0)); + + if (importNode.options.multiple) { + env.importMultiple = true; + } + + this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, importedAtRoot, fullPath) { + if (e && !e.filename) { + e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; + } + + var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector; + if (!env.importMultiple) { + if (duplicateImport) { + importNode.skip = true; + } else { + importNode.skip = function() { + if (fullPath in importVisitor.onceFileDetectionMap) { + return true; + } + importVisitor.onceFileDetectionMap[fullPath] = true; + return false; + }; + } + } + + var subFinish = function(e) { + importVisitor.importCount--; + + if (importVisitor.importCount === 0 && importVisitor.isFinished) { + importVisitor._finish(e); + } + }; + + if (root) { + importNode.root = root; + importNode.importedFilename = fullPath; + + if (!inlineCSS && (env.importMultiple || !duplicateImport)) { + importVisitor.recursionDetector[fullPath] = true; + new(ImportVisitor)(importVisitor._importer, subFinish, env, importVisitor.onceFileDetectionMap, importVisitor.recursionDetector) + .run(root); + return; + } + } + + subFinish(); + }); + } + } + visitArgs.visitDeeper = false; + return importNode; + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + return ruleNode; + }, + visitDirective: function (directiveNode, visitArgs) { + this.env.frames.unshift(directiveNode); + return directiveNode; + }, + visitDirectiveOut: function (directiveNode) { + this.env.frames.shift(); + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + this.env.frames.unshift(mixinDefinitionNode); + return mixinDefinitionNode; + }, + visitMixinDefinitionOut: function (mixinDefinitionNode) { + this.env.frames.shift(); + }, + visitRuleset: function (rulesetNode, visitArgs) { + this.env.frames.unshift(rulesetNode); + return rulesetNode; + }, + visitRulesetOut: function (rulesetNode) { + this.env.frames.shift(); + }, + visitMedia: function (mediaNode, visitArgs) { + this.env.frames.unshift(mediaNode.rules[0]); + return mediaNode; + }, + visitMediaOut: function (mediaNode) { + this.env.frames.shift(); + } +}; +module.exports = ImportVisitor; + +},{"../contexts.js":2,"./visitor.js":69}],66:[function(require,module,exports){ +var visitors = { + Visitor: require("./visitor"), + ImportVisitor: require('./import-visitor.js'), + ExtendVisitor: require('./extend-visitor.js'), + JoinSelectorVisitor: require('./join-selector-visitor.js'), + ToCSSVisitor: require('./to-css-visitor.js') +}; + +module.exports = visitors; + +},{"./extend-visitor.js":64,"./import-visitor.js":65,"./join-selector-visitor.js":67,"./to-css-visitor.js":68,"./visitor":69}],67:[function(require,module,exports){ +var Visitor = require("./visitor.js"); + +var JoinSelectorVisitor = function() { + this.contexts = [[]]; + this._visitor = new Visitor(this); +}; + +JoinSelectorVisitor.prototype = { + run: function (root) { + return this._visitor.visit(root); + }, + visitRule: function (ruleNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { + visitArgs.visitDeeper = false; + }, + + visitRuleset: function (rulesetNode, visitArgs) { + var context = this.contexts[this.contexts.length - 1], + paths = [], selectors; + + this.contexts.push(paths); + + if (! rulesetNode.root) { + selectors = rulesetNode.selectors; + if (selectors) { + selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); + rulesetNode.selectors = selectors.length ? selectors : (selectors = null); + if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } + } + if (!selectors) { rulesetNode.rules = null; } + rulesetNode.paths = paths; + } + }, + visitRulesetOut: function (rulesetNode) { + this.contexts.length = this.contexts.length - 1; + }, + visitMedia: function (mediaNode, visitArgs) { + var context = this.contexts[this.contexts.length - 1]; + mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); + } +}; + +module.exports = JoinSelectorVisitor; + +},{"./visitor.js":69}],68:[function(require,module,exports){ +var tree = require("../tree/index.js"), + Visitor = require("./visitor.js"); + +var ToCSSVisitor = function(env) { + this._visitor = new Visitor(this); + this._env = env; +}; + +ToCSSVisitor.prototype = { + isReplacing: true, + run: function (root) { + return this._visitor.visit(root); + }, + + visitRule: function (ruleNode, visitArgs) { + if (ruleNode.variable) { + return []; + } + return ruleNode; + }, + + visitMixinDefinition: function (mixinNode, visitArgs) { + // mixin definitions do not get eval'd - this means they keep state + // so we have to clear that state here so it isn't used if toCSS is called twice + mixinNode.frames = []; + return []; + }, + + visitExtend: function (extendNode, visitArgs) { + return []; + }, + + visitComment: function (commentNode, visitArgs) { + if (commentNode.isSilent(this._env)) { + return []; + } + return commentNode; + }, + + visitMedia: function(mediaNode, visitArgs) { + mediaNode.accept(this._visitor); + visitArgs.visitDeeper = false; + + if (!mediaNode.rules.length) { + return []; + } + return mediaNode; + }, + + visitDirective: function(directiveNode, visitArgs) { + if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) { + return []; + } + if (directiveNode.name === "@charset") { + // Only output the debug info together with subsequent @charset definitions + // a comment (or @media statement) before the actual @charset directive would + // be considered illegal css as it has to be on the first line + if (this.charset) { + if (directiveNode.debugInfo) { + var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n"); + comment.debugInfo = directiveNode.debugInfo; + return this._visitor.visit(comment); + } + return []; + } + this.charset = true; + } + if (directiveNode.rules && directiveNode.rules.rules) { + this._mergeRules(directiveNode.rules.rules); + } + return directiveNode; + }, + + checkPropertiesInRoot: function(rules) { + var ruleNode; + for(var i = 0; i < rules.length; i++) { + ruleNode = rules[i]; + if (ruleNode instanceof tree.Rule && !ruleNode.variable) { + throw { message: "properties must be inside selector blocks, they cannot be in the root.", + index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null}; + } + } + }, + + visitRuleset: function (rulesetNode, visitArgs) { + var rule, rulesets = []; + if (rulesetNode.firstRoot) { + this.checkPropertiesInRoot(rulesetNode.rules); + } + if (! rulesetNode.root) { + if (rulesetNode.paths) { + rulesetNode.paths = rulesetNode.paths + .filter(function(p) { + var i; + if (p[0].elements[0].combinator.value === ' ') { + p[0].elements[0].combinator = new(tree.Combinator)(''); + } + for(i = 0; i < p.length; i++) { + if (p[i].getIsReferenced() && p[i].getIsOutput()) { + return true; + } + } + return false; + }); + } + + // Compile rules and rulesets + var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; + for (var i = 0; i < nodeRuleCnt; ) { + rule = nodeRules[i]; + if (rule && rule.rules) { + // visit because we are moving them out from being a child + rulesets.push(this._visitor.visit(rule)); + nodeRules.splice(i, 1); + nodeRuleCnt--; + continue; + } + i++; + } + // accept the visitor to remove rules and refactor itself + // then we can decide now whether we want it or not + if (nodeRuleCnt > 0) { + rulesetNode.accept(this._visitor); + } else { + rulesetNode.rules = null; + } + visitArgs.visitDeeper = false; + + nodeRules = rulesetNode.rules; + if (nodeRules) { + this._mergeRules(nodeRules); + nodeRules = rulesetNode.rules; + } + if (nodeRules) { + this._removeDuplicateRules(nodeRules); + nodeRules = rulesetNode.rules; + } + + // now decide whether we keep the ruleset + if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) { + rulesets.splice(0, 0, rulesetNode); + } + } else { + rulesetNode.accept(this._visitor); + visitArgs.visitDeeper = false; + if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) { + rulesets.splice(0, 0, rulesetNode); + } + } + if (rulesets.length === 1) { + return rulesets[0]; + } + return rulesets; + }, + + _removeDuplicateRules: function(rules) { + if (!rules) { return; } + + // remove duplicates + var ruleCache = {}, + ruleList, rule, i; + + for(i = rules.length - 1; i >= 0 ; i--) { + rule = rules[i]; + if (rule instanceof tree.Rule) { + if (!ruleCache[rule.name]) { + ruleCache[rule.name] = rule; + } else { + ruleList = ruleCache[rule.name]; + if (ruleList instanceof tree.Rule) { + ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)]; + } + var ruleCSS = rule.toCSS(this._env); + if (ruleList.indexOf(ruleCSS) !== -1) { + rules.splice(i, 1); + } else { + ruleList.push(ruleCSS); + } + } + } + } + }, + + _mergeRules: function (rules) { + if (!rules) { return; } + + var groups = {}, + parts, + rule, + key; + + for (var i = 0; i < rules.length; i++) { + rule = rules[i]; + + if ((rule instanceof tree.Rule) && rule.merge) { + key = [rule.name, + rule.important ? "!" : ""].join(","); + + if (!groups[key]) { + groups[key] = []; + } else { + rules.splice(i--, 1); + } + + groups[key].push(rule); + } + } + + Object.keys(groups).map(function (k) { + + function toExpression(values) { + return new (tree.Expression)(values.map(function (p) { + return p.value; + })); + } + + function toValue(values) { + return new (tree.Value)(values.map(function (p) { + return p; + })); + } + + parts = groups[k]; + + if (parts.length > 1) { + rule = parts[0]; + var spacedGroups = []; + var lastSpacedGroup = []; + parts.map(function (p) { + if (p.merge==="+") { + if (lastSpacedGroup.length > 0) { + spacedGroups.push(toExpression(lastSpacedGroup)); + } + lastSpacedGroup = []; + } + lastSpacedGroup.push(p); + }); + spacedGroups.push(toExpression(lastSpacedGroup)); + rule.value = toValue(spacedGroups); + } + }); + } +}; + +module.exports = ToCSSVisitor; + +},{"../tree/index.js":43,"./visitor.js":69}],69:[function(require,module,exports){ +var tree = require("../tree/index.js"); + +var _visitArgs = { visitDeeper: true }, + _hasIndexed = false; + +function _noop(node) { + return node; +} + +function indexNodeTypes(parent, ticker) { + // add .typeIndex to tree node types for lookup table + var key, child; + for (key in parent) { + if (parent.hasOwnProperty(key)) { + child = parent[key]; + switch (typeof child) { + case "function": + // ignore bound functions directly on tree which do not have a prototype + // or aren't nodes + if (child.prototype && child.prototype.type) { + child.prototype.typeIndex = ticker++; + } + break; + case "object": + ticker = indexNodeTypes(child, ticker); + break; + } + } + } + return ticker; +} + +var Visitor = function(implementation) { + this._implementation = implementation; + this._visitFnCache = []; + + if (!_hasIndexed) { + indexNodeTypes(tree, 1); + _hasIndexed = true; + } +}; + +Visitor.prototype = { + visit: function(node) { + if (!node) { + return node; + } + + var nodeTypeIndex = node.typeIndex; + if (!nodeTypeIndex) { + return node; + } + + var visitFnCache = this._visitFnCache, + impl = this._implementation, + aryIndx = nodeTypeIndex << 1, + outAryIndex = aryIndx | 1, + func = visitFnCache[aryIndx], + funcOut = visitFnCache[outAryIndex], + visitArgs = _visitArgs, + fnName; + + visitArgs.visitDeeper = true; + + if (!func) { + fnName = "visit" + node.type; + func = impl[fnName] || _noop; + funcOut = impl[fnName + "Out"] || _noop; + visitFnCache[aryIndx] = func; + visitFnCache[outAryIndex] = funcOut; + } + + if (func !== _noop) { + var newNode = func.call(impl, node, visitArgs); + if (impl.isReplacing) { + node = newNode; + } + } + + if (visitArgs.visitDeeper && node && node.accept) { + node.accept(this); + } + + if (funcOut != _noop) { + funcOut.call(impl, node); + } + + return node; + }, + visitArray: function(nodes, nonReplacing) { + if (!nodes) { + return nodes; + } + + var cnt = nodes.length, i; + + // Non-replacing + if (nonReplacing || !this._implementation.isReplacing) { + for (i = 0; i < cnt; i++) { + this.visit(nodes[i]); + } + return nodes; + } + + // Replacing + var out = []; + for (i = 0; i < cnt; i++) { + var evald = this.visit(nodes[i]); + if (!evald.splice) { + out.push(evald); + } else if (evald.length) { + this.flatten(evald, out); + } + } + return out; + }, + flatten: function(arr, out) { + if (!out) { + out = []; + } + + var cnt, i, item, + nestedCnt, j, nestedItem; + + for (i = 0, cnt = arr.length; i < cnt; i++) { + item = arr[i]; + if (!item.splice) { + out.push(item); + continue; + } + + for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { + nestedItem = item[j]; + if (!nestedItem.splice) { + out.push(nestedItem); + } else if (nestedItem.length) { + this.flatten(nestedItem, out); + } + } + } + + return out; + } +}; +module.exports = Visitor; + +},{"../tree/index.js":43}]},{},[1]) \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/mkdirp/.npmignore b/node_modules/less-middleware/node_modules/mkdirp/.npmignore new file mode 100644 index 000000000..9303c347e --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log \ No newline at end of file diff --git a/node_modules/less-middleware/node_modules/mkdirp/.travis.yml b/node_modules/less-middleware/node_modules/mkdirp/.travis.yml new file mode 100644 index 000000000..84fd7ca24 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.9 diff --git a/node_modules/less-middleware/node_modules/mkdirp/LICENSE b/node_modules/less-middleware/node_modules/mkdirp/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/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/less-middleware/node_modules/mkdirp/examples/pow.js b/node_modules/less-middleware/node_modules/mkdirp/examples/pow.js new file mode 100644 index 000000000..e6924212e --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/examples/pow.js @@ -0,0 +1,6 @@ +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/index.js b/node_modules/less-middleware/node_modules/mkdirp/index.js new file mode 100644 index 000000000..fda6de8a2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/index.js @@ -0,0 +1,82 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, mode, f, made) { + if (typeof mode === 'function' || mode === undefined) { + f = mode; + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + fs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), mode, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, mode, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + fs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, mode, made) { + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + try { + fs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), mode, made); + sync(p, mode, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = fs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/less-middleware/node_modules/mkdirp/package.json b/node_modules/less-middleware/node_modules/mkdirp/package.json new file mode 100644 index 000000000..3fbe0271b --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/package.json @@ -0,0 +1,36 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.3.5", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "main": "./index", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "http://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "~0.4.0" + }, + "license": "MIT", + "readme": "# mkdirp\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\n# example\n\n## pow.js\n\n```js\nvar mkdirp = require('mkdirp');\n \nmkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n});\n```\n\nOutput\n\n```\npow!\n```\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\n# methods\n\n```js\nvar mkdirp = require('mkdirp');\n```\n\n## mkdirp(dir, mode, cb)\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\n## mkdirp.sync(dir, mode)\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "homepage": "https://github.com/substack/node-mkdirp", + "_id": "mkdirp@0.3.5", + "_shasum": "de3e5f8961c88c787ee1368df849ac4413eca8d7", + "_from": "mkdirp@~0.3.5", + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.5.tgz" +} diff --git a/node_modules/less-middleware/node_modules/mkdirp/readme.markdown b/node_modules/less-middleware/node_modules/mkdirp/readme.markdown new file mode 100644 index 000000000..83b0216ab --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/readme.markdown @@ -0,0 +1,63 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, mode, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `mode`. + +If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +## mkdirp.sync(dir, mode) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `mode`. + +If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +# license + +MIT diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/chmod.js b/node_modules/less-middleware/node_modules/mkdirp/test/chmod.js new file mode 100644 index 000000000..520dcb8e9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/chmod.js @@ -0,0 +1,38 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +test('chmod-pre', function (t) { + var mode = 0744 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); + t.end(); + }); + }); +}); + +test('chmod', function (t) { + var mode = 0755 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.end(); + }); + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/clobber.js b/node_modules/less-middleware/node_modules/mkdirp/test/clobber.js new file mode 100644 index 000000000..0eb709987 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/clobber.js @@ -0,0 +1,37 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +// a file in the way +var itw = ps.slice(0, 3).join('/'); + + +test('clobber-pre', function (t) { + console.error("about to write to "+itw) + fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); + + fs.stat(itw, function (er, stat) { + t.ifError(er) + t.ok(stat && stat.isFile(), 'should be file') + t.end() + }) +}) + +test('clobber', function (t) { + t.plan(2); + mkdirp(file, 0755, function (err) { + t.ok(err); + t.equal(err.code, 'ENOTDIR'); + t.end(); + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/mkdirp.js b/node_modules/less-middleware/node_modules/mkdirp/test/mkdirp.js new file mode 100644 index 000000000..b07cd70c1 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/mkdirp.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('woo', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/perm.js b/node_modules/less-middleware/node_modules/mkdirp/test/perm.js new file mode 100644 index 000000000..23a7abbd2 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/perm.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('async perm', function (t) { + t.plan(2); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); + +test('async root perm', function (t) { + mkdirp('/tmp', 0755, function (err) { + if (err) t.fail(err); + t.end(); + }); + t.end(); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/perm_sync.js b/node_modules/less-middleware/node_modules/mkdirp/test/perm_sync.js new file mode 100644 index 000000000..f685f6090 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/perm_sync.js @@ -0,0 +1,39 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('sync perm', function (t) { + t.plan(2); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; + + mkdirp.sync(file, 0755); + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }); +}); + +test('sync root perm', function (t) { + t.plan(1); + + var file = '/tmp'; + mkdirp.sync(file, 0755); + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/race.js b/node_modules/less-middleware/node_modules/mkdirp/test/race.js new file mode 100644 index 000000000..96a044763 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/race.js @@ -0,0 +1,41 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('race', function (t) { + t.plan(4); + var ps = [ '', 'tmp' ]; + + for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); + } + var file = ps.join('/'); + + var res = 2; + mk(file, function () { + if (--res === 0) t.end(); + }); + + mk(file, function () { + if (--res === 0) t.end(); + }); + + function mk (file, cb) { + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + if (cb) cb(); + } + }) + }) + }); + } +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/rel.js b/node_modules/less-middleware/node_modules/mkdirp/test/rel.js new file mode 100644 index 000000000..79858243a --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/rel.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('rel', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var cwd = process.cwd(); + process.chdir('/tmp'); + + var file = [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + process.chdir(cwd); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/return.js b/node_modules/less-middleware/node_modules/mkdirp/test/return.js new file mode 100644 index 000000000..bce68e561 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/return.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, '/tmp/' + x); + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, null); + }); + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/return_sync.js b/node_modules/less-middleware/node_modules/mkdirp/test/return_sync.js new file mode 100644 index 000000000..7c222d355 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/return_sync.js @@ -0,0 +1,24 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + // Note that this will throw on failure, which will fail the test. + var made = mkdirp.sync(file); + t.equal(made, '/tmp/' + x); + + // making the same file again should have no effect. + made = mkdirp.sync(file); + t.equal(made, null); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/root.js b/node_modules/less-middleware/node_modules/mkdirp/test/root.js new file mode 100644 index 000000000..97ad7a2f3 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/root.js @@ -0,0 +1,18 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('root', function (t) { + // '/' on unix, 'c:/' on windows. + var file = path.resolve('/'); + + mkdirp(file, 0755, function (err) { + if (err) throw err + fs.stat(file, function (er, stat) { + if (er) throw er + t.ok(stat.isDirectory(), 'target is a directory'); + t.end(); + }) + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/sync.js b/node_modules/less-middleware/node_modules/mkdirp/test/sync.js new file mode 100644 index 000000000..7530cada8 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('sync', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file, 0755); + } catch (err) { + t.fail(err); + return t.end(); + } + + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }); + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/umask.js b/node_modules/less-middleware/node_modules/mkdirp/test/umask.js new file mode 100644 index 000000000..64ccafe22 --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/umask.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('implicit mode from umask', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, function (err) { + if (err) t.fail(err); + else path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, 0777 & (~process.umask())); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }) + }) + }); +}); diff --git a/node_modules/less-middleware/node_modules/mkdirp/test/umask_sync.js b/node_modules/less-middleware/node_modules/mkdirp/test/umask_sync.js new file mode 100644 index 000000000..35bd5cbbf --- /dev/null +++ b/node_modules/less-middleware/node_modules/mkdirp/test/umask_sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('umask sync modes', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file); + } catch (err) { + t.fail(err); + return t.end(); + } + + path.exists(file, function (ex) { + if (!ex) t.fail('file not created') + else fs.stat(file, function (err, stat) { + if (err) t.fail(err) + else { + t.equal(stat.mode & 0777, (0777 & (~process.umask()))); + t.ok(stat.isDirectory(), 'target not a directory'); + t.end(); + } + }); + }); +}); diff --git a/node_modules/less-middleware/node_modules/node.extend/.npmignore b/node_modules/less-middleware/node_modules/node.extend/.npmignore new file mode 100644 index 000000000..f1250e584 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/less-middleware/node_modules/node.extend/.travis.yml b/node_modules/less-middleware/node_modules/node.extend/.travis.yml new file mode 100644 index 000000000..301843aa9 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" + - "0.6" + - "0.4" + diff --git a/node_modules/less-middleware/node_modules/node.extend/History.md b/node_modules/less-middleware/node_modules/node.extend/History.md new file mode 100644 index 000000000..633fb9309 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/History.md @@ -0,0 +1,21 @@ +## 1.0.1 / 2013-04-02 + + - Fix tests + + + +## 1.0.0 / 2012-02-28 + + - Add tests for the stable release + + + +## 0.0.2 / 2012-01-11 + + - Add repository to package.json + + + +## 0.0.1 / 2012-01-10 + + - Initial release diff --git a/node_modules/less-middleware/node_modules/node.extend/Readme.md b/node_modules/less-middleware/node_modules/node.extend/Readme.md new file mode 100644 index 000000000..524b173bb --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/Readme.md @@ -0,0 +1,73 @@ +# node.extend + +A port of jQuery.extend that **actually works** on node.js + +[![Build Status][3]][4] [![dependency status][5]][6] + +[![browser support][1]][2] + + +## Description + +None of the existing ones on npm really work therefore I ported it myself. + + + +## Usage + +To install this module in your current working directory (which should already contain a package.json), run + +``` +npm install node.extend +``` + +You can additionally just list the module in your [package.json](https://npmjs.org/doc/json.html) and run npm install. + +Then, require this package where you need it: + +``` +var extend = require('node.extend'); +``` + +The syntax for merging two objects is as follows: + +``` +var destObject = extend({}, sourceObject); +// Where sourceObject is the object whose properties will be copied into another. +// NOTE: In this situation, this is not a deep merge. See below on how to handle a deep merge. +``` + +For information about how the clone works internally, view source in lib/extend.js or checkout the doc from [jQuery][] + +### A Note About Deep Merge (avoiding pass-by-reference cloning) + +In order to force a deep merge, when extending an object, you must pass boolean true as the first argument to extend: + +``` +var destObject = extend(true, {}, sourceObject); +// Where sourceObject is the object whose properties will be copied into another. +``` + +See [this article](http://www.jon-carlos.com/2013/is-javascript-call-by-value-or-call-by-reference/) for more information about the need for deep merges in JavaScript. + +## Credit + +- Jordan Harband [@ljharb][] + + + +## License + +Copyright 2011, John Resig +Dual licensed under the MIT or GPL Version 2 licenses. +http://jquery.org/license + +[1]: https://ci.testling.com/dreamerslab/node.extend.png +[2]: https://ci.testling.com/dreamerslab/node.extend +[3]: https://travis-ci.org/dreamerslab/node.extend.png +[4]: https://travis-ci.org/dreamerslab/node.extend +[5]: https://david-dm.org/dreamerslab/node.extend.png +[6]: https://david-dm.org/dreamerslab/node.extend +[jQuery]: http://api.jquery.com/jQuery.extend/ +[@ljharb]: https://twitter.com/ljharb + diff --git a/node_modules/less-middleware/node_modules/node.extend/index.js b/node_modules/less-middleware/node_modules/node.extend/index.js new file mode 100644 index 000000000..52ee121a4 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/index.js @@ -0,0 +1,2 @@ +module.exports = require('./lib/extend'); + diff --git a/node_modules/less-middleware/node_modules/node.extend/lib/extend.js b/node_modules/less-middleware/node_modules/node.extend/lib/extend.js new file mode 100644 index 000000000..78e999194 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/lib/extend.js @@ -0,0 +1,82 @@ +/*! + * node.extend + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * @fileoverview + * Port of jQuery.extend that actually works on node.js + */ +var is = require('is'); + +function extend() { + var target = arguments[0] || {}; + var i = 1; + var length = arguments.length; + var deep = false; + var options, name, src, copy, copy_is_array, clone; + + // 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' && !is.fn(target)) { + target = {}; + } + + for (; i < length; i++) { + // Only deal with non-null/undefined values + options = arguments[i] + if (options != null) { + if (typeof options === 'string') { + options = options.split(''); + } + // 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 && (is.hash(copy) || (copy_is_array = is.array(copy)))) { + if (copy_is_array) { + copy_is_array = false; + clone = src && is.array(src) ? src : []; + } else { + clone = src && is.hash(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = extend(deep, clone, copy); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +/** + * @public + */ +extend.version = '1.0.8'; + +/** + * Exports module. + */ +module.exports = extend; + diff --git a/node_modules/less-middleware/node_modules/node.extend/node_modules/is/LICENSE.md b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/LICENSE.md new file mode 100644 index 000000000..b0b7e1a85 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/LICENSE.md @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Enrico Marino + +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/less-middleware/node_modules/node.extend/node_modules/is/README.md b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/README.md new file mode 100644 index 000000000..16cb56af5 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/README.md @@ -0,0 +1,131 @@ +# is + +The definitive JavaScript type testing library + +To be or not to be? This is the library! + +[![browser support][1]][2] + +## Installation + +As a node.js module + + $ npm install is + +As a component + + $ component install enricomarino/is + +## API + +### general + + - is.a (value, type) or is.type (value, type) + - is.defined (value) + - is.empty (value) + - is.equal (value, other) + - is.hosted (value, host) + - is.instance (value, constructor) + - is.instanceof (value, constructor) - deprecated, because in ES3 browsers, "instanceof" is a reserved word + - is.null (value) - deprecated, because in ES3 browsers, "null" is a reserved word + - is.undef (value) + - is.undefined (value) - deprecated, because in ES3 browsers, "undefined" is a reserved word + +### arguments + + - is.args (value) + - is.arguments (value) - deprecated, because "arguments" is a reserved word + - is.args.empty (value) + +### array + + - is.array (value) + - is.array.empty (value) + - is.arraylike (value) + +### boolean + + - is.boolean (value) + - is.false (value) - deprecated, because in ES3 browsers, "false" is a reserved word + - is.true (value) - deprecated, because in ES3 browsers, "true" is a reserved word + +### date + + - is.date (value) + +### element + + - is.element (value) + +### error + + - is.error (value) + +### function + + - is.fn(value) + - is.function(value) - deprecated, because in ES3 browsers, "function" is a reserved word + +### number + + - is.number (value) + - is.infinite (value) + - is.decimal (value) + - is.divisibleBy (value, n) + - is.int (value) + - is.maximum (value, others) + - is.minimum (value, others) + - is.nan (value) + - is.even (value) + - is.odd (value) + - is.ge (value, other) + - is.gt (value, other) + - is.le (value, other) + - is.lt (value, other) + - is.within (value, start, finish) + +### object + + - is.object (value) + +### regexp + + - is.regexp (value) + +### string + + - is.string (value) + + +## Contributors + +- [Jordan Harband](https://github.com/ljharb) + +## License + +(The MIT License) + +Copyright (c) 2013 Enrico Marino + +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. + +[1]: https://ci.testling.com/enricomarino/is.png +[2]: https://ci.testling.com/enricomarino/is + diff --git a/node_modules/less-middleware/node_modules/node.extend/node_modules/is/component.json b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/component.json new file mode 100644 index 000000000..50f6cd91e --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/component.json @@ -0,0 +1,8 @@ +{ + "name": "is", + "repo": "enricomarino/is", + "description": "The definitive type testing library", + "version": "0.2.0", + "dependencies": {}, + "scripts": ["index.js"] +} diff --git a/node_modules/less-middleware/node_modules/node.extend/node_modules/is/index.js b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/index.js new file mode 100644 index 000000000..37aa73a5e --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/index.js @@ -0,0 +1,712 @@ + +/**! + * is + * the definitive JavaScript type testing library + * + * @copyright 2013 Enrico Marino + * @license MIT + */ + +var objProto = Object.prototype; +var owns = objProto.hasOwnProperty; +var toString = objProto.toString; +var isActualNaN = function (value) { + return value !== value; +}; +var NON_HOST_TYPES = { + "boolean": 1, + "number": 1, + "string": 1, + "undefined": 1 +}; + +/** + * Expose `is` + */ + +var is = module.exports = {}; + +/** + * Test general. + */ + +/** + * is.type + * Test if `value` is a type of `type`. + * + * @param {Mixed} value value to test + * @param {String} type type + * @return {Boolean} true if `value` is a type of `type`, false otherwise + * @api public + */ + +is.a = +is.type = function (value, type) { + return typeof value === type; +}; + +/** + * is.defined + * Test if `value` is defined. + * + * @param {Mixed} value value to test + * @return {Boolean} true if 'value' is defined, false otherwise + * @api public + */ + +is.defined = function (value) { + return value !== undefined; +}; + +/** + * is.empty + * Test if `value` is empty. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is empty, false otherwise + * @api public + */ + +is.empty = function (value) { + var type = toString.call(value); + var key; + + if ('[object Array]' === type || '[object Arguments]' === type) { + return value.length === 0; + } + + if ('[object Object]' === type) { + for (key in value) if (owns.call(value, key)) return false; + return true; + } + + if ('[object String]' === type) { + return '' === value; + } + + return false; +}; + +/** + * is.equal + * Test if `value` is equal to `other`. + * + * @param {Mixed} value value to test + * @param {Mixed} other value to compare with + * @return {Boolean} true if `value` is equal to `other`, false otherwise + */ + +is.equal = function (value, other) { + var strictlyEqual = value === other; + if (strictlyEqual) { + return true; + } + + var type = toString.call(value); + var key; + + if (type !== toString.call(other)) { + return false; + } + + if ('[object Object]' === type) { + for (key in value) { + if (!is.equal(value[key], other[key]) || !(key in other)) { + return false; + } + } + for (key in other) { + if (!is.equal(value[key], other[key]) || !(key in value)) { + return false; + } + } + return true; + } + + if ('[object Array]' === type) { + key = value.length; + if (key !== other.length) { + return false; + } + while (--key) { + if (!is.equal(value[key], other[key])) { + return false; + } + } + return true; + } + + if ('[object Function]' === type) { + return value.prototype === other.prototype; + } + + if ('[object Date]' === type) { + return value.getTime() === other.getTime(); + } + + return strictlyEqual; +}; + +/** + * is.hosted + * Test if `value` is hosted by `host`. + * + * @param {Mixed} value to test + * @param {Mixed} host host to test with + * @return {Boolean} true if `value` is hosted by `host`, false otherwise + * @api public + */ + +is.hosted = function (value, host) { + var type = typeof host[value]; + return type === 'object' ? !!host[value] : !NON_HOST_TYPES[type]; +}; + +/** + * is.instance + * Test if `value` is an instance of `constructor`. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an instance of `constructor` + * @api public + */ + +is.instance = is['instanceof'] = function (value, constructor) { + return value instanceof constructor; +}; + +/** + * is.null + * Test if `value` is null. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is null, false otherwise + * @api public + */ + +is['null'] = function (value) { + return value === null; +}; + +/** + * is.undef + * Test if `value` is undefined. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is undefined, false otherwise + * @api public + */ + +is.undef = is['undefined'] = function (value) { + return value === undefined; +}; + +/** + * Test arguments. + */ + +/** + * is.args + * Test if `value` is an arguments object. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an arguments object, false otherwise + * @api public + */ + +is.args = is['arguments'] = function (value) { + var isStandardArguments = '[object Arguments]' === toString.call(value); + var isOldArguments = !is.array(value) && is.arraylike(value) && is.object(value) && is.fn(value.callee); + return isStandardArguments || isOldArguments; +}; + +/** + * Test array. + */ + +/** + * is.array + * Test if 'value' is an array. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an array, false otherwise + * @api public + */ + +is.array = function (value) { + return '[object Array]' === toString.call(value); +}; + +/** + * is.arguments.empty + * Test if `value` is an empty arguments object. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an empty arguments object, false otherwise + * @api public + */ +is.args.empty = function (value) { + return is.args(value) && value.length === 0; +}; + +/** + * is.array.empty + * Test if `value` is an empty array. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an empty array, false otherwise + * @api public + */ +is.array.empty = function (value) { + return is.array(value) && value.length === 0; +}; + +/** + * is.arraylike + * Test if `value` is an arraylike object. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an arguments object, false otherwise + * @api public + */ + +is.arraylike = function (value) { + return !!value && !is.boolean(value) + && owns.call(value, 'length') + && isFinite(value.length) + && is.number(value.length) + && value.length >= 0; +}; + +/** + * Test boolean. + */ + +/** + * is.boolean + * Test if `value` is a boolean. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a boolean, false otherwise + * @api public + */ + +is.boolean = function (value) { + return '[object Boolean]' === toString.call(value); +}; + +/** + * is.false + * Test if `value` is false. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is false, false otherwise + * @api public + */ + +is['false'] = function (value) { + return is.boolean(value) && (value === false || value.valueOf() === false); +}; + +/** + * is.true + * Test if `value` is true. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is true, false otherwise + * @api public + */ + +is['true'] = function (value) { + return is.boolean(value) && (value === true || value.valueOf() === true); +}; + +/** + * Test date. + */ + +/** + * is.date + * Test if `value` is a date. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a date, false otherwise + * @api public + */ + +is.date = function (value) { + return '[object Date]' === toString.call(value); +}; + +/** + * Test element. + */ + +/** + * is.element + * Test if `value` is an html element. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an HTML Element, false otherwise + * @api public + */ + +is.element = function (value) { + return value !== undefined + && typeof HTMLElement !== 'undefined' + && value instanceof HTMLElement + && value.nodeType === 1; +}; + +/** + * Test error. + */ + +/** + * is.error + * Test if `value` is an error object. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an error object, false otherwise + * @api public + */ + +is.error = function (value) { + return '[object Error]' === toString.call(value); +}; + +/** + * Test function. + */ + +/** + * is.fn / is.function (deprecated) + * Test if `value` is a function. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a function, false otherwise + * @api public + */ + +is.fn = is['function'] = function (value) { + var isAlert = typeof window !== 'undefined' && value === window.alert; + return isAlert || '[object Function]' === toString.call(value); +}; + +/** + * Test number. + */ + +/** + * is.number + * Test if `value` is a number. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a number, false otherwise + * @api public + */ + +is.number = function (value) { + return '[object Number]' === toString.call(value); +}; + +/** + * is.infinite + * Test if `value` is positive or negative infinity. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is positive or negative Infinity, false otherwise + * @api public + */ +is.infinite = function (value) { + return value === Infinity || value === -Infinity; +}; + +/** + * is.decimal + * Test if `value` is a decimal number. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a decimal number, false otherwise + * @api public + */ + +is.decimal = function (value) { + return is.number(value) && !isActualNaN(value) && !is.infinite(value) && value % 1 !== 0; +}; + +/** + * is.divisibleBy + * Test if `value` is divisible by `n`. + * + * @param {Number} value value to test + * @param {Number} n dividend + * @return {Boolean} true if `value` is divisible by `n`, false otherwise + * @api public + */ + +is.divisibleBy = function (value, n) { + var isDividendInfinite = is.infinite(value); + var isDivisorInfinite = is.infinite(n); + var isNonZeroNumber = is.number(value) && !isActualNaN(value) && is.number(n) && !isActualNaN(n) && n !== 0; + return isDividendInfinite || isDivisorInfinite || (isNonZeroNumber && value % n === 0); +}; + +/** + * is.int + * Test if `value` is an integer. + * + * @param value to test + * @return {Boolean} true if `value` is an integer, false otherwise + * @api public + */ + +is.int = function (value) { + return is.number(value) && !isActualNaN(value) && value % 1 === 0; +}; + +/** + * is.maximum + * Test if `value` is greater than 'others' values. + * + * @param {Number} value value to test + * @param {Array} others values to compare with + * @return {Boolean} true if `value` is greater than `others` values + * @api public + */ + +is.maximum = function (value, others) { + if (isActualNaN(value)) { + throw new TypeError('NaN is not a valid value'); + } else if (!is.arraylike(others)) { + throw new TypeError('second argument must be array-like'); + } + var len = others.length; + + while (--len >= 0) { + if (value < others[len]) { + return false; + } + } + + return true; +}; + +/** + * is.minimum + * Test if `value` is less than `others` values. + * + * @param {Number} value value to test + * @param {Array} others values to compare with + * @return {Boolean} true if `value` is less than `others` values + * @api public + */ + +is.minimum = function (value, others) { + if (isActualNaN(value)) { + throw new TypeError('NaN is not a valid value'); + } else if (!is.arraylike(others)) { + throw new TypeError('second argument must be array-like'); + } + var len = others.length; + + while (--len >= 0) { + if (value > others[len]) { + return false; + } + } + + return true; +}; + +/** + * is.nan + * Test if `value` is not a number. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is not a number, false otherwise + * @api public + */ + +is.nan = function (value) { + return !is.number(value) || value !== value; +}; + +/** + * is.even + * Test if `value` is an even number. + * + * @param {Number} value value to test + * @return {Boolean} true if `value` is an even number, false otherwise + * @api public + */ + +is.even = function (value) { + return is.infinite(value) || (is.number(value) && value === value && value % 2 === 0); +}; + +/** + * is.odd + * Test if `value` is an odd number. + * + * @param {Number} value value to test + * @return {Boolean} true if `value` is an odd number, false otherwise + * @api public + */ + +is.odd = function (value) { + return is.infinite(value) || (is.number(value) && value === value && value % 2 !== 0); +}; + +/** + * is.ge + * Test if `value` is greater than or equal to `other`. + * + * @param {Number} value value to test + * @param {Number} other value to compare with + * @return {Boolean} + * @api public + */ + +is.ge = function (value, other) { + if (isActualNaN(value) || isActualNaN(other)) { + throw new TypeError('NaN is not a valid value'); + } + return !is.infinite(value) && !is.infinite(other) && value >= other; +}; + +/** + * is.gt + * Test if `value` is greater than `other`. + * + * @param {Number} value value to test + * @param {Number} other value to compare with + * @return {Boolean} + * @api public + */ + +is.gt = function (value, other) { + if (isActualNaN(value) || isActualNaN(other)) { + throw new TypeError('NaN is not a valid value'); + } + return !is.infinite(value) && !is.infinite(other) && value > other; +}; + +/** + * is.le + * Test if `value` is less than or equal to `other`. + * + * @param {Number} value value to test + * @param {Number} other value to compare with + * @return {Boolean} if 'value' is less than or equal to 'other' + * @api public + */ + +is.le = function (value, other) { + if (isActualNaN(value) || isActualNaN(other)) { + throw new TypeError('NaN is not a valid value'); + } + return !is.infinite(value) && !is.infinite(other) && value <= other; +}; + +/** + * is.lt + * Test if `value` is less than `other`. + * + * @param {Number} value value to test + * @param {Number} other value to compare with + * @return {Boolean} if `value` is less than `other` + * @api public + */ + +is.lt = function (value, other) { + if (isActualNaN(value) || isActualNaN(other)) { + throw new TypeError('NaN is not a valid value'); + } + return !is.infinite(value) && !is.infinite(other) && value < other; +}; + +/** + * is.within + * Test if `value` is within `start` and `finish`. + * + * @param {Number} value value to test + * @param {Number} start lower bound + * @param {Number} finish upper bound + * @return {Boolean} true if 'value' is is within 'start' and 'finish' + * @api public + */ +is.within = function (value, start, finish) { + if (isActualNaN(value) || isActualNaN(start) || isActualNaN(finish)) { + throw new TypeError('NaN is not a valid value'); + } else if (!is.number(value) || !is.number(start) || !is.number(finish)) { + throw new TypeError('all arguments must be numbers'); + } + var isAnyInfinite = is.infinite(value) || is.infinite(start) || is.infinite(finish); + return isAnyInfinite || (value >= start && value <= finish); +}; + +/** + * Test object. + */ + +/** + * is.object + * Test if `value` is an object. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is an object, false otherwise + * @api public + */ + +is.object = function (value) { + return value && '[object Object]' === toString.call(value); +}; + +/** + * is.hash + * Test if `value` is a hash - a plain object literal. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a hash, false otherwise + * @api public + */ + +is.hash = function (value) { + return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; +}; + +/** + * Test regexp. + */ + +/** + * is.regexp + * Test if `value` is a regular expression. + * + * @param {Mixed} value value to test + * @return {Boolean} true if `value` is a regexp, false otherwise + * @api public + */ + +is.regexp = function (value) { + return '[object RegExp]' === toString.call(value); +}; + +/** + * Test string. + */ + +/** + * is.string + * Test if `value` is a string. + * + * @param {Mixed} value value to test + * @return {Boolean} true if 'value' is a string, false otherwise + * @api public + */ + +is.string = function (value) { + return '[object String]' === toString.call(value); +}; + diff --git a/node_modules/less-middleware/node_modules/node.extend/node_modules/is/package.json b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/package.json new file mode 100644 index 000000000..852a3c206 --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/package.json @@ -0,0 +1,66 @@ +{ + "name": "is", + "author": { + "name": "Enrico Marino", + "url": "http://onirame.com" + }, + "description": "the definitive JavaScript type testing library", + "homepage": "https://github.com/enricomarino/is", + "keywords": [ + "util", + "type", + "test" + ], + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "dependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/enricomarino/is.git" + }, + "main": "index.js", + "version": "0.3.0", + "scripts": { + "test": "node test/index.js", + "coverage": "covert test/index.js", + "coverage-quiet": "covert test/index.js --quiet" + }, + "devDependencies": { + "tape": "~2.5.0", + "foreach": "~2.0.4", + "covert": "~0.3.1" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0", + "chrome/22.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/5.0.5..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "engines": { + "node": "*" + }, + "readme": "# is\n\nThe definitive JavaScript type testing library\n\nTo be or not to be? This is the library!\n\n[![browser support][1]][2]\n\n## Installation\n\nAs a node.js module\n\n $ npm install is\n\nAs a component\n\n $ component install enricomarino/is\n\n## API\n\n### general\n\n - is.a (value, type) or is.type (value, type)\n - is.defined (value)\n - is.empty (value)\n - is.equal (value, other)\n - is.hosted (value, host)\n - is.instance (value, constructor)\n - is.instanceof (value, constructor) - deprecated, because in ES3 browsers, \"instanceof\" is a reserved word\n - is.null (value) - deprecated, because in ES3 browsers, \"null\" is a reserved word\n - is.undef (value)\n - is.undefined (value) - deprecated, because in ES3 browsers, \"undefined\" is a reserved word\n\n### arguments\n\n - is.args (value)\n - is.arguments (value) - deprecated, because \"arguments\" is a reserved word\n - is.args.empty (value)\n\n### array\n\n - is.array (value)\n - is.array.empty (value)\n - is.arraylike (value)\n\n### boolean\n\n - is.boolean (value)\n - is.false (value) - deprecated, because in ES3 browsers, \"false\" is a reserved word\n - is.true (value) - deprecated, because in ES3 browsers, \"true\" is a reserved word\n\n### date\n\n - is.date (value)\n\n### element\n\n - is.element (value)\n\n### error\n\n - is.error (value)\n\n### function\n\n - is.fn(value)\n - is.function(value) - deprecated, because in ES3 browsers, \"function\" is a reserved word\n\n### number\n\n - is.number (value)\n - is.infinite (value)\n - is.decimal (value)\n - is.divisibleBy (value, n)\n - is.int (value)\n - is.maximum (value, others)\n - is.minimum (value, others)\n - is.nan (value)\n - is.even (value)\n - is.odd (value)\n - is.ge (value, other)\n - is.gt (value, other)\n - is.le (value, other)\n - is.lt (value, other)\n - is.within (value, start, finish)\n\n### object\n\n - is.object (value)\n\n### regexp\n\n - is.regexp (value)\n\n### string\n\n - is.string (value)\n\n\n## Contributors\n\n- [Jordan Harband](https://github.com/ljharb)\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2013 Enrico Marino\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[1]: https://ci.testling.com/enricomarino/is.png\n[2]: https://ci.testling.com/enricomarino/is\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/enricomarino/is/issues" + }, + "_id": "is@0.3.0", + "_shasum": "a8f71dfc8a6e28371627f26c929098c6f4d5d5d7", + "_from": "is@~0.3.0", + "_resolved": "https://registry.npmjs.org/is/-/is-0.3.0.tgz" +} diff --git a/node_modules/less-middleware/node_modules/node.extend/node_modules/is/test/index.js b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/test/index.js new file mode 100644 index 000000000..534e4c80c --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/node_modules/is/test/index.js @@ -0,0 +1,560 @@ +var test = require('tape'); +var is = require('../index.js'); + +var forEach = require('foreach'); + +test('is.type', function (t) { + var booleans = [true, false]; + forEach(booleans, function (boolean) { + t.ok(is.type(boolean, 'boolean'), '"' + boolean + '" is a boolean'); + }); + + var numbers = [1, 0 / 1, 0 / -1, NaN, Infinity, -Infinity]; + forEach(numbers, function (number) { + t.ok(is.type(number, 'number'), '"' + number + '" is a number'); + }); + + var objects = [{}, null, new Date()]; + forEach(objects, function (object) { + t.ok(is.type(object, 'object'), '"' + object + '" is an object'); + }); + + var strings = ['', 'abc']; + forEach(strings, function (string) { + t.ok(is.type(string, 'string'), '"' + string + '" is a string'); + }); + + t.ok(is.type(undefined, 'undefined'), 'undefined is undefined'); + + t.end(); +}); + +test('is.undef', function (t) { + t.ok(is.undef(), 'absent undefined is undefined'); + t.ok(is.undef(undefined), 'literal undefined is undefined'); + t.notOk(is.undef(null), 'null is not undefined'); + t.notOk(is.undef({}), 'object is not undefined'); + t.end(); +}); + +test('is.defined', function (t) { + t.notOk(is.defined(), 'undefined is not defined'); + t.ok(is.defined(null), 'null is defined'); + t.ok(is.defined({}), 'object is undefined'); + t.end(); +}); + +test('is.empty', function (t) { + t.ok(is.empty(''), 'empty string is empty'); + t.ok(is.empty([]), 'empty array is empty'); + t.ok(is.empty({}), 'empty object is empty'); + (function () { t.ok(is.empty(arguments), 'empty arguments is empty'); }()); + t.end(); +}); + +test('is.equal', function (t) { + t.test('primitives', function (pt) { + var primitives = [true, false, undefined, null, '', 'foo', 0, Infinity, -Infinity]; + pt.plan(primitives.length); + for (var i = 0; i < primitives.length; ++i) { + pt.ok(is.equal(primitives[i], primitives[i]), 'primitives are equal to themselves: ' + primitives[i]); + } + pt.end(); + }); + + t.test('arrays', function (at) { + at.ok(is.equal([1, 2, 3], [1, 2, 3]), 'arrays are shallowly equal'); + at.ok(is.equal([1, 2, [3, 4]], [1, 2, [3, 4]]), 'arrays are deep equal'); + at.notOk(is.equal([1, 2], [2, 3]), 'inequal arrays are not equal'); + + var arr = [1, 2]; + at.ok(is.equal(arr, arr), 'array is equal to itself'); + + at.end(); + }); + + t.test('dates', function (dt) { + var now = new Date(); + dt.ok(is.equal(now, new Date(now.getTime())), 'two equal date objects are equal'); + dt.notOk(is.equal(now, new Date()), 'two inequal date objects are not equal'); + dt.end(); + }); + + t.test('plain objects', function (ot) { + ot.ok(is.equal({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 }), 'objects are shallowly equal'); + ot.ok(is.equal({ a: { b: 1 } }, { a: { b: 1 } }), 'objects are deep equal'); + ot.notOk(is.equal({ a: 1 }, { a: 2 }), 'inequal objects are not equal'); + ot.end(); + }); + + t.test('object instances', function (ot) { + var F = function F() { + this.foo = 'bar'; + }; + F.prototype = {}; + var G = function G() { + this.foo = 'bar'; + }; + var f = new F(); + var g = new G(); + + ot.ok(is.equal(f, f), 'the same object instances are equal'); + ot.ok(is.equal(f, new F()), 'two object instances are equal when the prototype and props are the same'); + ot.ok(is.equal(f, new G()), 'two object instances are equal when the prototype is not the same, but props are'); + + g.bar = 'baz'; + ot.notOk(is.equal(f, g), 'object instances are not equal when the prototype and props are not the same'); + ot.notOk(is.equal(g, f), 'object instances are not equal when the prototype and props are not the same'); + ot.end(); + }); + + t.test('functions', function (ft) { + var F = function () {}; + F.prototype = {}; + var G = function () {}; + G.prototype = new Date(); + + ft.notEqual(F.prototype, G.prototype, 'F and G have different prototypes'); + ft.notOk(is.equal(F, G), 'two functions are not equal when the prototype is not the same'); + + var H = function () {}; + H.prototype = F.prototype; + + ft.equal(F.prototype, H.prototype, 'F and H have the same prototype'); + ft.ok(is.equal(F, H), 'two functions are equal when the prototype is the same'); + ft.end(); + }); + + t.end(); +}); + +test('is.hosted', function (t) { + t.ok(is.hosted('a', { a: {} }), 'object is hosted'); + t.ok(is.hosted('a', { a: [] }), 'array is hosted'); + t.ok(is.hosted('a', { a: function () {} }), 'function is hosted'); + t.notOk(is.hosted('a', { a: true }), 'boolean value is not hosted'); + t.notOk(is.hosted('a', { a: false }), 'boolean value is not hosted'); + t.notOk(is.hosted('a', { a: 3 }), 'number value is not hosted'); + t.notOk(is.hosted('a', { a: undefined }), 'undefined value is not hosted'); + t.notOk(is.hosted('a', { a: 'abc' }), 'string value is not hosted'); + t.notOk(is.hosted('a', { a: null }), 'null value is not hosted'); + t.end(); +}); + +test('is.instance', function (t) { + t.ok(is.instance(new Date(), Date), 'new Date is instanceof Date'); + var F = function () {}; + t.ok(is.instance(new F(), F), 'new constructor is instanceof constructor'); + t.end(); +}); + +test('is.null', function (t) { + var isNull = is['null']; + t.ok(isNull(null), 'null is null'); + t.notOk(isNull(undefined), 'undefined is not null'); + t.notOk(isNull({}), 'object is not null'); + t.end(); +}); + +test('is.args', function (t) { + t.notOk(is.args([]), 'array is not arguments'); + (function () { t.ok(is.args(arguments), 'arguments is arguments'); }()); + (function () { t.notOk(is.args(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); }()); + var fakeOldArguments = { + length: 3, + callee: function () {} + }; + t.ok(is.args(fakeOldArguments), 'old-style arguments object is arguments'); + t.end(); +}); + +test('is.args.empty', function (t) { + t.notOk(is.args.empty([]), 'empty array is not empty arguments'); + (function () { t.ok(is.args.empty(arguments), 'empty arguments is empty arguments'); }()); + (function () { t.notOk(is.args.empty(Array.prototype.slice.call(arguments)), 'empty sliced arguments is not empty arguments'); }()); + t.end(); +}); + + +test('is.array', function (t) { + t.ok(is.array([]), 'array is array'); + (function () { t.ok(is.array(Array.prototype.slice.call(arguments)), 'sliced arguments is array'); }()); + t.end(); +}); + +test('is.array.empty', function (t) { + t.ok(is.array.empty([]), 'empty array is empty array'); + (function () { t.notOk(is.array.empty(arguments), 'empty arguments is not empty array'); }()); + (function () { t.ok(is.array.empty(Array.prototype.slice.call(arguments)), 'empty sliced arguments is empty array'); }()); + t.end(); +}); + +test('is.isarraylike', function (t) { + t.notOk(is.arraylike(), 'undefined is not array-like'); + t.notOk(is.arraylike(null), 'null is not array-like'); + t.notOk(is.arraylike(false), 'false is not array-like'); + t.notOk(is.arraylike(true), 'true is not array-like'); + t.ok(is.arraylike({ length: 0 }), 'object with zero length is array-like'); + t.ok(is.arraylike({ length: 1 }), 'object with positive length is array-like'); + t.notOk(is.arraylike({ length: -1 }), 'object with negative length is not array-like'); + t.notOk(is.arraylike({ length: NaN }), 'object with NaN length is not array-like'); + t.notOk(is.arraylike({ length: 'foo' }), 'object with string length is not array-like'); + t.notOk(is.arraylike({ length: '' }), 'object with empty string length is not array-like'); + t.ok(is.arraylike([]), 'array is array-like'); + (function () { t.ok(is.arraylike(arguments), 'empty arguments is array-like'); }()); + (function () { t.ok(is.arraylike(arguments), 'nonempty arguments is array-like'); }(1, 2, 3)); + t.end(); +}); + +test('is.boolean', function (t) { + t.ok(is.boolean(true), 'literal true is a boolean'); + t.ok(is.boolean(false), 'literal false is a boolean'); + t.ok(is.boolean(new Boolean(true)), 'object true is a boolean'); + t.ok(is.boolean(new Boolean(false)), 'object false is a boolean'); + t.notOk(is.boolean(), 'undefined is not a boolean'); + t.notOk(is.boolean(null), 'null is not a boolean'); + t.end(); +}); + +test('is.false', function (t) { + var isFalse = is['false']; + t.ok(isFalse(false), 'false is false'); + t.ok(isFalse(new Boolean(false)), 'object false is false'); + t.notOk(isFalse(true), 'true is not false'); + t.notOk(isFalse(), 'undefined is not false'); + t.notOk(isFalse(null), 'null is not false'); + t.notOk(isFalse(''), 'empty string is not false'); + t.end(); +}); + +test('is.true', function (t) { + var isTrue = is['true']; + t.ok(isTrue(true), 'true is true'); + t.ok(isTrue(new Boolean(true)), 'object true is true'); + t.notOk(isTrue(false), 'false is not true'); + t.notOk(isTrue(), 'undefined is not true'); + t.notOk(isTrue(null), 'null is not true'); + t.notOk(isTrue(''), 'empty string is not true'); + t.end(); +}); + +test('is.date', function (t) { + t.ok(is.date(new Date()), 'new Date is date'); + t.notOk(is.date(), 'undefined is not date'); + t.notOk(is.date(null), 'null is not date'); + t.notOk(is.date(''), 'empty string is not date'); + var nowTS = (new Date()).getTime(); + t.notOk(is.date(nowTS), 'timestamp is not date'); + var F = function () {}; + F.prototype = new Date(); + t.notOk(is.date(new F()), 'Date subtype is not date'); + t.end(); +}); + +test('is.element', function (t) { + t.notOk(is.element(), 'undefined is not element'); + if (typeof HTMLElement !== 'undefined') { + var element = document.createElement('div'); + t.ok(is.element(element), 'HTMLElement is element'); + t.notOk(is.element({ nodeType: 1 }), 'object with nodeType is not element'); + } else { + t.ok(true, 'Skipping is.element test in a non-browser environment'); + } + t.end(); +}); + +test('is.error', function (t) { + var err = new Error('foo'); + t.ok(is.error(err), 'Error is error'); + t.notOk(is.error({}), 'object is not error'); + t.notOk(is.error({ toString: function () { return '[object Error]'; } }), 'object with error\'s toString is not error'); + t.end(); +}); + +test('is.fn', function (t) { + t.equal(is['function'], is.fn, 'alias works'); + t.ok(is.fn(function () {}), 'function is function'); + t.ok(is.fn(console.log), 'console.log is function'); + if (typeof window !== 'undefined') { + // in IE7/8, typeof alert === 'object' + t.ok(is.fn(window.alert), 'window.alert is function'); + } + t.notOk(is.fn({}), 'object is not function'); + t.notOk(is.fn(null), 'null is not function'); + t.end(); +}); + +test('is.number', function (t) { + t.ok(is.number(0), 'positive zero is number'); + t.ok(is.number(0 / -1), 'negative zero is number'); + t.ok(is.number(3), 'three is number'); + t.ok(is.number(NaN), 'NaN is number'); + t.ok(is.number(Infinity), 'infinity is number'); + t.ok(is.number(-Infinity), 'negative infinity is number'); + t.ok(is.number(new Number(42)), 'object number is number'); + t.notOk(is.number(), 'undefined is not number'); + t.notOk(is.number(null), 'null is not number'); + t.notOk(is.number(true), 'true is not number'); + t.end(); +}); + +test('is.infinite', function (t) { + t.ok(is.infinite(Infinity), 'positive infinity is infinite'); + t.ok(is.infinite(-Infinity), 'negative infinity is infinite'); + t.notOk(is.infinite(NaN), 'NaN is not infinite'); + t.notOk(is.infinite(0), 'a number is not infinite'); + t.end(); +}); + +test('is.decimal', function (t) { + t.ok(is.decimal(1.1), 'decimal is decimal'); + t.notOk(is.decimal(0), 'zero is not decimal'); + t.notOk(is.decimal(1), 'integer is not decimal'); + t.notOk(is.decimal(NaN), 'NaN is not decimal'); + t.notOk(is.decimal(Infinity), 'Infinity is not decimal'); + t.end(); +}); + +test('is.divisibleBy', function (t) { + t.ok(is.divisibleBy(4, 2), '4 is divisible by 2'); + t.ok(is.divisibleBy(4, 2), '4 is divisible by 2'); + t.ok(is.divisibleBy(0, 1), '0 is divisible by 1'); + t.ok(is.divisibleBy(Infinity, 1), 'infinity is divisible by anything'); + t.ok(is.divisibleBy(1, Infinity), 'anything is divisible by infinity'); + t.ok(is.divisibleBy(Infinity, Infinity), 'infinity is divisible by infinity'); + t.notOk(is.divisibleBy(1, 0), '1 is not divisible by 0'); + t.notOk(is.divisibleBy(NaN, 1), 'NaN is not divisible by 1'); + t.notOk(is.divisibleBy(1, NaN), '1 is not divisible by NaN'); + t.notOk(is.divisibleBy(NaN, NaN), 'NaN is not divisible by NaN'); + t.notOk(is.divisibleBy(1, 3), '1 is not divisible by 3'); + t.end(); +}); + +test('is.int', function (t) { + t.ok(is.int(0), '0 is integer'); + t.ok(is.int(3), '3 is integer'); + t.notOk(is.int(1.1), '1.1 is not integer'); + t.notOk(is.int(NaN), 'NaN is not integer'); + t.notOk(is.int(Infinity), 'infinity is not integer'); + t.notOk(is.int(null), 'null is not integer'); + t.notOk(is.int(), 'undefined is not integer'); + t.end(); +}); + +test('is.maximum', function (t) { + t.ok(is.maximum(3, [3, 2, 1]), '3 is maximum of [3,2,1]'); + t.ok(is.maximum(3, [1, 2, 3]), '3 is maximum of [1,2,3]'); + t.ok(is.maximum(4, [1, 2, 3]), '4 is maximum of [1,2,3]'); + t.ok(is.maximum('c', ['a', 'b', 'c']), 'c is maximum of [a,b,c]'); + t.notOk(is.maximum(2, [1, 2, 3]), '2 is not maximum of [1,2,3]'); + + var nanError = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.maximum(NaN); }, nanError, 'throws when first value is NaN'); + + var error = new TypeError('second argument must be array-like'); + t.throws(function () { return is.maximum(2, null); }, error, 'throws when second value is not array-like'); + t.throws(function () { return is.maximum(2, {}); }, error, 'throws when second value is not array-like'); + t.end(); +}); + +test('is.minimum', function (t) { + t.ok(is.minimum(1, [1, 2, 3]), '1 is minimum of [1,2,3]'); + t.ok(is.minimum(0, [1, 2, 3]), '0 is minimum of [1,2,3]'); + t.ok(is.minimum('a', ['a', 'b', 'c']), 'a is minimum of [a,b,c]'); + t.notOk(is.minimum(2, [1, 2, 3]), '2 is not minimum of [1,2,3]'); + + var nanError = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.minimum(NaN); }, nanError, 'throws when first value is NaN'); + + var error = new TypeError('second argument must be array-like'); + t.throws(function () { return is.minimum(2, null); }, error, 'throws when second value is not array-like'); + t.throws(function () { return is.minimum(2, {}); }, error, 'throws when second value is not array-like'); + t.end(); +}); + +test('is.nan', function (t) { + t.ok(is.nan(NaN), 'NaN is not a number'); + t.ok(is.nan('abc'), 'string is not a number'); + t.ok(is.nan(true), 'boolean is not a number'); + t.ok(is.nan({}), 'object is not a number'); + t.ok(is.nan([]), 'array is not a number'); + t.ok(is.nan(function () {}), 'function is not a number'); + t.notOk(is.nan(0), 'zero is a number'); + t.notOk(is.nan(3), 'three is a number'); + t.notOk(is.nan(1.1), '1.1 is a number'); + t.notOk(is.nan(Infinity), 'infinity is a number'); + t.end(); +}); + +test('is.even', function (t) { + t.ok(is.even(0), 'zero is even'); + t.ok(is.even(2), 'two is even'); + t.ok(is.even(Infinity), 'infinity is even'); + t.notOk(is.even(1), '1 is not even'); + t.notOk(is.even(), 'undefined is not even'); + t.notOk(is.even(null), 'null is not even'); + t.notOk(is.even(NaN), 'NaN is not even'); + t.end(); +}); + +test('is.odd', function (t) { + t.ok(is.odd(1), 'zero is odd'); + t.ok(is.odd(3), 'two is odd'); + t.ok(is.odd(Infinity), 'infinity is odd'); + t.notOk(is.odd(0), '0 is not odd'); + t.notOk(is.odd(2), '2 is not odd'); + t.notOk(is.odd(), 'undefined is not odd'); + t.notOk(is.odd(null), 'null is not odd'); + t.notOk(is.odd(NaN), 'NaN is not odd'); + t.end(); +}); + +test('is.ge', function (t) { + t.ok(is.ge(3, 2), '3 is greater than 2'); + t.notOk(is.ge(2, 3), '2 is not greater than 3'); + t.ok(is.ge(3, 3), '3 is greater than or equal to 3'); + t.ok(is.ge('abc', 'a'), 'abc is greater than a'); + t.ok(is.ge('abc', 'abc'), 'abc is greater than or equal to abc'); + t.notOk(is.ge('a', 'abc'), 'a is not greater than abc'); + t.notOk(is.ge(Infinity, 0), 'infinity is not greater than anything'); + t.notOk(is.ge(0, Infinity), 'anything is not greater than infinity'); + var error = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.ge(NaN, 2); }, error, 'throws when first value is NaN'); + t.throws(function () { return is.ge(2, NaN); }, error, 'throws when second value is NaN'); + t.end(); +}); + +test('is.gt', function (t) { + t.ok(is.gt(3, 2), '3 is greater than 2'); + t.notOk(is.gt(2, 3), '2 is not greater than 3'); + t.notOk(is.gt(3, 3), '3 is not greater than 3'); + t.ok(is.gt('abc', 'a'), 'abc is greater than a'); + t.notOk(is.gt('abc', 'abc'), 'abc is not greater than abc'); + t.notOk(is.gt('a', 'abc'), 'a is not greater than abc'); + t.notOk(is.gt(Infinity, 0), 'infinity is not greater than anything'); + t.notOk(is.gt(0, Infinity), 'anything is not greater than infinity'); + var error = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.gt(NaN, 2); }, error, 'throws when first value is NaN'); + t.throws(function () { return is.gt(2, NaN); }, error, 'throws when second value is NaN'); + t.end(); +}); + +test('is.le', function (t) { + t.ok(is.le(2, 3), '2 is lesser than or equal to 3'); + t.notOk(is.le(3, 2), '3 is not lesser than or equal to 2'); + t.ok(is.le(3, 3), '3 is lesser than or equal to 3'); + t.ok(is.le('a', 'abc'), 'a is lesser than or equal to abc'); + t.ok(is.le('abc', 'abc'), 'abc is lesser than or equal to abc'); + t.notOk(is.le('abc', 'a'), 'abc is not lesser than or equal to a'); + t.notOk(is.le(Infinity, 0), 'infinity is not lesser than or equal to anything'); + t.notOk(is.le(0, Infinity), 'anything is not lesser than or equal to infinity'); + var error = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.le(NaN, 2); }, error, 'throws when first value is NaN'); + t.throws(function () { return is.le(2, NaN); }, error, 'throws when second value is NaN'); + t.end(); +}); + +test('is.lt', function (t) { + t.ok(is.lt(2, 3), '2 is lesser than 3'); + t.notOk(is.lt(3, 2), '3 is not lesser than 2'); + t.notOk(is.lt(3, 3), '3 is not lesser than 3'); + t.ok(is.lt('a', 'abc'), 'a is lesser than abc'); + t.notOk(is.lt('abc', 'abc'), 'abc is not lesser than abc'); + t.notOk(is.lt('abc', 'a'), 'abc is not lesser than a'); + t.notOk(is.lt(Infinity, 0), 'infinity is not lesser than anything'); + t.notOk(is.lt(0, Infinity), 'anything is not lesser than infinity'); + var error = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.lt(NaN, 2); }, error, 'throws when first value is NaN'); + t.throws(function () { return is.lt(2, NaN); }, error, 'throws when second value is NaN'); + t.end(); +}); + +test('is.within', function (t) { + var nanError = new TypeError('NaN is not a valid value'); + t.throws(function () { return is.within(NaN, 0, 0); }, nanError, 'throws when first value is NaN'); + t.throws(function () { return is.within(0, NaN, 0); }, nanError, 'throws when second value is NaN'); + t.throws(function () { return is.within(0, 0, NaN); }, nanError, 'throws when third value is NaN'); + + var error = new TypeError('all arguments must be numbers'); + t.throws(function () { return is.within('', 0, 0); }, error, 'throws when first value is string'); + t.throws(function () { return is.within(0, '', 0); }, error, 'throws when second value is string'); + t.throws(function () { return is.within(0, 0, ''); }, error, 'throws when third value is string'); + t.throws(function () { return is.within({}, 0, 0); }, error, 'throws when first value is object'); + t.throws(function () { return is.within(0, {}, 0); }, error, 'throws when second value is object'); + t.throws(function () { return is.within(0, 0, {}); }, error, 'throws when third value is object'); + t.throws(function () { return is.within(null, 0, 0); }, error, 'throws when first value is null'); + t.throws(function () { return is.within(0, null, 0); }, error, 'throws when second value is null'); + t.throws(function () { return is.within(0, 0, null); }, error, 'throws when third value is null'); + t.throws(function () { return is.within(undefined, 0, 0); }, error, 'throws when first value is undefined'); + t.throws(function () { return is.within(0, undefined, 0); }, error, 'throws when second value is undefined'); + t.throws(function () { return is.within(0, 0, undefined); }, error, 'throws when third value is undefined'); + + t.ok(is.within(2, 1, 3), '2 is between 1 and 3'); + t.ok(is.within(0, -1, 1), '0 is between -1 and 1'); + t.ok(is.within(2, 0, Infinity), 'infinity always returns true'); + t.ok(is.within(2, Infinity, 2), 'infinity always returns true'); + t.ok(is.within(Infinity, 0, 1), 'infinity always returns true'); + t.notOk(is.within(2, -1, -1), '2 is not between -1 and 1'); + t.end(); +}); + +test('is.object', function (t) { + t.ok(is.object({}), 'object literal is object'); + t.notOk(is.object(), 'undefined is not an object'); + t.notOk(is.object(null), 'null is not an object'); + t.notOk(is.object(true), 'true is not an object'); + t.notOk(is.object(''), 'string is not an object'); + t.notOk(is.object(NaN), 'NaN is not an object'); + t.notOk(is.object(Object), 'object constructor is not an object'); + t.notOk(is.object(function () {}), 'function is not an object'); + t.end(); +}); + +test('is.hash', function (t) { + t.ok(is.hash({}), 'empty object literal is hash'); + t.ok(is.hash({ 1: 2, a: "b" }), 'object literal is hash'); + t.notOk(is.hash(), 'undefined is not a hash'); + t.notOk(is.hash(null), 'null is not a hash'); + t.notOk(is.hash(new Date()), 'date is not a hash'); + t.notOk(is.hash(new String()), 'string object is not a hash'); + t.notOk(is.hash(''), 'string literal is not a hash'); + t.notOk(is.hash(new Number()), 'number object is not a hash'); + t.notOk(is.hash(1), 'number literal is not a hash'); + t.notOk(is.hash(true), 'true is not a hash'); + t.notOk(is.hash(false), 'false is not a hash'); + t.notOk(is.hash(new Boolean()), 'boolean obj is not hash'); + t.notOk(is.hash(false), 'literal false is not hash'); + t.notOk(is.hash(true), 'literal true is not hash'); + if (typeof module !== 'undefined') { + t.ok(is.hash(module.exports), 'module.exports is a hash'); + } + if (typeof window !== 'undefined') { + t.notOk(is.hash(window), 'window is not a hash'); + t.notOk(is.hash(document.createElement('div')), 'element is not a hash'); + } else if (typeof process !== 'undefined') { + t.notOk(is.hash(global), 'global is not a hash'); + t.notOk(is.hash(process), 'process is not a hash'); + } + t.end(); +}); + +test('is.regexp', function (t) { + t.ok(is.regexp(/a/g), 'regex literal is regex'); + t.ok(is.regexp(new RegExp('a', 'g')), 'regex object is regex'); + t.notOk(is.regexp(), 'undefined is not regex'); + t.notOk(is.regexp(function () {}), 'function is not regex'); + t.notOk(is.regexp('/a/g'), 'string regex is not regex'); + t.end(); +}); + +test('is.string', function (t) { + t.ok(is.string('foo'), 'string literal is string'); + t.ok(is.string(new String('foo')), 'string literal is string'); + t.notOk(is.string(), 'undefined is not string'); + t.notOk(is.string(String), 'string constructor is not string'); + var F = function () {}; + F.prototype = new String(); + t.notOk(is.string(F), 'string subtype is not string'); + t.end(); +}); + diff --git a/node_modules/less-middleware/node_modules/node.extend/package.json b/node_modules/less-middleware/node_modules/node.extend/package.json new file mode 100644 index 000000000..07e04985b --- /dev/null +++ b/node_modules/less-middleware/node_modules/node.extend/package.json @@ -0,0 +1,76 @@ +{ + "name": "node.extend", + "version": "1.0.10", + "description": "A port of jQuery.extend that actually works on node.js", + "keywords": [ + "extend", + "jQuery", + "jQuery extend", + "clone", + "copy", + "inherit" + ], + "author": { + "name": "dreamerslab", + "email": "ben@dreamerslab.com" + }, + "dependencies": { + "is": "~0.3.0" + }, + "devDependencies": { + "tape": "~2.10.2" + }, + "repository": { + "type": "git", + "url": "https://github.com/dreamerslab/node.extend.git" + }, + "contributors": [ + { + "name": "Jordan Harband" + } + ], + "main": "index", + "scripts": { + "test": "node test/index.js" + }, + "engines": [ + "node >= 0.4" + ], + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "licenses": [ + { + "type": "MIT", + "url": "http://en.wikipedia.org/wiki/MIT_License" + }, + { + "type": "GPL", + "url": "http://en.wikipedia.org/wiki/GNU_General_Public_License" + } + ], + "readme": "# node.extend\n\nA port of jQuery.extend that **actually works** on node.js\n\n[![Build Status][3]][4] [![dependency status][5]][6]\n\n[![browser support][1]][2]\n\n\n## Description\n\nNone of the existing ones on npm really work therefore I ported it myself.\n\n\n\n## Usage\n\nTo install this module in your current working directory (which should already contain a package.json), run\n\n```\nnpm install node.extend\n```\n\nYou can additionally just list the module in your [package.json](https://npmjs.org/doc/json.html) and run npm install.\n\nThen, require this package where you need it:\n\n```\nvar extend = require('node.extend');\n```\n\nThe syntax for merging two objects is as follows:\n\n```\nvar destObject = extend({}, sourceObject);\n// Where sourceObject is the object whose properties will be copied into another.\n// NOTE: In this situation, this is not a deep merge. See below on how to handle a deep merge.\n```\n\nFor information about how the clone works internally, view source in lib/extend.js or checkout the doc from [jQuery][]\n\n### A Note About Deep Merge (avoiding pass-by-reference cloning)\n\nIn order to force a deep merge, when extending an object, you must pass boolean true as the first argument to extend:\n\n```\nvar destObject = extend(true, {}, sourceObject);\n// Where sourceObject is the object whose properties will be copied into another.\n```\n\nSee [this article](http://www.jon-carlos.com/2013/is-javascript-call-by-value-or-call-by-reference/) for more information about the need for deep merges in JavaScript.\n\n## Credit\n\n- Jordan Harband [@ljharb][]\n\n\n\n## License\n\nCopyright 2011, John Resig\nDual licensed under the MIT or GPL Version 2 licenses.\nhttp://jquery.org/license\n\n[1]: https://ci.testling.com/dreamerslab/node.extend.png\n[2]: https://ci.testling.com/dreamerslab/node.extend\n[3]: https://travis-ci.org/dreamerslab/node.extend.png\n[4]: https://travis-ci.org/dreamerslab/node.extend\n[5]: https://david-dm.org/dreamerslab/node.extend.png\n[6]: https://david-dm.org/dreamerslab/node.extend\n[jQuery]: http://api.jquery.com/jQuery.extend/\n[@ljharb]: https://twitter.com/ljharb\n\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/dreamerslab/node.extend/issues" + }, + "homepage": "https://github.com/dreamerslab/node.extend", + "_id": "node.extend@1.0.10", + "_shasum": "3269bddf81c54535f408abc784c32b0d2bd55f6f", + "_from": "node.extend@~1.0.8", + "_resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.0.10.tgz" +} diff --git a/node_modules/less-middleware/package.json b/node_modules/less-middleware/package.json new file mode 100644 index 000000000..995adfebc --- /dev/null +++ b/node_modules/less-middleware/package.json @@ -0,0 +1,42 @@ +{ + "author": { + "name": "Randy Merrill", + "email": "Zoramite+github@gmail.com", + "url": "http://forthedeveloper.com" + }, + "name": "less-middleware", + "description": "LESS.js middleware for connect.", + "version": "1.0.4", + "repository": { + "type": "git", + "url": "git://github.com/emberfeather/less.js-middleware.git" + }, + "main": "lib/middleware.js", + "dependencies": { + "less": "1.7.x", + "mkdirp": "~0.3.5", + "node.extend": "~1.0.8" + }, + "devDependencies": { + "mocha": "~1.17.1", + "supertest": "~0.9.0", + "express": "~3.4.7", + "fs-extra": "~0.11.0" + }, + "engines": { + "node": ">= 0.7.1" + }, + "scripts": { + "test": "mocha" + }, + "readme": "**The less-middleware has recently been updated to version `1.0.4`.**\n\n**If you are seeing an error similar to `TypeError: Arguments to path.join must be strings` please read the [migration guide](https://github.com/emberfeather/less.js-middleware/wiki/Migration-0.1.x-1.0.x) to update your code.**\n\nThis middleware was created to allow processing of [Less](http://lesscss.org) files for [Connect JS](http://www.senchalabs.org/connect/) framework and by extension the [Express JS](http://expressjs.com/) framework.\n\n[![Build Status](https://drone.io/github.com/emberfeather/less.js-middleware/status.png)](https://drone.io/github.com/emberfeather/less.js-middleware/latest)\n\n## Installation\n\n```sh\nnpm install less-middleware --save\n```\n\n## Usage\n\n```js\nlessMiddleware(source, [{options}])\n```\n\n### Express\n\n```js\nvar lessMiddleware = require('less-middleware');\n\nvar app = express();\napp.use(lessMiddleware(__dirname + '/public'));\napp.use(express.static(__dirname + '/public'));\n```\n\n### `options`\n\nThe following options can be used to control the behavior of the middleware:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    OptionDescriptionDefault
    compilerOptions for the less compiler. See the \"compiler Options\" section below.
    debugShow more verbose logging?false
    destDestination directory to output the compiled .css files.Same directory as less source files.
    forceAlways re-compile less files on each request.false
    onceOnly recompile once after each server restart. Useful for reducing disk i/o on production.false
    parserOptions for the less parser. See the \"parser Options\" section below.
    pathRootCommon root of the source and destination. It is prepended to both the source and destination before being used.null
    postprocessObject containing functions relavent to preprocessing data.
    postprocess.cssFunction that modifies the compiled css output before being stored.function(css, req){...}
    preprocessObject containing functions relavent to preprocessing data.
    preprocess.lessFunction that modifies the raw less output before being parsed and compiled.function(src, req){...}
    preprocess.pathFunction that modifies the less pathname before being loaded from the filesystem.function(pathname, req){...}
    storeCssFunction that is in charge of storing the css in the filesystem.function(pathname, css, next){...}
    cacheFilePath to a JSON file that will be used to cache less data across server restarts. This can greatly speed up initial load time after a server restart - if the less files haven't changed and the css files still exist, specifying this option will mean that the less files don't need to be recompiled after a server restart.
    \n\n## `compiler` Options\n\nThe `options.compiler` is passed directly into the less parser with minimal defaults or changes by the middleware.\n\nThe following are the defaults used by the middleware:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    OptionDefault
    compressauto
    sourceMapfalse
    yuicompressfalse
    \n\n## `parser` Options\n\nThe `options.parser` is passed directly into the less parser with minimal defaults or changes by the middleware.\n\nThe following are the defaults used by the middleware:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    OptionDefault
    dumpLineNumbers0
    paths[source]
    optimization0
    relativeUrlsfalse
    \n\n## Examples\n\nCommon examples of using the Less middleware are available in the [wiki](https://github.com/emberfeather/less.js-middleware/wiki/Examples).\n\n## Troubleshooting\n\n### My less never recompiles, even when I use `{force: true}`!\n\nMake sure you're declaring less-middleware before your static middleware, if you're using the same directory, e.g. (with express):\n\n\n```js\nvar lessMiddleware = require('less-middleware');\n\nvar app = express();\napp.use(lessMiddleware(__dirname + '/public'));\napp.use(express.static(__dirname + '/public'));\n```\n\nnot\n\n```js\nvar lessMiddleware = require('less-middleware');\n\nvar app = express();\napp.use(express.static(__dirname + '/public'));\napp.use(lessMiddleware(__dirname + '/public'));\n```\n\n### IIS\n\nIf you are hosting your app on IIS you will have to modify your `web.config` file in order to allow NodeJS to serve your CSS static files. IIS will cache your CSS files, bypassing NodeJS static file serving, which in turn does not allow the middleware to recompile your LESS files.\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/emberfeather/less.js-middleware/issues" + }, + "homepage": "https://github.com/emberfeather/less.js-middleware", + "_id": "less-middleware@1.0.4", + "_shasum": "8227559f2d839f8f984f45bbd438eff5058b7de1", + "_from": "less-middleware@", + "_resolved": "https://registry.npmjs.org/less-middleware/-/less-middleware-1.0.4.tgz" +} diff --git a/node_modules/less-middleware/readme.md b/node_modules/less-middleware/readme.md new file mode 100644 index 000000000..d60a5ae65 --- /dev/null +++ b/node_modules/less-middleware/readme.md @@ -0,0 +1,210 @@ +**The less-middleware has recently been updated to version `1.0.4`.** + +**If you are seeing an error similar to `TypeError: Arguments to path.join must be strings` please read the [migration guide](https://github.com/emberfeather/less.js-middleware/wiki/Migration-0.1.x-1.0.x) to update your code.** + +This middleware was created to allow processing of [Less](http://lesscss.org) files for [Connect JS](http://www.senchalabs.org/connect/) framework and by extension the [Express JS](http://expressjs.com/) framework. + +[![Build Status](https://drone.io/github.com/emberfeather/less.js-middleware/status.png)](https://drone.io/github.com/emberfeather/less.js-middleware/latest) + +## Installation + +```sh +npm install less-middleware --save +``` + +## Usage + +```js +lessMiddleware(source, [{options}]) +``` + +### Express + +```js +var lessMiddleware = require('less-middleware'); + +var app = express(); +app.use(lessMiddleware(__dirname + '/public')); +app.use(express.static(__dirname + '/public')); +``` + +### `options` + +The following options can be used to control the behavior of the middleware: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionDescriptionDefault
    compilerOptions for the less compiler. See the "compiler Options" section below.
    debugShow more verbose logging?false
    destDestination directory to output the compiled .css files.Same directory as less source files.
    forceAlways re-compile less files on each request.false
    onceOnly recompile once after each server restart. Useful for reducing disk i/o on production.false
    parserOptions for the less parser. See the "parser Options" section below.
    pathRootCommon root of the source and destination. It is prepended to both the source and destination before being used.null
    postprocessObject containing functions relavent to preprocessing data.
    postprocess.cssFunction that modifies the compiled css output before being stored.function(css, req){...}
    preprocessObject containing functions relavent to preprocessing data.
    preprocess.lessFunction that modifies the raw less output before being parsed and compiled.function(src, req){...}
    preprocess.pathFunction that modifies the less pathname before being loaded from the filesystem.function(pathname, req){...}
    storeCssFunction that is in charge of storing the css in the filesystem.function(pathname, css, next){...}
    cacheFilePath to a JSON file that will be used to cache less data across server restarts. This can greatly speed up initial load time after a server restart - if the less files haven't changed and the css files still exist, specifying this option will mean that the less files don't need to be recompiled after a server restart.
    + +## `compiler` Options + +The `options.compiler` is passed directly into the less parser with minimal defaults or changes by the middleware. + +The following are the defaults used by the middleware: + + + + + + + + + + + + + + + + + + + + + + +
    OptionDefault
    compressauto
    sourceMapfalse
    yuicompressfalse
    + +## `parser` Options + +The `options.parser` is passed directly into the less parser with minimal defaults or changes by the middleware. + +The following are the defaults used by the middleware: + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionDefault
    dumpLineNumbers0
    paths[source]
    optimization0
    relativeUrlsfalse
    + +## Examples + +Common examples of using the Less middleware are available in the [wiki](https://github.com/emberfeather/less.js-middleware/wiki/Examples). + +## Troubleshooting + +### My less never recompiles, even when I use `{force: true}`! + +Make sure you're declaring less-middleware before your static middleware, if you're using the same directory, e.g. (with express): + + +```js +var lessMiddleware = require('less-middleware'); + +var app = express(); +app.use(lessMiddleware(__dirname + '/public')); +app.use(express.static(__dirname + '/public')); +``` + +not + +```js +var lessMiddleware = require('less-middleware'); + +var app = express(); +app.use(express.static(__dirname + '/public')); +app.use(lessMiddleware(__dirname + '/public')); +``` + +### IIS + +If you are hosting your app on IIS you will have to modify your `web.config` file in order to allow NodeJS to serve your CSS static files. IIS will cache your CSS files, bypassing NodeJS static file serving, which in turn does not allow the middleware to recompile your LESS files. diff --git a/node_modules/less-middleware/test/fixtures/cacheFile-exp.json b/node_modules/less-middleware/test/fixtures/cacheFile-exp.json new file mode 100644 index 000000000..a2af62aac --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/cacheFile-exp.json @@ -0,0 +1,15 @@ +{ + "{$}/import.less":{ + "imports":[ + { + "path":"{$}/import-header.less" + }, + { + "path":"{$}/import-color.less" + }, + { + "path":"{$}/import-widget.less" + } + ] + } +} diff --git a/node_modules/less-middleware/test/fixtures/cacheFile-exp2.json b/node_modules/less-middleware/test/fixtures/cacheFile-exp2.json new file mode 100644 index 000000000..2231db3b6 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/cacheFile-exp2.json @@ -0,0 +1,9 @@ +{ + "{$}/import.less":{ + "imports":[ + { + "path":"{$}/import-color.less" + } + ] + } +} diff --git a/node_modules/less-middleware/test/fixtures/import-color.less b/node_modules/less-middleware/test/fixtures/import-color.less new file mode 100644 index 000000000..9f5fce6d0 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/import-color.less @@ -0,0 +1,2 @@ +@titleColor: #f00; +@linkColor: #00f; diff --git a/node_modules/less-middleware/test/fixtures/import-exp.css b/node_modules/less-middleware/test/fixtures/import-exp.css new file mode 100644 index 000000000..77f1d98cc --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/import-exp.css @@ -0,0 +1 @@ +#header{color:#f00}.widget{color:#f00;background:#00f} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/import-header.less b/node_modules/less-middleware/test/fixtures/import-header.less new file mode 100644 index 000000000..633a8f173 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/import-header.less @@ -0,0 +1,5 @@ +@import "import-color"; + +#header { + color: @titleColor; +} diff --git a/node_modules/less-middleware/test/fixtures/import-widget.less b/node_modules/less-middleware/test/fixtures/import-widget.less new file mode 100644 index 000000000..85cd7ba71 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/import-widget.less @@ -0,0 +1,6 @@ +@import "import-color"; + +.widget { + color: @titleColor; + background: @linkColor; +} diff --git a/node_modules/less-middleware/test/fixtures/import.less b/node_modules/less-middleware/test/fixtures/import.less new file mode 100644 index 000000000..0c4911d89 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/import.less @@ -0,0 +1,2 @@ +@import "import-header"; +@import "import-widget"; diff --git a/node_modules/less-middleware/test/fixtures/importSimple-exp.css b/node_modules/less-middleware/test/fixtures/importSimple-exp.css new file mode 100644 index 000000000..4a5c01d6b --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/importSimple-exp.css @@ -0,0 +1 @@ +a{color:#00f} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/importSimple.less b/node_modules/less-middleware/test/fixtures/importSimple.less new file mode 100644 index 000000000..64479eed3 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/importSimple.less @@ -0,0 +1,5 @@ +@import "import-color"; + +a { + color: @linkColor; +} diff --git a/node_modules/less-middleware/test/fixtures/pathRoot-exp.css b/node_modules/less-middleware/test/fixtures/pathRoot-exp.css new file mode 100644 index 000000000..02f42d63e --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/pathRoot-exp.css @@ -0,0 +1 @@ +body{color:#d3d3d3} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/pathRoot.less b/node_modules/less-middleware/test/fixtures/pathRoot.less new file mode 100644 index 000000000..dca4f6b6f --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/pathRoot.less @@ -0,0 +1,5 @@ +@color1: #d3d3d3; + +body { + color: @color1; +} diff --git a/node_modules/less-middleware/test/fixtures/postprocessCss-exp.css b/node_modules/less-middleware/test/fixtures/postprocessCss-exp.css new file mode 100644 index 000000000..7356f9b5d --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/postprocessCss-exp.css @@ -0,0 +1,2 @@ +/* Prepended Comment */ +.widget{color:#f00} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/postprocessCss.less b/node_modules/less-middleware/test/fixtures/postprocessCss.less new file mode 100644 index 000000000..83ff730f0 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/postprocessCss.less @@ -0,0 +1,3 @@ +.widget { + color: #f00; +} diff --git a/node_modules/less-middleware/test/fixtures/preprocessLess-exp-a.css b/node_modules/less-middleware/test/fixtures/preprocessLess-exp-a.css new file mode 100644 index 000000000..5206d1bdd --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/preprocessLess-exp-a.css @@ -0,0 +1 @@ +h1 .widget{color:#00f} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/preprocessLess-exp-b.css b/node_modules/less-middleware/test/fixtures/preprocessLess-exp-b.css new file mode 100644 index 000000000..3ccccb6a7 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/preprocessLess-exp-b.css @@ -0,0 +1 @@ +.widget{color:#00f} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/preprocessLess.less b/node_modules/less-middleware/test/fixtures/preprocessLess.less new file mode 100644 index 000000000..f457541c8 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/preprocessLess.less @@ -0,0 +1,3 @@ +.widget { + color: #00f; +} diff --git a/node_modules/less-middleware/test/fixtures/preprocessPath-exp.css b/node_modules/less-middleware/test/fixtures/preprocessPath-exp.css new file mode 100644 index 000000000..5c6f41272 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/preprocessPath-exp.css @@ -0,0 +1 @@ +.widget{color:#0f0} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/preprocessPath.less b/node_modules/less-middleware/test/fixtures/preprocessPath.less new file mode 100644 index 000000000..48dccc24e --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/preprocessPath.less @@ -0,0 +1,3 @@ +.widget { + color: #0f0; +} diff --git a/node_modules/less-middleware/test/fixtures/simple-exp.css b/node_modules/less-middleware/test/fixtures/simple-exp.css new file mode 100644 index 000000000..02f42d63e --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/simple-exp.css @@ -0,0 +1 @@ +body{color:#d3d3d3} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/simple-exp.css.map b/node_modules/less-middleware/test/fixtures/simple-exp.css.map new file mode 100644 index 000000000..b347302b6 --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/simple-exp.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["simple.less"],"names":[],"mappings":"AAEA,KACI"} \ No newline at end of file diff --git a/node_modules/less-middleware/test/fixtures/simple.less b/node_modules/less-middleware/test/fixtures/simple.less new file mode 100644 index 000000000..dca4f6b6f --- /dev/null +++ b/node_modules/less-middleware/test/fixtures/simple.less @@ -0,0 +1,5 @@ +@color1: #d3d3d3; + +body { + color: @color1; +} diff --git a/node_modules/less-middleware/test/test-middleware.js b/node_modules/less-middleware/test/test-middleware.js new file mode 100644 index 000000000..0a8cad00d --- /dev/null +++ b/node_modules/less-middleware/test/test-middleware.js @@ -0,0 +1,253 @@ +"use strict"; + +var express = require('express'); +var fs = require('fs'); +var mkdirp = require('mkdirp'); +var middleware = require('../lib/middleware'); +var os = require('os'); +var request = require('supertest'); +var assert = require('assert'); +var copySync = require('fs-extra').copySync; +var path = require('path'); + +var tmpDest = __dirname + '/artifacts'; +var clearCache = function(filename) { + if(fs.existsSync(tmpDest + '/' + filename)) { + // Unlinking file since it is cached without reguard to params. + // TODO: Remove when the imports cache is aware of params. + fs.unlinkSync(tmpDest + '/' + filename); + } +}; + +var setupExpress = function(src, options, staticDest) { + staticDest = staticDest || options.dest; + options = options || {}; + var app = express(); + app.use(middleware(src, options)); + app.use(express.static(staticDest)); + return app; +} + +describe('middleware', function(){ + describe('simple', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest + }); + + it('should process simple less files', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/simple-exp.css', 'utf8'); + request(app) + .get('/simple.css') + .expect(200) + .expect(expected, done); + }); + }); + + describe('source map', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest, + force: true, // Need to force since using the same file as the simple test. + compiler: { + sourceMap: true + } + }); + + it('should handle source map files', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/simple-exp.css.map', 'utf8'); + request(app) + .get('/simple.css.map') + .expect(200) + .expect(expected, done); + }); + }); + + describe('import', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest + }); + + it('should process less files with imports', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/importSimple-exp.css', 'utf8'); + request(app) + .get('/importSimple.css') + .expect(200) + .expect(expected, done); + }); + + it('should process less files with nested imports', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/import-exp.css', 'utf8'); + request(app) + .get('/import.css') + .expect(200) + .expect(expected, done); + }); + }); + + describe('options', function(){ + describe('postprocess', function(){ + describe('css', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest, + postprocess: { + css: function(css, req) { + return '/* Prepended Comment */\n' + css; + } + } + }); + + it('should prepend the comment on all output css', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/postprocessCss-exp.css', 'utf8'); + request(app) + .get('/postprocessCss.css') + .expect(200) + .expect(expected, done); + }); + }); + }); + + describe('preprocess', function(){ + describe('less', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest, + preprocess: { + less: function(src, req) { + if (req.param("namespace")) { + src = req.param("namespace") + " { " + src + " }"; + } + return src; + } + } + }); + + it('should add namespace when found', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/preprocessLess-exp-a.css', 'utf8'); + clearCache('preprocessLess.css'); + request(app) + .get('/preprocessLess.css?namespace=h1') + .expect(200) + .expect(expected, done); + }); + + it('should not add namespace when none provided', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/preprocessLess-exp-b.css', 'utf8'); + clearCache('preprocessLess.css'); + request(app) + .get('/preprocessLess.css') + .expect(200) + .expect(expected, done); + }); + }); + + describe('path', function(){ + var app = setupExpress(__dirname + '/fixtures', { + dest: tmpDest, + preprocess: { + path: function(pathname, req) { + return pathname.replace('.ltr', ''); + } + } + }); + + it('should remove .ltr from the less path when found', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/preprocessPath-exp.css', 'utf8'); + request(app) + .get('/preprocessPath.ltr.css') + .expect(200) + .expect(expected, done); + }); + + it('should not change less path when no matching .ltr', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/preprocessPath-exp.css', 'utf8'); + request(app) + .get('/preprocessPath.css') + .expect(200) + .expect(expected, done); + }); + }); + + describe('pathRoot', function(){ + var app = setupExpress('/fixtures', { + dest: '/artifacts', + pathRoot: __dirname + }, tmpDest); + + it('should process simple less files', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/pathRoot-exp.css', 'utf8'); + request(app) + .get('/pathRoot.css') + .expect(200) + .expect(expected, done); + }); + }); + }); + + describe('cacheFile', function() { + var middlewareSrc = tmpDest + '/fixturesCopy'; + var dest = tmpDest + '/cacheFileTest'; + var cacheFile = dest + '/cacheFile.json'; + try { + mkdirp.sync(middlewareSrc); + } catch(e) { + if (e && e.code != 'EEXIST') throw e; + } + copySync(__dirname + '/fixtures', middlewareSrc); + var app; + + var expandExpected = function(file) { + return file.replace(/\{\$\}/g, middlewareSrc); + } + + var checkCacheFile = function(cacheFile, expectedFile){ + return function(){ + middleware._saveCacheToFile(); + var cacheFileExpected = JSON.parse(expandExpected(fs.readFileSync(expectedFile, 'utf8'))); + var cacheFileOutput = JSON.parse(fs.readFileSync(cacheFile, 'utf8')); + for (var file in cacheFileExpected) { + assert(cacheFileOutput[file] != undefined); + var expectedImports = cacheFileExpected[file].imports; + var outputImports = cacheFileOutput[file].imports; + for (var i = 0; i < expectedImports.length; i++) { + assert.equal(expectedImports[i].path, outputImports[i].path); + } + assert.equal(outputImports.length, expectedImports.length); + } + } + } + + beforeEach(function() { + // Unfortunately because cache-related items are stored in globals + // (which they need to be so that they are shared across different + // middleware invocations), to properly test the cacheFile option we + // need to re-require the middleware for each of these tests. + var mpath = path.resolve(__dirname, '../lib/middleware.js'); + delete require.cache[mpath]; + middleware = require('../lib/middleware'); + app = setupExpress(middlewareSrc, { + dest: dest, + cacheFile: cacheFile + }); + }); + + it('should process files correctly and store the right cached imports', function(done){ + var expected = fs.readFileSync(__dirname + '/fixtures/import-exp.css', 'utf8'); + request(app) + .get('/import.css') + .expect(200) + .expect(expected) + .expect(checkCacheFile(cacheFile, __dirname + '/fixtures/cacheFile-exp.json')) + .end(done); + }); + + it('should ignore cached imports if the file has changed and update cached imports', function(done){ + copySync(middlewareSrc + '/importSimple.less', middlewareSrc + '/import.less'); + var expected = fs.readFileSync(__dirname + '/fixtures/importSimple-exp.css', 'utf8'); + request(app) + .get('/import.css') + .expect(200) + .expect(expected) + .expect(checkCacheFile(cacheFile, __dirname + '/fixtures/cacheFile-exp2.json')) + .end(done); + }); + }); + }); +}); diff --git a/node_modules/less-middleware/test/test-utilities.js b/node_modules/less-middleware/test/test-utilities.js new file mode 100644 index 000000000..5c7b80a8c --- /dev/null +++ b/node_modules/less-middleware/test/test-utilities.js @@ -0,0 +1,27 @@ +"use strict"; + +var utilities = require('../lib/utilities'); +var assert = require('assert'); + +describe('utilities', function(){ + describe('#isCompressedPath()', function(){ + it('should match path when valid path found', function(){ + assert.equal(true, utilities.isCompressedPath('styles-min.css')); + assert.equal(true, utilities.isCompressedPath('styles.min.css')); + }); + + it('should not match path when invalid path found', function(){ + assert.equal(false, utilities.isCompressedPath('styles.css')); + }); + }); + + describe('#isValidPath()', function(){ + it('should match path when valid path found', function(){ + assert.equal(true, utilities.isValidPath('styles.css')); + }); + + it('should not match path when invalid path found', function(){ + assert.equal(false, utilities.isValidPath('styles.less')); + }); + }); +}); diff --git a/node_modules/method-override/.npmignore b/node_modules/method-override/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/method-override/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/method-override/History.md b/node_modules/method-override/History.md new file mode 100644 index 000000000..5e3dd3654 --- /dev/null +++ b/node_modules/method-override/History.md @@ -0,0 +1,15 @@ +1.0.2 / 2014-05-22 +================== + + * Handle `req.body` key referencing array or object + * Handle multiple HTTP headers + +1.0.1 / 2014-05-17 +================== + + * deps: pin dependency versions + +1.0.0 / 2014-03-03 +================== + + * Genesis from `connect` diff --git a/node_modules/method-override/README.md b/node_modules/method-override/README.md new file mode 100644 index 000000000..0a375d945 --- /dev/null +++ b/node_modules/method-override/README.md @@ -0,0 +1,69 @@ +# method-override [![Build Status](https://travis-ci.org/expressjs/method-override.svg)](https://travis-ci.org/expressjs/method-override) [![NPM version](https://badge.fury.io/js/method-override.svg)](http://badge.fury.io/js/method-override) + +Lets you use HTTP verbs such as PUT or DELETE in places you normally can't. + +Previously `connect.methodOverride()`. + +## Install + +```sh +$ npm install method-override +``` + +## API + +**NOTE** It is very important that this module is used **before** any module that +needs to know the method of the request (for example, it _must_ be used prior to +the `csurf` module). + +### methodOverride(key) + +Create a new middleware function to override the `req.method` property with a new +value. This value will be pulled from the `X-HTTP-Method-Override` header of the +request. If this header is not present, then this module will look in the `req.body` +object for a property name given by the `key` argument (and if found, will delete +the property from `req.body`). + +If the found method is supported by node.js core, then `req.method` will be set to +this value, as if it has originally been that value. The previous `req.method` +value will be stored in `req.originalMethod`. + +#### key + +This is the property to look for the overwritten method in the `req.body` object. +This defaults to `"_method"`. + +## Examples + +```js +var bodyParser = require('body-parser') +var connect = require('connect') +var methodOverride = require('method-override') + +app.use(bodyParser()) +app.use(methodOverride()) +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +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/method-override/index.js b/node_modules/method-override/index.js new file mode 100644 index 000000000..31b4bbf46 --- /dev/null +++ b/node_modules/method-override/index.js @@ -0,0 +1,70 @@ +/*! + * Connect - methodOverride + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var methods = require('methods'); + +/** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, otherwise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param {String} key + * @return {Function} + * @api public + */ + +module.exports = function methodOverride(key){ + key = key || '_method'; + return function methodOverride(req, res, next) { + var method + var val + + req.originalMethod = req.originalMethod || req.method; + + // req.body + if (req.body && typeof req.body === 'object' && key in req.body) { + method = req.body[key] + delete req.body[key] + } + + // check X-HTTP-Method-Override + val = req.headers['x-http-method-override'] + if (val) { + // multiple headers get joined with comma by node.js core + method = val.split(/ *, */) + } + + if (Array.isArray(method)) { + method = method[0] + } + + // replace + if (supports(method)) { + req.method = method.toUpperCase() + } + + next(); + }; +}; + +/** + * Check if node supports `method`. + */ + +function supports(method) { + return method + && typeof method === 'string' + && methods.indexOf(method.toLowerCase()) !== -1 +} diff --git a/node_modules/method-override/node_modules/methods/.npmignore b/node_modules/method-override/node_modules/methods/.npmignore new file mode 100644 index 000000000..c2658d7d1 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/method-override/node_modules/methods/History.md b/node_modules/method-override/node_modules/methods/History.md new file mode 100644 index 000000000..2fbd77625 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/History.md @@ -0,0 +1,10 @@ + +1.0.0 / 2014-05-08 +================== + + * add PURGE. Closes #9 + +0.1.0 / 2013-10-28 +================== + + * add http.METHODS support diff --git a/node_modules/method-override/node_modules/methods/LICENSE b/node_modules/method-override/node_modules/methods/LICENSE new file mode 100644 index 000000000..8bce401dc --- /dev/null +++ b/node_modules/method-override/node_modules/methods/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk + +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/method-override/node_modules/methods/Readme.md b/node_modules/method-override/node_modules/methods/Readme.md new file mode 100644 index 000000000..ac0658e21 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/Readme.md @@ -0,0 +1,4 @@ + +# Methods + + HTTP verbs that node core's parser supports. diff --git a/node_modules/method-override/node_modules/methods/index.js b/node_modules/method-override/node_modules/methods/index.js new file mode 100644 index 000000000..0f9cea919 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/index.js @@ -0,0 +1,38 @@ + +var http = require('http'); + +if (http.METHODS) { + module.exports = http.METHODS.map(function(method){ + return method.toLowerCase(); + }); + + return; +} + +module.exports = [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search' +]; diff --git a/node_modules/method-override/node_modules/methods/package.json b/node_modules/method-override/node_modules/methods/package.json new file mode 100644 index 000000000..a184b8678 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/package.json @@ -0,0 +1,49 @@ +{ + "name": "methods", + "version": "1.0.0", + "description": "HTTP methods that node supports", + "main": "index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha" + }, + "keywords": [ + "http", + "methods" + ], + "author": { + "name": "TJ Holowaychuk" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-methods.git" + }, + "devDependencies": { + "mocha": "1.17.x" + }, + "bugs": { + "url": "https://github.com/visionmedia/node-methods/issues" + }, + "homepage": "https://github.com/visionmedia/node-methods", + "_id": "methods@1.0.0", + "dist": { + "shasum": "9a73d86375dfcef26ef61ca3e4b8a2e2538a80e3", + "tarball": "http://registry.npmjs.org/methods/-/methods-1.0.0.tgz" + }, + "_from": "methods@1.0.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "9a73d86375dfcef26ef61ca3e4b8a2e2538a80e3", + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/method-override/node_modules/methods/test/methods.js b/node_modules/method-override/node_modules/methods/test/methods.js new file mode 100644 index 000000000..527beaba8 --- /dev/null +++ b/node_modules/method-override/node_modules/methods/test/methods.js @@ -0,0 +1,33 @@ +var http = require('http'); +var assert = require('assert'); +var methods = require('..'); + +describe('methods', function() { + + if (http.METHODS) { + + it('is a lowercased http.METHODS', function() { + var lowercased = http.METHODS.map(function(method) { + return method.toLowerCase(); + }); + assert.deepEqual(lowercased, methods); + }); + + } else { + + it('contains GET, POST, PUT, and DELETE', function() { + assert.notEqual(methods.indexOf('get'), -1); + assert.notEqual(methods.indexOf('post'), -1); + assert.notEqual(methods.indexOf('put'), -1); + assert.notEqual(methods.indexOf('delete'), -1); + }); + + it('is all lowercase', function() { + for (var i = 0; i < methods.length; i ++) { + assert(methods[i], methods[i].toLowerCase(), methods[i] + " isn't all lowercase"); + } + }); + + } + +}); diff --git a/node_modules/method-override/package.json b/node_modules/method-override/package.json new file mode 100644 index 000000000..b9851ad10 --- /dev/null +++ b/node_modules/method-override/package.json @@ -0,0 +1,82 @@ +{ + "name": "method-override", + "description": "Override HTTP verbs", + "version": "1.0.2", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/method-override.git" + }, + "bugs": { + "url": "https://github.com/expressjs/method-override/issues" + }, + "dependencies": { + "methods": "1.0.0" + }, + "devDependencies": { + "istanbul": "0.2.10", + "mocha": "~1.19.0", + "supertest": "~0.12.1" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "homepage": "https://github.com/expressjs/method-override", + "_id": "method-override@1.0.2", + "_shasum": "d6f80275db23a23380028c9215b97470be01d689", + "_from": "method-override@^1.0.0", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "d6f80275db23a23380028c9215b97470be01d689", + "tarball": "http://registry.npmjs.org/method-override/-/method-override-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/method-override/-/method-override-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/.npmignore b/node_modules/morgan/.npmignore new file mode 100644 index 000000000..cd39b7720 --- /dev/null +++ b/node_modules/morgan/.npmignore @@ -0,0 +1,3 @@ +coverage/ +test/ +.travis.yml diff --git a/node_modules/morgan/History.md b/node_modules/morgan/History.md new file mode 100644 index 000000000..ca4557e44 --- /dev/null +++ b/node_modules/morgan/History.md @@ -0,0 +1,56 @@ +1.2.3 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.2.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.2.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.2.0 / 2014-07-19 +================== + + * Add `:remote-user` token + * Add `combined` log format + * Add `common` log format + * Add `morgan(format, options)` function signature + * Deprecate `default` format -- use `combined` format instead + * Deprecate not providing a format + * Remove non-standard grey color from `dev` format + +1.1.1 / 2014-05-20 +================== + + * simplify method to get remote address + +1.1.0 / 2014-05-18 +================== + + * "dev" format will use same tokens as other formats + * `:response-time` token is now empty when immediate used + * `:response-time` token is now monotonic + * `:response-time` token has precision to 1 μs + * fix `:status` + immediate output in node.js 0.8 + * improve `buffer` option to prevent indefinite event loop holding + * deps: bytes@1.0.0 + - add negative support + +1.0.1 / 2014-05-04 +================== + + * Make buffer unique per morgan instance + * deps: bytes@0.3.0 + * added terabyte support + +1.0.0 / 2014-02-08 +================== + + * Initial release diff --git a/node_modules/morgan/README.md b/node_modules/morgan/README.md new file mode 100644 index 000000000..e6723b4e1 --- /dev/null +++ b/node_modules/morgan/README.md @@ -0,0 +1,149 @@ +# morgan + +[![NPM version](https://badge.fury.io/js/morgan.svg)](http://badge.fury.io/js/morgan) +[![Build Status](https://travis-ci.org/expressjs/morgan.svg?branch=master)](https://travis-ci.org/expressjs/morgan) +[![Coverage Status](https://img.shields.io/coveralls/expressjs/morgan.svg?branch=master)](https://coveralls.io/r/expressjs/morgan) +[![Gittip](http://img.shields.io/gittip/dougwilson.svg)](https://www.gittip.com/dougwilson/) + +HTTP request logger middleware for node.js + +> Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion. + +## API + +```js +var express = require('express') +var morgan = require('morgan') + +var app = express() +app.use(morgan('combined')) +``` + +### morgan(format, options) + +Create a new morgan logger middleware function using the given `format` and `options`. +The `format` argument may be a string of a predefined name (see below for the names), +a string of a format string, or a function that will produce a log entry. + +```js +// a pre-defined name +morgan('combined') + +// a format string +morgan(':remote-addr :method :url') + +// a custom function +morgan(function (req, res) { + return req.method + ' ' + req.url +}) +``` + +#### Options + +Morgan accepts these properties in the options object. + +#### buffer + +Buffer duration before writing logs to the `stream`, defaults to `false`. When +set to `true`, defaults to `1000 ms`. + +#### immediate + +Write log line on request instead of response. This means that a requests will +be logged even if the server crashes, _but data from the response (like the +response code, content length, etc.) cannot be logged_. + +##### skip + +Function to determine if logging is skipped, defaults to `false`. This function +will be called as `skip(req, res)`. + +```js +// only log error responses +morgan('combined', { + skip: function (req, res) { return res.statusCode < 400 } +}) +``` + +##### stream + +Output stream for writing log lines, defaults to `process.stdout`. + +#### Predefined Formats + +There are various pre-defined formats provided: + +##### combined + +Standard Apache combined log output. + +``` +:remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" +``` + +##### common + +Standard Apache common log output. + +``` +:remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] +``` + +##### dev + +Concise output colored by response status for development use. The `:status` +token will be colored red for server error codes, yellow for client error +codes, cyan for redirection codes, and uncolored for all other codes. + +``` +:method :url :status :response-time ms - :res[content-length] +``` + +##### short + +Shorter than default, also including response time. + +``` +:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms +``` + +##### tiny + +The minimal output. + +``` +:method :url :status :res[content-length] - :response-time ms +``` + +#### Tokens + +- `:req[header]` ex: `:req[Accept]` +- `:res[header]` ex: `:res[Content-Length]` +- `:http-version` +- `:response-time` +- `:remote-addr` +- `:remote-user` +- `:date` +- `:method` +- `:url` +- `:referrer` +- `:user-agent` +- `:status` + +To define a token, simply invoke `morgan.token()` with the name and a callback function. The value returned is then available as ":type" in this case: +```js +morgan.token('type', function(req, res){ return req.headers['content-type']; }) +``` + + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +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/morgan/index.js b/node_modules/morgan/index.js new file mode 100644 index 000000000..7a6d35b56 --- /dev/null +++ b/node_modules/morgan/index.js @@ -0,0 +1,314 @@ +/*! + * morgan + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var auth = require('basic-auth') +var bytes = require('bytes'); +var deprecate = require('depd')('morgan') +var onFinished = require('on-finished') + +/** + * Default log buffer duration. + */ + +var defaultBufferDuration = 1000; + +/** + * Create a logger middleware. + * + * @param {String|Function} format + * @param {Object} [options] + * @return {Function} middleware + * @api public + */ + +exports = module.exports = function morgan(format, options) { + if (typeof format === 'object') { + options = format + format = options.format || 'default' + + // smart deprecation message + deprecate('morgan(options): use morgan(' + (typeof format === 'string' ? JSON.stringify(format) : 'format') + ', options) instead') + } + + if (format === undefined) { + deprecate('undefined format: specify a format') + } + + options = options || {} + + // output on request instead of response + var immediate = options.immediate; + + // check if log entry should be skipped + var skip = options.skip || function () { return false; }; + + // format name + var fmt = exports[format] || format || exports.default; + + // compile format + if ('function' != typeof fmt) fmt = compile(fmt); + + // options + var stream = options.stream || process.stdout + , buffer = options.buffer; + + // buffering support + if (buffer) { + var realStream = stream + var buf = [] + var timer = null + var interval = 'number' == typeof buffer + ? buffer + : defaultBufferDuration + + // flush function + var flush = function(){ + timer = null + + if (buf.length) { + realStream.write(buf.join('')); + buf.length = 0; + } + } + + // swap the stream + stream = { + write: function(str){ + if (timer === null) { + timer = setTimeout(flush, interval) + } + + buf.push(str); + } + }; + } + + return function logger(req, res, next) { + req._startAt = process.hrtime(); + req._startTime = new Date; + req._remoteAddress = req.connection && req.connection.remoteAddress; + + function logRequest(){ + if (skip(req, res)) return; + var line = fmt(exports, req, res); + if (null == line) return; + stream.write(line + '\n'); + }; + + // immediate + if (immediate) { + logRequest(); + } else { + onFinished(res, logRequest) + } + + next(); + }; +}; + +/** + * Compile `fmt` into a function. + * + * @param {String} fmt + * @return {Function} + * @api private + */ + +function compile(fmt) { + fmt = fmt.replace(/"/g, '\\"'); + var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ + return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "'; + }) + '";' + return new Function('tokens, req, res', js); +}; + +/** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param {String} name + * @param {Function} fn + * @return {Object} exports for chaining + * @api public + */ + +exports.token = function(name, fn) { + exports[name] = fn; + return this; +}; + +/** + * Define a `fmt` with the given `name`. + * + * @param {String} name + * @param {String|Function} fmt + * @return {Object} exports for chaining + * @api public + */ + +exports.format = function(name, fmt){ + exports[name] = fmt; + return this; +}; + +/** + * Apache combined log format. + */ + +exports.format('combined', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"') + +/** + * Apache common log format. + */ + +exports.format('common', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length]') + +/** + * Default format. + */ + +exports.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); +deprecate.property(exports, 'default', 'default format: use combined format') + +/** + * Short format. + */ + +exports.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); + +/** + * Tiny format. + */ + +exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); + +/** + * dev (colored) + */ + +exports.format('dev', function(tokens, req, res){ + var color = 32; // green + var status = res.statusCode; + + if (status >= 500) color = 31; // red + else if (status >= 400) color = 33; // yellow + else if (status >= 300) color = 36; // cyan + + var fn = compile('\x1b[0m:method :url \x1b[' + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m'); + + return fn(tokens, req, res); +}); + +/** + * request url + */ + +exports.token('url', function(req){ + return req.originalUrl || req.url; +}); + +/** + * request method + */ + +exports.token('method', function(req){ + return req.method; +}); + +/** + * response time in milliseconds + */ + +exports.token('response-time', function(req, res){ + if (!res._header || !req._startAt) return ''; + var diff = process.hrtime(req._startAt); + var ms = diff[0] * 1e3 + diff[1] * 1e-6; + return ms.toFixed(3); +}); + +/** + * UTC date + */ + +exports.token('date', function(){ + return new Date().toUTCString(); +}); + +/** + * response status code + */ + +exports.token('status', function(req, res){ + return res._header ? res.statusCode : null; +}); + +/** + * normalized referrer + */ + +exports.token('referrer', function(req){ + return req.headers['referer'] || req.headers['referrer']; +}); + +/** + * remote address + */ + +exports.token('remote-addr', function(req){ + if (req.ip) return req.ip; + if (req._remoteAddress) return req._remoteAddress; + if (req.connection) return req.connection.remoteAddress; + return undefined; +}); + +/** + * remote user + */ + +exports.token('remote-user', function (req) { + var creds = auth(req) + var user = (creds && creds.name) || '-' + return user; +}) + +/** + * HTTP version + */ + +exports.token('http-version', function(req){ + return req.httpVersionMajor + '.' + req.httpVersionMinor; +}); + +/** + * UA string + */ + +exports.token('user-agent', function(req){ + return req.headers['user-agent']; +}); + +/** + * request header + */ + +exports.token('req', function(req, res, field){ + return req.headers[field.toLowerCase()]; +}); + +/** + * response header + */ + +exports.token('res', function(req, res, field){ + return (res._headers || {})[field.toLowerCase()]; +}); + diff --git a/node_modules/morgan/node_modules/basic-auth/Readme.md b/node_modules/morgan/node_modules/basic-auth/Readme.md new file mode 100644 index 000000000..5859757c6 --- /dev/null +++ b/node_modules/morgan/node_modules/basic-auth/Readme.md @@ -0,0 +1,26 @@ +# basic-auth + + Generic basic auth Authorization header field parser for whatever. + +## Installation + +``` +$ npm install basic-auth +``` + +## Example + + Pass a node request or koa Context object to the module exported. If + parsing fails `undefined` is returned, otherwise an object with + `.name` and `.pass`. + +```js +var auth = require('basic-auth'); +var user = auth(req); +// => { name: 'something', pass: 'whatever' } + +``` + +# License + + MIT diff --git a/node_modules/morgan/node_modules/basic-auth/index.js b/node_modules/morgan/node_modules/basic-auth/index.js new file mode 100644 index 000000000..3ef1ff171 --- /dev/null +++ b/node_modules/morgan/node_modules/basic-auth/index.js @@ -0,0 +1,28 @@ + +/** + * Parse the Authorization header field of `req`. + * + * @param {Request} req + * @return {Object} with .name and .pass + * @api public + */ + +module.exports = function(req){ + req = req.req || req; + + var auth = req.headers.authorization; + if (!auth) return; + + // malformed + var parts = auth.split(' '); + if ('basic' != parts[0].toLowerCase()) return; + if (!parts[1]) return; + auth = parts[1]; + + // credentials + auth = new Buffer(auth, 'base64').toString(); + auth = auth.match(/^([^:]*):(.*)$/); + if (!auth) return; + + return { name: auth[1], pass: auth[2] }; +}; diff --git a/node_modules/morgan/node_modules/basic-auth/package.json b/node_modules/morgan/node_modules/basic-auth/package.json new file mode 100644 index 000000000..844455dff --- /dev/null +++ b/node_modules/morgan/node_modules/basic-auth/package.json @@ -0,0 +1,56 @@ +{ + "name": "basic-auth", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-basic-auth" + }, + "description": "generic basic auth parser", + "keywords": [ + "basic", + "auth", + "authorization", + "basicauth" + ], + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "make test" + }, + "files": [ + "index.js" + ], + "license": "MIT", + "gitHead": "099e8c703ea3994d72240492aba9b115517cf45e", + "bugs": { + "url": "https://github.com/visionmedia/node-basic-auth/issues" + }, + "homepage": "https://github.com/visionmedia/node-basic-auth", + "_id": "basic-auth@1.0.0", + "_shasum": "111b2d9ff8e4e6d136b8c84ea5e096cb87351637", + "_from": "basic-auth@1.0.0", + "_npmVersion": "1.4.16", + "_npmUser": { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "111b2d9ff8e4e6d136b8c84ea5e096cb87351637", + "tarball": "http://registry.npmjs.org/basic-auth/-/basic-auth-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/node_modules/bytes/.npmignore b/node_modules/morgan/node_modules/bytes/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/morgan/node_modules/bytes/History.md b/node_modules/morgan/node_modules/bytes/History.md new file mode 100644 index 000000000..5097352ec --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/History.md @@ -0,0 +1,25 @@ + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/morgan/node_modules/bytes/Makefile b/node_modules/morgan/node_modules/bytes/Makefile new file mode 100644 index 000000000..8e8640f2e --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --reporter spec \ + --require should + +.PHONY: test \ No newline at end of file diff --git a/node_modules/morgan/node_modules/bytes/Readme.md b/node_modules/morgan/node_modules/bytes/Readme.md new file mode 100644 index 000000000..5591b28fb --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/Readme.md @@ -0,0 +1,54 @@ +# node-bytes + + Byte string parser / formatter. + +## Example: + +```js +bytes('1kb') +// => 1024 + +bytes('2mb') +// => 2097152 + +bytes('1gb') +// => 1073741824 + +bytes(1073741824) +// => 1gb + +bytes(1099511627776) +// => 1tb +``` + +## Installation + +``` +$ npm install bytes +$ component install visionmedia/bytes.js +``` + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +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/morgan/node_modules/bytes/component.json b/node_modules/morgan/node_modules/bytes/component.json new file mode 100644 index 000000000..2929c25d6 --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/component.json @@ -0,0 +1,7 @@ +{ + "name": "bytes", + "description": "byte size string parser / serializer", + "keywords": ["bytes", "utility"], + "version": "0.2.1", + "scripts": ["index.js"] +} diff --git a/node_modules/morgan/node_modules/bytes/index.js b/node_modules/morgan/node_modules/bytes/index.js new file mode 100644 index 000000000..c1da2fe40 --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/index.js @@ -0,0 +1,41 @@ + +/** + * Parse byte `size` string. + * + * @param {String} size + * @return {Number} + * @api public + */ + +module.exports = function(size) { + if ('number' == typeof size) return convert(size); + var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb|tb)$/) + , n = parseFloat(parts[1]) + , type = parts[2]; + + var map = { + kb: 1 << 10 + , mb: 1 << 20 + , gb: 1 << 30 + , tb: ((1 << 30) * 1024) + }; + + return map[type] * n; +}; + +/** + * convert bytes into string. + * + * @param {Number} b - bytes to convert + * @return {String} + * @api public + */ + +function convert (b) { + var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10, abs = Math.abs(b); + if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb'; + if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; + if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; + if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; + return b + 'b'; +} diff --git a/node_modules/morgan/node_modules/bytes/package.json b/node_modules/morgan/node_modules/bytes/package.json new file mode 100644 index 000000000..61a79a5f8 --- /dev/null +++ b/node_modules/morgan/node_modules/bytes/package.json @@ -0,0 +1,50 @@ +{ + "name": "bytes", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "byte size string parser / serializer", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/bytes.js.git" + }, + "version": "1.0.0", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "component": { + "scripts": { + "bytes/index.js": "index.js" + } + }, + "bugs": { + "url": "https://github.com/visionmedia/bytes.js/issues" + }, + "homepage": "https://github.com/visionmedia/bytes.js", + "_id": "bytes@1.0.0", + "dist": { + "shasum": "3569ede8ba34315fab99c3e92cb04c7220de1fa8", + "tarball": "http://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz" + }, + "_from": "bytes@1.0.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "3569ede8ba34315fab99c3e92cb04c7220de1fa8", + "_resolved": "https://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/node_modules/depd/.npmignore b/node_modules/morgan/node_modules/depd/.npmignore new file mode 100644 index 000000000..0c7e391fd --- /dev/null +++ b/node_modules/morgan/node_modules/depd/.npmignore @@ -0,0 +1,4 @@ +coverage/ +files/ +test/ +.travis.yml diff --git a/node_modules/morgan/node_modules/depd/History.md b/node_modules/morgan/node_modules/depd/History.md new file mode 100644 index 000000000..ba1af12ee --- /dev/null +++ b/node_modules/morgan/node_modules/depd/History.md @@ -0,0 +1,56 @@ +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/morgan/node_modules/depd/LICENSE b/node_modules/morgan/node_modules/depd/LICENSE new file mode 100644 index 000000000..b7dce6cf9 --- /dev/null +++ b/node_modules/morgan/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/morgan/node_modules/depd/Readme.md b/node_modules/morgan/node_modules/depd/Readme.md new file mode 100644 index 000000000..47a53a179 --- /dev/null +++ b/node_modules/morgan/node_modules/depd/Readme.md @@ -0,0 +1,272 @@ +# depd + +[![NPM version](https://badge.fury.io/js/depd.svg)](http://badge.fury.io/js/depd) +[![Build Status](https://travis-ci.org/dougwilson/nodejs-depd.svg?branch=master)](https://travis-ci.org/dougwilson/nodejs-depd) +[![Coverage Status](https://img.shields.io/coveralls/dougwilson/nodejs-depd.svg?branch=master)](https://coveralls.io/r/dougwilson/nodejs-depd) +[![Gittip](http://img.shields.io/gittip/dougwilson.svg)](https://www.gittip.com/dougwilson/) + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +```sh +$ npm install depd +``` + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspecting the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations. + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations. + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/morgan/node_modules/depd/index.js b/node_modules/morgan/node_modules/depd/index.js new file mode 100644 index 000000000..a6fb37288 --- /dev/null +++ b/node_modules/morgan/node_modules/depd/index.js @@ -0,0 +1,520 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Get listener count on event emitter. + */ + +/*istanbul ignore next*/ +var eventListenerCount = EventEmitter.listenerCount + || function (emitter, type) { return emitter.listeners(type).length } + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + var typeName = callSite.getTypeName() + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + // make useful type name + if (typeName === 'Function') { + typeName = callSite.getThis().name || typeName + } + + return callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/morgan/node_modules/depd/package.json b/node_modules/morgan/node_modules/depd/package.json new file mode 100644 index 000000000..6935dc5f1 --- /dev/null +++ b/node_modules/morgan/node_modules/depd/package.json @@ -0,0 +1,56 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "0.4.4", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git://github.com/dougwilson/nodejs-depd" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.20.1", + "should": "~4.0.4" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --require should test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" + }, + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@0.4.4", + "dist": { + "shasum": "07091fae75f97828d89b4a02a2d4778f0e7c0662", + "tarball": "http://registry.npmjs.org/depd/-/depd-0.4.4.tgz" + }, + "_from": "depd@0.4.4", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "directories": {}, + "_shasum": "07091fae75f97828d89b4a02a2d4778f0e7c0662", + "_resolved": "https://registry.npmjs.org/depd/-/depd-0.4.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/node_modules/on-finished/HISTORY.md b/node_modules/morgan/node_modules/on-finished/HISTORY.md new file mode 100644 index 000000000..0aa241b19 --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/HISTORY.md @@ -0,0 +1,66 @@ +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/morgan/node_modules/on-finished/LICENSE b/node_modules/morgan/node_modules/on-finished/LICENSE new file mode 100644 index 000000000..5931fd23e --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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/morgan/node_modules/on-finished/README.md b/node_modules/morgan/node_modules/on-finished/README.md new file mode 100644 index 000000000..887b5c389 --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/README.md @@ -0,0 +1,90 @@ +# on-finished + +[![NPM Version](http://img.shields.io/npm/v/on-finished.svg?style=flat)](https://www.npmjs.org/package/on-finished) +[![Node.js Version](http://img.shields.io/badge/node.js->=_0.8-brightgreen.svg?style=flat)](http://nodejs.org/download/) +[![Build Status](http://img.shields.io/travis/jshttp/on-finished.svg?style=flat)](https://travis-ci.org/jshttp/on-finished) +[![Coverage Status](https://img.shields.io/coveralls/jshttp/on-finished.svg?style=flat)](https://coveralls.io/r/jshttp/on-finished) + +Execute a callback when a request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to to an error, the first argument will contain the error. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +```js +onFinished(res, function (err) { + // clean up open fds, etc. +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to to an error, the first argument will contain the error. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +```js +var data = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +### Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) diff --git a/node_modules/morgan/node_modules/on-finished/index.js b/node_modules/morgan/node_modules/on-finished/index.js new file mode 100644 index 000000000..a5055610b --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/index.js @@ -0,0 +1,127 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = onFinished; +module.exports.isFinished = isFinished; + +/** +* Module dependencies. +*/ + +var first = require('ee-first') + +/** +* Variables. +*/ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @api public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine is message is already finished. + * + * @param {object} msg + * @return {boolean} + * @api public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(!socket || msg.finished || !socket.writable) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(!socket || msg.complete || !socket.readable) + } + + // don't know + return undefined +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @api private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + var socket = msg.socket + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + + // finished on first event + first([ + [socket, 'error', 'close'], + [msg, 'end', 'finish'], + ], attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @api private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err) + } + } + + listener.queue = [] + + return listener +} diff --git a/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/LICENSE b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 000000000..a7ae8ee9b --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +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/morgan/node_modules/on-finished/node_modules/ee-first/README.md b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 000000000..0ebc0aa4f --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,63 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/index.js b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 000000000..d0c48c994 --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,60 @@ + +module.exports = function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, cleanup) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + return function (fn) { + done = fn + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + done.apply(null, arguments) + } +} + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/package.json b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 000000000..54d04e1f6 --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.0.5", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/jonathanong/ee-first" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "1" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "c9d9a6881863c0d2fcc2e4ac99a170088c205304", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.0.5", + "_shasum": "8c9b212898d8cd9f1a9436650ce7be202c9e9ff0", + "_from": "ee-first@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "8c9b212898d8cd9f1a9436650ce7be202c9e9ff0", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.0.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/node_modules/on-finished/package.json b/node_modules/morgan/node_modules/on-finished/package.json new file mode 100644 index 000000000..b842572e9 --- /dev/null +++ b/node_modules/morgan/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/jshttp/on-finished" + }, + "dependencies": { + "ee-first": "1.0.5" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.21.4" + }, + "engine": { + "node": ">= 0.8.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "1ad808e704e2aeda3a7464b78cacead2fb453727", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.1.0", + "_shasum": "0c539f09291e8ffadde0c8a25850fb2cedc7022d", + "_from": "on-finished@2.1.0", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "0c539f09291e8ffadde0c8a25850fb2cedc7022d", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/morgan/package.json b/node_modules/morgan/package.json new file mode 100644 index 000000000..93ccbd0f5 --- /dev/null +++ b/node_modules/morgan/package.json @@ -0,0 +1,87 @@ +{ + "name": "morgan", + "description": "http request logger middleware for node.js", + "version": "1.2.3", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/expressjs/morgan" + }, + "dependencies": { + "basic-auth": "1.0.0", + "bytes": "1.0.0", + "depd": "0.4.4", + "on-finished": "2.1.0" + }, + "devDependencies": { + "istanbul": "0.3.0", + "mocha": "~1.21.0", + "should": "~4.0.4", + "supertest": "~0.13.0" + }, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec" + }, + "gitHead": "733e01ec43b0b25c1a2b6bd1a6d3e5ca845ac95a", + "bugs": { + "url": "https://github.com/expressjs/morgan/issues" + }, + "homepage": "https://github.com/expressjs/morgan", + "_id": "morgan@1.2.3", + "_shasum": "3b0f1704df90255a542591abacd797891a8c40a1", + "_from": "morgan@^1.0.0", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "3b0f1704df90255a542591abacd797891a8c40a1", + "tarball": "http://registry.npmjs.org/morgan/-/morgan-1.2.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/morgan/-/morgan-1.2.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/package.json b/package.json index 4b627f3e8..6860e5dc0 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,10 @@ "private": true, "dependencies": { "body-parser": "^1.0.2", - "error-handler": "^0.1.4", "express": "~4.1.1", + "express-error-handler": "^0.5.4", "jade": "~0.31.2", + "less-middleware": "^1.0.4", "method-override": "^1.0.0", "morgan": "^1.0.0" } diff --git a/public/css/app.css b/public/css/app.css index c92524070..a0a2ff270 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -1,30 +1 @@ -/* app css stylesheet */ - -.menu { - list-style: none; - border-bottom: 0.1em solid black; - margin-bottom: 2em; - padding: 0 0 0.5em; -} - -.menu:before { - content: "["; -} - -.menu:after { - content: "]"; -} - -.menu > li { - display: inline; -} - -.menu > li:before { - content: "|"; - padding-right: 0.3em; -} - -.menu > li:nth-child(1):before { - content: ""; - padding: 0; -} +*{padding:0;margin:0}#wrapper{width:100%} \ No newline at end of file diff --git a/public/css/app.less b/public/css/app.less new file mode 100644 index 000000000..2586ceeb9 --- /dev/null +++ b/public/css/app.less @@ -0,0 +1,16 @@ +/* Overrides */ +* { + padding: 0; + margin: 0; +} +body { + +} +/* Classes */ + + +/* DIVs */ + +#wrapper { + width: 100%; +} \ No newline at end of file diff --git a/public/js/app.js b/public/js/app.js index e8c895486..e2929b897 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -7,20 +7,55 @@ angular.module('myApp', [ 'myApp.filters', 'myApp.services', 'myApp.directives' -]). -config(function ($routeProvider, $locationProvider) { - $routeProvider. - when('/view1', { - templateUrl: 'partials/partial1', - controller: 'MyCtrl1' - }). - when('/view2', { - templateUrl: 'partials/partial2', - controller: 'MyCtrl2' - }). - otherwise({ - redirectTo: '/view1' - }); - - $locationProvider.html5Mode(true); -}); +]); + +/*** Controllers ***/ + +angular.module('myApp.controllers', []). + controller('AppCtrl', function ($scope, $http) { + + $http({ + method: 'GET', + url: '/api/name' + }). + success(function (data, status, headers, config) { + $scope.name = data.name; + }). + error(function (data, status, headers, config) { + $scope.name = 'Error!'; + }); + + }). + controller('MyCtrl1', function ($scope) { + // write Ctrl here + + }). + controller('MyCtrl2', function ($scope) { + // write Ctrl here + + }); + +/*** Directives ***/ + +angular.module('myApp.directives', []). + directive('appVersion', function (version) { + return function(scope, elm, attrs) { + elm.text(version); + }; + }); + +/*** Filters ***/ + +angular.module('myApp.filters', []). + filter('interpolate', function (version) { + return function (text) { + return String(text).replace(/\%VERSION\%/mg, version); + }; + }); + +/*** Services ***/ + +// Demonstrate how to register services +// In this case it is a simple value service. +angular.module('myApp.services', []). + value('version', '0.1'); diff --git a/public/js/lib/angular/angular-animate.js b/public/js/lib/angular/angular-animate.js new file mode 100644 index 000000000..74a80f6ed --- /dev/null +++ b/public/js/lib/angular/angular-animate.js @@ -0,0 +1,1689 @@ +/** + * @license AngularJS v1.2.22 + * (c) 2010-2014 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular, undefined) {'use strict'; + +/* jshint maxlen: false */ + +/** + * @ngdoc module + * @name ngAnimate + * @description + * + * # ngAnimate + * + * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. + * + * + *
    + * + * # Usage + * + * To see animations in action, all that is required is to define the appropriate CSS classes + * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: + * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation + * by using the `$animate` service. + * + * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: + * + * | Directive | Supported Animations | + * |---------------------------------------------------------- |----------------------------------------------------| + * | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move | + * | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave | + * | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave | + * | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave | + * | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave | + * | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove | + * | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) | + * | {@link ng.directive:form#usage_animations form} | add and remove (dirty, pristine, valid, invalid & all other validations) | + * | {@link ng.directive:ngModel#usage_animations ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | + * + * You can find out more information about animations upon visiting each directive page. + * + * Below is an example of how to apply animations to a directive that supports animation hooks: + * + * ```html + * + * + * + * + * ``` + * + * Keep in mind that, by default, if an animation is running, any child elements cannot be animated + * until the parent element's animation has completed. This blocking feature can be overridden by + * placing the `ng-animate-children` attribute on a parent container tag. + * + * ```html + *
    + *
    + *
    + * ... + *
    + *
    + *
    + * ``` + * + * When the `on` expression value changes and an animation is triggered then each of the elements within + * will all animate without the block being applied to child elements. + * + *

    CSS-defined Animations

    + * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes + * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported + * and can be used to play along with this naming structure. + * + * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: + * + * ```html + * + * + *
    + *
    + *
    + * ``` + * + * The following code below demonstrates how to perform animations using **CSS animations** with Angular: + * + * ```html + * + * + *
    + *
    + *
    + * ``` + * + * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. + * + * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add + * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically + * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be + * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end + * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element + * has no CSS transition/animation classes applied to it. + * + *

    CSS Staggering Animations

    + * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a + * curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be + * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for + * the animation. The style property expected within the stagger class can either be a **transition-delay** or an + * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). + * + * ```css + * .my-animation.ng-enter { + * /* standard transition code */ + * -webkit-transition: 1s linear all; + * transition: 1s linear all; + * opacity:0; + * } + * .my-animation.ng-enter-stagger { + * /* this will have a 100ms delay between each successive leave animation */ + * -webkit-transition-delay: 0.1s; + * transition-delay: 0.1s; + * + * /* in case the stagger doesn't work then these two values + * must be set to 0 to avoid an accidental CSS inheritance */ + * -webkit-transition-duration: 0s; + * transition-duration: 0s; + * } + * .my-animation.ng-enter.ng-enter-active { + * /* standard transition styles */ + * opacity:1; + * } + * ``` + * + * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations + * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this + * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation + * will also be reset if more than 10ms has passed after the last animation has been fired. + * + * The following code will issue the **ng-leave-stagger** event on the element provided: + * + * ```js + * var kids = parent.children(); + * + * $animate.leave(kids[0]); //stagger index=0 + * $animate.leave(kids[1]); //stagger index=1 + * $animate.leave(kids[2]); //stagger index=2 + * $animate.leave(kids[3]); //stagger index=3 + * $animate.leave(kids[4]); //stagger index=4 + * + * $timeout(function() { + * //stagger has reset itself + * $animate.leave(kids[5]); //stagger index=0 + * $animate.leave(kids[6]); //stagger index=1 + * }, 100, false); + * ``` + * + * Stagger animations are currently only supported within CSS-defined animations. + * + *

    JavaScript-defined Animations

    + * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not + * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. + * + * ```js + * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. + * var ngModule = angular.module('YourApp', ['ngAnimate']); + * ngModule.animation('.my-crazy-animation', function() { + * return { + * enter: function(element, done) { + * //run the animation here and call done when the animation is complete + * return function(cancelled) { + * //this (optional) function will be called when the animation + * //completes or when the animation is cancelled (the cancelled + * //flag will be set to true if cancelled). + * }; + * }, + * leave: function(element, done) { }, + * move: function(element, done) { }, + * + * //animation that can be triggered before the class is added + * beforeAddClass: function(element, className, done) { }, + * + * //animation that can be triggered after the class is added + * addClass: function(element, className, done) { }, + * + * //animation that can be triggered before the class is removed + * beforeRemoveClass: function(element, className, done) { }, + * + * //animation that can be triggered after the class is removed + * removeClass: function(element, className, done) { } + * }; + * }); + * ``` + * + * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run + * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits + * the element's CSS class attribute value and then run the matching animation event function (if found). + * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will + * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). + * + * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. + * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, + * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation + * or transition code that is defined via a stylesheet). + * + */ + +angular.module('ngAnimate', ['ng']) + + /** + * @ngdoc provider + * @name $animateProvider + * @description + * + * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. + * When an animation is triggered, the $animate service will query the $animate service to find any animations that match + * the provided name value. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * + */ + .directive('ngAnimateChildren', function() { + var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; + return function(scope, element, attrs) { + var val = attrs.ngAnimateChildren; + if(angular.isString(val) && val.length === 0) { //empty attribute + element.data(NG_ANIMATE_CHILDREN, true); + } else { + scope.$watch(val, function(value) { + element.data(NG_ANIMATE_CHILDREN, !!value); + }); + } + }; + }) + + //this private service is only used within CSS-enabled animations + //IE8 + IE9 do not support rAF natively, but that is fine since they + //also don't support transitions and keyframes which means that the code + //below will never be used by the two browsers. + .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) { + var bod = $document[0].body; + return function(fn) { + //the returned function acts as the cancellation function + return $$rAF(function() { + //the line below will force the browser to perform a repaint + //so that all the animated elements within the animation frame + //will be properly updated and drawn on screen. This is + //required to perform multi-class CSS based animations with + //Firefox. DO NOT REMOVE THIS LINE. + var a = bod.offsetWidth + 1; + fn(); + }); + }; + }]) + + .config(['$provide', '$animateProvider', function($provide, $animateProvider) { + var noop = angular.noop; + var forEach = angular.forEach; + var selectors = $animateProvider.$$selectors; + + var ELEMENT_NODE = 1; + var NG_ANIMATE_STATE = '$$ngAnimateState'; + var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; + var NG_ANIMATE_CLASS_NAME = 'ng-animate'; + var rootAnimateState = {running: true}; + + function extractElementNode(element) { + for(var i = 0; i < element.length; i++) { + var elm = element[i]; + if(elm.nodeType == ELEMENT_NODE) { + return elm; + } + } + } + + function prepareElement(element) { + return element && angular.element(element); + } + + function stripCommentsFromElement(element) { + return angular.element(extractElementNode(element)); + } + + function isMatchingElement(elm1, elm2) { + return extractElementNode(elm1) == extractElementNode(elm2); + } + + $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', + function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) { + + var globalAnimationCounter = 0; + $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); + + // disable animations during bootstrap, but once we bootstrapped, wait again + // for another digest until enabling animations. The reason why we digest twice + // is because all structural animations (enter, leave and move) all perform a + // post digest operation before animating. If we only wait for a single digest + // to pass then the structural animation would render its animation on page load. + // (which is what we're trying to avoid when the application first boots up.) + $rootScope.$$postDigest(function() { + $rootScope.$$postDigest(function() { + rootAnimateState.running = false; + }); + }); + + var classNameFilter = $animateProvider.classNameFilter(); + var isAnimatableClassName = !classNameFilter + ? function() { return true; } + : function(className) { + return classNameFilter.test(className); + }; + + function blockElementAnimations(element) { + var data = element.data(NG_ANIMATE_STATE) || {}; + data.running = true; + element.data(NG_ANIMATE_STATE, data); + } + + function lookup(name) { + if (name) { + var matches = [], + flagMap = {}, + classes = name.substr(1).split('.'); + + //the empty string value is the default animation + //operation which performs CSS transition and keyframe + //animations sniffing. This is always included for each + //element animation procedure if the browser supports + //transitions and/or keyframe animations. The default + //animation is added to the top of the list to prevent + //any previous animations from affecting the element styling + //prior to the element being animated. + if ($sniffer.transitions || $sniffer.animations) { + matches.push($injector.get(selectors[''])); + } + + for(var i=0; i < classes.length; i++) { + var klass = classes[i], + selectorFactoryName = selectors[klass]; + if(selectorFactoryName && !flagMap[klass]) { + matches.push($injector.get(selectorFactoryName)); + flagMap[klass] = true; + } + } + return matches; + } + } + + function animationRunner(element, animationEvent, className) { + //transcluded directives may sometimes fire an animation using only comment nodes + //best to catch this early on to prevent any animation operations from occurring + var node = element[0]; + if(!node) { + return; + } + + var isSetClassOperation = animationEvent == 'setClass'; + var isClassBased = isSetClassOperation || + animationEvent == 'addClass' || + animationEvent == 'removeClass'; + + var classNameAdd, classNameRemove; + if(angular.isArray(className)) { + classNameAdd = className[0]; + classNameRemove = className[1]; + className = classNameAdd + ' ' + classNameRemove; + } + + var currentClassName = element.attr('class'); + var classes = currentClassName + ' ' + className; + if(!isAnimatableClassName(classes)) { + return; + } + + var beforeComplete = noop, + beforeCancel = [], + before = [], + afterComplete = noop, + afterCancel = [], + after = []; + + var animationLookup = (' ' + classes).replace(/\s+/g,'.'); + forEach(lookup(animationLookup), function(animationFactory) { + var created = registerAnimation(animationFactory, animationEvent); + if(!created && isSetClassOperation) { + registerAnimation(animationFactory, 'addClass'); + registerAnimation(animationFactory, 'removeClass'); + } + }); + + function registerAnimation(animationFactory, event) { + var afterFn = animationFactory[event]; + var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; + if(afterFn || beforeFn) { + if(event == 'leave') { + beforeFn = afterFn; + //when set as null then animation knows to skip this phase + afterFn = null; + } + after.push({ + event : event, fn : afterFn + }); + before.push({ + event : event, fn : beforeFn + }); + return true; + } + } + + function run(fns, cancellations, allCompleteFn) { + var animations = []; + forEach(fns, function(animation) { + animation.fn && animations.push(animation); + }); + + var count = 0; + function afterAnimationComplete(index) { + if(cancellations) { + (cancellations[index] || noop)(); + if(++count < animations.length) return; + cancellations = null; + } + allCompleteFn(); + } + + //The code below adds directly to the array in order to work with + //both sync and async animations. Sync animations are when the done() + //operation is called right away. DO NOT REFACTOR! + forEach(animations, function(animation, index) { + var progress = function() { + afterAnimationComplete(index); + }; + switch(animation.event) { + case 'setClass': + cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress)); + break; + case 'addClass': + cancellations.push(animation.fn(element, classNameAdd || className, progress)); + break; + case 'removeClass': + cancellations.push(animation.fn(element, classNameRemove || className, progress)); + break; + default: + cancellations.push(animation.fn(element, progress)); + break; + } + }); + + if(cancellations && cancellations.length === 0) { + allCompleteFn(); + } + } + + return { + node : node, + event : animationEvent, + className : className, + isClassBased : isClassBased, + isSetClassOperation : isSetClassOperation, + before : function(allCompleteFn) { + beforeComplete = allCompleteFn; + run(before, beforeCancel, function() { + beforeComplete = noop; + allCompleteFn(); + }); + }, + after : function(allCompleteFn) { + afterComplete = allCompleteFn; + run(after, afterCancel, function() { + afterComplete = noop; + allCompleteFn(); + }); + }, + cancel : function() { + if(beforeCancel) { + forEach(beforeCancel, function(cancelFn) { + (cancelFn || noop)(true); + }); + beforeComplete(true); + } + if(afterCancel) { + forEach(afterCancel, function(cancelFn) { + (cancelFn || noop)(true); + }); + afterComplete(true); + } + } + }; + } + + /** + * @ngdoc service + * @name $animate + * @kind function + * + * @description + * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. + * When any of these operations are run, the $animate service + * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) + * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. + * + * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives + * will work out of the box without any extra configuration. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * + */ + return { + /** + * @ngdoc method + * @name $animate#enter + * @kind function + * + * @description + * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once + * the animation is started, the following CSS classes will be present on the element for the duration of the animation: + * + * Below is a breakdown of each step that occurs during enter animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.enter(...) is called | class="my-animation" | + * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | + * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | + * | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | + * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | + * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | + * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | + * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | + * + * @param {DOMElement} element the element that will be the focus of the enter animation + * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation + * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation + * @param {function()=} doneCallback the callback function that will be called once the animation is complete + */ + enter : function(element, parentElement, afterElement, doneCallback) { + element = angular.element(element); + parentElement = prepareElement(parentElement); + afterElement = prepareElement(afterElement); + + blockElementAnimations(element); + $delegate.enter(element, parentElement, afterElement); + $rootScope.$$postDigest(function() { + element = stripCommentsFromElement(element); + performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback); + }); + }, + + /** + * @ngdoc method + * @name $animate#leave + * @kind function + * + * @description + * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during leave animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.leave(...) is called | class="my-animation" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | + * | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | + * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | + * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | + * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 9. The element is removed from the DOM | ... | + * | 10. The doneCallback() callback is fired (if provided) | ... | + * + * @param {DOMElement} element the element that will be the focus of the leave animation + * @param {function()=} doneCallback the callback function that will be called once the animation is complete + */ + leave : function(element, doneCallback) { + element = angular.element(element); + cancelChildAnimations(element); + blockElementAnimations(element); + $rootScope.$$postDigest(function() { + performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() { + $delegate.leave(element); + }, doneCallback); + }); + }, + + /** + * @ngdoc method + * @name $animate#move + * @kind function + * + * @description + * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or + * add the element directly after the afterElement element if present. Then the move animation will be run. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during move animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.move(...) is called | class="my-animation" | + * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | + * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | + * | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | + * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | + * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | + * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | + * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | + * + * @param {DOMElement} element the element that will be the focus of the move animation + * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation + * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation + * @param {function()=} doneCallback the callback function that will be called once the animation is complete + */ + move : function(element, parentElement, afterElement, doneCallback) { + element = angular.element(element); + parentElement = prepareElement(parentElement); + afterElement = prepareElement(afterElement); + + cancelChildAnimations(element); + blockElementAnimations(element); + $delegate.move(element, parentElement, afterElement); + $rootScope.$$postDigest(function() { + element = stripCommentsFromElement(element); + performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback); + }); + }, + + /** + * @ngdoc method + * @name $animate#addClass + * + * @description + * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. + * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide + * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions + * or keyframes are defined on the -add or base CSS class). + * + * Below is a breakdown of each step that occurs during addClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |------------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | + * | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | + * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | + * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | + * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super super-add super-add-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | + * | 9. The super class is kept on the element | class="my-animation super" | + * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | + * + * @param {DOMElement} element the element that will be animated + * @param {string} className the CSS class that will be added to the element and then animated + * @param {function()=} doneCallback the callback function that will be called once the animation is complete + */ + addClass : function(element, className, doneCallback) { + element = angular.element(element); + element = stripCommentsFromElement(element); + performAnimation('addClass', className, element, null, null, function() { + $delegate.addClass(element, className); + }, doneCallback); + }, + + /** + * @ngdoc method + * @name $animate#removeClass + * + * @description + * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value + * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in + * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if + * no CSS transitions or keyframes are defined on the -remove or base CSS classes). + * + * Below is a breakdown of each step that occurs during removeClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |-----------------------------------------------------------------------------------------------|---------------------------------------------| + * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | + * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | + * | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| + * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | + * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | + * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | + * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | + * + * + * @param {DOMElement} element the element that will be animated + * @param {string} className the CSS class that will be animated and then removed from the element + * @param {function()=} doneCallback the callback function that will be called once the animation is complete + */ + removeClass : function(element, className, doneCallback) { + element = angular.element(element); + element = stripCommentsFromElement(element); + performAnimation('removeClass', className, element, null, null, function() { + $delegate.removeClass(element, className); + }, doneCallback); + }, + + /** + * + * @ngdoc function + * @name $animate#setClass + * @function + * @description Adds and/or removes the given CSS classes to and from the element. + * Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will its CSS classes changed + * removed from it + * @param {string} add the CSS classes which will be added to the element + * @param {string} remove the CSS class which will be removed from the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * CSS classes have been set on the element + */ + setClass : function(element, add, remove, doneCallback) { + element = angular.element(element); + element = stripCommentsFromElement(element); + performAnimation('setClass', [add, remove], element, null, null, function() { + $delegate.setClass(element, add, remove); + }, doneCallback); + }, + + /** + * @ngdoc method + * @name $animate#enabled + * @kind function + * + * @param {boolean=} value If provided then set the animation on or off. + * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation + * @return {boolean} Current animation state. + * + * @description + * Globally enables/disables animations. + * + */ + enabled : function(value, element) { + switch(arguments.length) { + case 2: + if(value) { + cleanup(element); + } else { + var data = element.data(NG_ANIMATE_STATE) || {}; + data.disabled = true; + element.data(NG_ANIMATE_STATE, data); + } + break; + + case 1: + rootAnimateState.disabled = !value; + break; + + default: + value = !rootAnimateState.disabled; + break; + } + return !!value; + } + }; + + /* + all animations call this shared animation triggering function internally. + The animationEvent variable refers to the JavaScript animation event that will be triggered + and the className value is the name of the animation that will be applied within the + CSS code. Element, parentElement and afterElement are provided DOM elements for the animation + and the onComplete callback will be fired once the animation is fully complete. + */ + function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { + + var runner = animationRunner(element, animationEvent, className); + if(!runner) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + closeAnimation(); + return; + } + + className = runner.className; + var elementEvents = angular.element._data(runner.node); + elementEvents = elementEvents && elementEvents.events; + + if (!parentElement) { + parentElement = afterElement ? afterElement.parent() : element.parent(); + } + + var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; + var runningAnimations = ngAnimateState.active || {}; + var totalActiveAnimations = ngAnimateState.totalActive || 0; + var lastAnimation = ngAnimateState.last; + + //only allow animations if the currently running animation is not structural + //or if there is no animation running at all + var skipAnimations; + if (runner.isClassBased) { + skipAnimations = ngAnimateState.running || + ngAnimateState.disabled || + (lastAnimation && !lastAnimation.isClassBased); + } + + //skip the animation if animations are disabled, a parent is already being animated, + //the element is not currently attached to the document body or then completely close + //the animation if any matching animations are not found at all. + //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. + if (skipAnimations || animationsDisabled(element, parentElement)) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + closeAnimation(); + return; + } + + var skipAnimation = false; + if(totalActiveAnimations > 0) { + var animationsToCancel = []; + if(!runner.isClassBased) { + if(animationEvent == 'leave' && runningAnimations['ng-leave']) { + skipAnimation = true; + } else { + //cancel all animations when a structural animation takes place + for(var klass in runningAnimations) { + animationsToCancel.push(runningAnimations[klass]); + cleanup(element, klass); + } + runningAnimations = {}; + totalActiveAnimations = 0; + } + } else if(lastAnimation.event == 'setClass') { + animationsToCancel.push(lastAnimation); + cleanup(element, className); + } + else if(runningAnimations[className]) { + var current = runningAnimations[className]; + if(current.event == animationEvent) { + skipAnimation = true; + } else { + animationsToCancel.push(current); + cleanup(element, className); + } + } + + if(animationsToCancel.length > 0) { + forEach(animationsToCancel, function(operation) { + operation.cancel(); + }); + } + } + + if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) { + skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR + } + + if(skipAnimation) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + fireDoneCallbackAsync(); + return; + } + + if(animationEvent == 'leave') { + //there's no need to ever remove the listener since the element + //will be removed (destroyed) after the leave animation ends or + //is cancelled midway + element.one('$destroy', function(e) { + var element = angular.element(this); + var state = element.data(NG_ANIMATE_STATE); + if(state) { + var activeLeaveAnimation = state.active['ng-leave']; + if(activeLeaveAnimation) { + activeLeaveAnimation.cancel(); + cleanup(element, 'ng-leave'); + } + } + }); + } + + //the ng-animate class does nothing, but it's here to allow for + //parent animations to find and cancel child animations when needed + element.addClass(NG_ANIMATE_CLASS_NAME); + + var localAnimationCount = globalAnimationCounter++; + totalActiveAnimations++; + runningAnimations[className] = runner; + + element.data(NG_ANIMATE_STATE, { + last : runner, + active : runningAnimations, + index : localAnimationCount, + totalActive : totalActiveAnimations + }); + + //first we run the before animations and when all of those are complete + //then we perform the DOM operation and run the next set of animations + fireBeforeCallbackAsync(); + runner.before(function(cancelled) { + var data = element.data(NG_ANIMATE_STATE); + cancelled = cancelled || + !data || !data.active[className] || + (runner.isClassBased && data.active[className].event != animationEvent); + + fireDOMOperation(); + if(cancelled === true) { + closeAnimation(); + } else { + fireAfterCallbackAsync(); + runner.after(closeAnimation); + } + }); + + function fireDOMCallback(animationPhase) { + var eventName = '$animate:' + animationPhase; + if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { + $$asyncCallback(function() { + element.triggerHandler(eventName, { + event : animationEvent, + className : className + }); + }); + } + } + + function fireBeforeCallbackAsync() { + fireDOMCallback('before'); + } + + function fireAfterCallbackAsync() { + fireDOMCallback('after'); + } + + function fireDoneCallbackAsync() { + fireDOMCallback('close'); + if(doneCallback) { + $$asyncCallback(function() { + doneCallback(); + }); + } + } + + //it is less complicated to use a flag than managing and canceling + //timeouts containing multiple callbacks. + function fireDOMOperation() { + if(!fireDOMOperation.hasBeenRun) { + fireDOMOperation.hasBeenRun = true; + domOperation(); + } + } + + function closeAnimation() { + if(!closeAnimation.hasBeenRun) { + closeAnimation.hasBeenRun = true; + var data = element.data(NG_ANIMATE_STATE); + if(data) { + /* only structural animations wait for reflow before removing an + animation, but class-based animations don't. An example of this + failing would be when a parent HTML tag has a ng-class attribute + causing ALL directives below to skip animations during the digest */ + if(runner && runner.isClassBased) { + cleanup(element, className); + } else { + $$asyncCallback(function() { + var data = element.data(NG_ANIMATE_STATE) || {}; + if(localAnimationCount == data.index) { + cleanup(element, className, animationEvent); + } + }); + element.data(NG_ANIMATE_STATE, data); + } + } + fireDoneCallbackAsync(); + } + } + } + + function cancelChildAnimations(element) { + var node = extractElementNode(element); + if (node) { + var nodes = angular.isFunction(node.getElementsByClassName) ? + node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : + node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); + forEach(nodes, function(element) { + element = angular.element(element); + var data = element.data(NG_ANIMATE_STATE); + if(data && data.active) { + forEach(data.active, function(runner) { + runner.cancel(); + }); + } + }); + } + } + + function cleanup(element, className) { + if(isMatchingElement(element, $rootElement)) { + if(!rootAnimateState.disabled) { + rootAnimateState.running = false; + rootAnimateState.structural = false; + } + } else if(className) { + var data = element.data(NG_ANIMATE_STATE) || {}; + + var removeAnimations = className === true; + if(!removeAnimations && data.active && data.active[className]) { + data.totalActive--; + delete data.active[className]; + } + + if(removeAnimations || !data.totalActive) { + element.removeClass(NG_ANIMATE_CLASS_NAME); + element.removeData(NG_ANIMATE_STATE); + } + } + } + + function animationsDisabled(element, parentElement) { + if (rootAnimateState.disabled) { + return true; + } + + if (isMatchingElement(element, $rootElement)) { + return rootAnimateState.running; + } + + var allowChildAnimations, parentRunningAnimation, hasParent; + do { + //the element did not reach the root element which means that it + //is not apart of the DOM. Therefore there is no reason to do + //any animations on it + if (parentElement.length === 0) break; + + var isRoot = isMatchingElement(parentElement, $rootElement); + var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {}); + if (state.disabled) { + return true; + } + + //no matter what, for an animation to work it must reach the root element + //this implies that the element is attached to the DOM when the animation is run + if (isRoot) { + hasParent = true; + } + + //once a flag is found that is strictly false then everything before + //it will be discarded and all child animations will be restricted + if (allowChildAnimations !== false) { + var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN); + if(angular.isDefined(animateChildrenFlag)) { + allowChildAnimations = animateChildrenFlag; + } + } + + parentRunningAnimation = parentRunningAnimation || + state.running || + (state.last && !state.last.isClassBased); + } + while(parentElement = parentElement.parent()); + + return !hasParent || (!allowChildAnimations && parentRunningAnimation); + } + }]); + + $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', + function($window, $sniffer, $timeout, $$animateReflow) { + // Detect proper transitionend/animationend event names. + var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; + + // If unprefixed events are not supported but webkit-prefixed are, use the latter. + // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. + // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` + // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. + // Register both events in case `window.onanimationend` is not supported because of that, + // do the same for `transitionend` as Safari is likely to exhibit similar behavior. + // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit + // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition + if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { + CSS_PREFIX = '-webkit-'; + TRANSITION_PROP = 'WebkitTransition'; + TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; + } else { + TRANSITION_PROP = 'transition'; + TRANSITIONEND_EVENT = 'transitionend'; + } + + if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { + CSS_PREFIX = '-webkit-'; + ANIMATION_PROP = 'WebkitAnimation'; + ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; + } else { + ANIMATION_PROP = 'animation'; + ANIMATIONEND_EVENT = 'animationend'; + } + + var DURATION_KEY = 'Duration'; + var PROPERTY_KEY = 'Property'; + var DELAY_KEY = 'Delay'; + var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; + var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; + var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; + var NG_ANIMATE_BLOCK_CLASS_NAME = 'ng-animate-block-transitions'; + var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; + var CLOSING_TIME_BUFFER = 1.5; + var ONE_SECOND = 1000; + + var lookupCache = {}; + var parentCounter = 0; + var animationReflowQueue = []; + var cancelAnimationReflow; + function afterReflow(element, callback) { + if(cancelAnimationReflow) { + cancelAnimationReflow(); + } + animationReflowQueue.push(callback); + cancelAnimationReflow = $$animateReflow(function() { + forEach(animationReflowQueue, function(fn) { + fn(); + }); + + animationReflowQueue = []; + cancelAnimationReflow = null; + lookupCache = {}; + }); + } + + var closingTimer = null; + var closingTimestamp = 0; + var animationElementQueue = []; + function animationCloseHandler(element, totalTime) { + var node = extractElementNode(element); + element = angular.element(node); + + //this item will be garbage collected by the closing + //animation timeout + animationElementQueue.push(element); + + //but it may not need to cancel out the existing timeout + //if the timestamp is less than the previous one + var futureTimestamp = Date.now() + totalTime; + if(futureTimestamp <= closingTimestamp) { + return; + } + + $timeout.cancel(closingTimer); + + closingTimestamp = futureTimestamp; + closingTimer = $timeout(function() { + closeAllAnimations(animationElementQueue); + animationElementQueue = []; + }, totalTime, false); + } + + function closeAllAnimations(elements) { + forEach(elements, function(element) { + var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); + if(elementData) { + (elementData.closeAnimationFn || noop)(); + } + }); + } + + function getElementAnimationDetails(element, cacheKey) { + var data = cacheKey ? lookupCache[cacheKey] : null; + if(!data) { + var transitionDuration = 0; + var transitionDelay = 0; + var animationDuration = 0; + var animationDelay = 0; + var transitionDelayStyle; + var animationDelayStyle; + var transitionDurationStyle; + var transitionPropertyStyle; + + //we want all the styles defined before and after + forEach(element, function(element) { + if (element.nodeType == ELEMENT_NODE) { + var elementStyles = $window.getComputedStyle(element) || {}; + + transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; + + transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); + + transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; + + transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; + + transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); + + animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; + + animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); + + var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); + + if(aDuration > 0) { + aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; + } + + animationDuration = Math.max(aDuration, animationDuration); + } + }); + data = { + total : 0, + transitionPropertyStyle: transitionPropertyStyle, + transitionDurationStyle: transitionDurationStyle, + transitionDelayStyle: transitionDelayStyle, + transitionDelay: transitionDelay, + transitionDuration: transitionDuration, + animationDelayStyle: animationDelayStyle, + animationDelay: animationDelay, + animationDuration: animationDuration + }; + if(cacheKey) { + lookupCache[cacheKey] = data; + } + } + return data; + } + + function parseMaxTime(str) { + var maxValue = 0; + var values = angular.isString(str) ? + str.split(/\s*,\s*/) : + []; + forEach(values, function(value) { + maxValue = Math.max(parseFloat(value) || 0, maxValue); + }); + return maxValue; + } + + function getCacheKey(element) { + var parentElement = element.parent(); + var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); + if(!parentID) { + parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); + parentID = parentCounter; + } + return parentID + '-' + extractElementNode(element).getAttribute('class'); + } + + function animateSetup(animationEvent, element, className, calculationDecorator) { + var cacheKey = getCacheKey(element); + var eventCacheKey = cacheKey + ' ' + className; + var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; + + var stagger = {}; + if(itemIndex > 0) { + var staggerClassName = className + '-stagger'; + var staggerCacheKey = cacheKey + ' ' + staggerClassName; + var applyClasses = !lookupCache[staggerCacheKey]; + + applyClasses && element.addClass(staggerClassName); + + stagger = getElementAnimationDetails(element, staggerCacheKey); + + applyClasses && element.removeClass(staggerClassName); + } + + /* the animation itself may need to add/remove special CSS classes + * before calculating the anmation styles */ + calculationDecorator = calculationDecorator || + function(fn) { return fn(); }; + + element.addClass(className); + + var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; + + var timings = calculationDecorator(function() { + return getElementAnimationDetails(element, eventCacheKey); + }); + + var transitionDuration = timings.transitionDuration; + var animationDuration = timings.animationDuration; + if(transitionDuration === 0 && animationDuration === 0) { + element.removeClass(className); + return false; + } + + element.data(NG_ANIMATE_CSS_DATA_KEY, { + running : formerData.running || 0, + itemIndex : itemIndex, + stagger : stagger, + timings : timings, + closeAnimationFn : noop + }); + + //temporarily disable the transition so that the enter styles + //don't animate twice (this is here to avoid a bug in Chrome/FF). + var isCurrentlyAnimating = formerData.running > 0 || animationEvent == 'setClass'; + if(transitionDuration > 0) { + blockTransitions(element, className, isCurrentlyAnimating); + } + + //staggering keyframe animations work by adjusting the `animation-delay` CSS property + //on the given element, however, the delay value can only calculated after the reflow + //since by that time $animate knows how many elements are being animated. Therefore, + //until the reflow occurs the element needs to be blocked (where the keyframe animation + //is set to `none 0s`). This blocking mechanism should only be set for when a stagger + //animation is detected and when the element item index is greater than 0. + if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) { + blockKeyframeAnimations(element); + } + + return true; + } + + function isStructuralAnimation(className) { + return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave'; + } + + function blockTransitions(element, className, isAnimating) { + if(isStructuralAnimation(className) || !isAnimating) { + extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; + } else { + element.addClass(NG_ANIMATE_BLOCK_CLASS_NAME); + } + } + + function blockKeyframeAnimations(element) { + extractElementNode(element).style[ANIMATION_PROP] = 'none 0s'; + } + + function unblockTransitions(element, className) { + var prop = TRANSITION_PROP + PROPERTY_KEY; + var node = extractElementNode(element); + if(node.style[prop] && node.style[prop].length > 0) { + node.style[prop] = ''; + } + element.removeClass(NG_ANIMATE_BLOCK_CLASS_NAME); + } + + function unblockKeyframeAnimations(element) { + var prop = ANIMATION_PROP; + var node = extractElementNode(element); + if(node.style[prop] && node.style[prop].length > 0) { + node.style[prop] = ''; + } + } + + function animateRun(animationEvent, element, className, activeAnimationComplete) { + var node = extractElementNode(element); + var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); + if(node.getAttribute('class').indexOf(className) == -1 || !elementData) { + activeAnimationComplete(); + return; + } + + var activeClassName = ''; + forEach(className.split(' '), function(klass, i) { + activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; + }); + + var stagger = elementData.stagger; + var timings = elementData.timings; + var itemIndex = elementData.itemIndex; + var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); + var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); + var maxDelayTime = maxDelay * ONE_SECOND; + + var startTime = Date.now(); + var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; + + var style = '', appliedStyles = []; + if(timings.transitionDuration > 0) { + var propertyStyle = timings.transitionPropertyStyle; + if(propertyStyle.indexOf('all') == -1) { + style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';'; + style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';'; + appliedStyles.push(CSS_PREFIX + 'transition-property'); + appliedStyles.push(CSS_PREFIX + 'transition-duration'); + } + } + + if(itemIndex > 0) { + if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { + var delayStyle = timings.transitionDelayStyle; + style += CSS_PREFIX + 'transition-delay: ' + + prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; '; + appliedStyles.push(CSS_PREFIX + 'transition-delay'); + } + + if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { + style += CSS_PREFIX + 'animation-delay: ' + + prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; '; + appliedStyles.push(CSS_PREFIX + 'animation-delay'); + } + } + + if(appliedStyles.length > 0) { + //the element being animated may sometimes contain comment nodes in + //the jqLite object, so we're safe to use a single variable to house + //the styles since there is always only one element being animated + var oldStyle = node.getAttribute('style') || ''; + node.setAttribute('style', oldStyle + '; ' + style); + } + + element.on(css3AnimationEvents, onAnimationProgress); + element.addClass(activeClassName); + elementData.closeAnimationFn = function() { + onEnd(); + activeAnimationComplete(); + }; + + var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0); + var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; + var totalTime = (staggerTime + animationTime) * ONE_SECOND; + + elementData.running++; + animationCloseHandler(element, totalTime); + return onEnd; + + // This will automatically be called by $animate so + // there is no need to attach this internally to the + // timeout done method. + function onEnd(cancelled) { + element.off(css3AnimationEvents, onAnimationProgress); + element.removeClass(activeClassName); + animateClose(element, className); + var node = extractElementNode(element); + for (var i in appliedStyles) { + node.style.removeProperty(appliedStyles[i]); + } + } + + function onAnimationProgress(event) { + event.stopPropagation(); + var ev = event.originalEvent || event; + var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); + + /* Firefox (or possibly just Gecko) likes to not round values up + * when a ms measurement is used for the animation */ + var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); + + /* $manualTimeStamp is a mocked timeStamp value which is set + * within browserTrigger(). This is only here so that tests can + * mock animations properly. Real events fallback to event.timeStamp, + * or, if they don't, then a timeStamp is automatically created for them. + * We're checking to see if the timeStamp surpasses the expected delay, + * but we're using elapsedTime instead of the timeStamp on the 2nd + * pre-condition since animations sometimes close off early */ + if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + activeAnimationComplete(); + } + } + } + + function prepareStaggerDelay(delayStyle, staggerDelay, index) { + var style = ''; + forEach(delayStyle.split(','), function(val, i) { + style += (i > 0 ? ',' : '') + + (index * staggerDelay + parseInt(val, 10)) + 's'; + }); + return style; + } + + function animateBefore(animationEvent, element, className, calculationDecorator) { + if(animateSetup(animationEvent, element, className, calculationDecorator)) { + return function(cancelled) { + cancelled && animateClose(element, className); + }; + } + } + + function animateAfter(animationEvent, element, className, afterAnimationComplete) { + if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { + return animateRun(animationEvent, element, className, afterAnimationComplete); + } else { + animateClose(element, className); + afterAnimationComplete(); + } + } + + function animate(animationEvent, element, className, animationComplete) { + //If the animateSetup function doesn't bother returning a + //cancellation function then it means that there is no animation + //to perform at all + var preReflowCancellation = animateBefore(animationEvent, element, className); + if(!preReflowCancellation) { + animationComplete(); + return; + } + + //There are two cancellation functions: one is before the first + //reflow animation and the second is during the active state + //animation. The first function will take care of removing the + //data from the element which will not make the 2nd animation + //happen in the first place + var cancel = preReflowCancellation; + afterReflow(element, function() { + unblockTransitions(element, className); + unblockKeyframeAnimations(element); + //once the reflow is complete then we point cancel to + //the new cancellation function which will remove all of the + //animation properties from the active animation + cancel = animateAfter(animationEvent, element, className, animationComplete); + }); + + return function(cancelled) { + (cancel || noop)(cancelled); + }; + } + + function animateClose(element, className) { + element.removeClass(className); + var data = element.data(NG_ANIMATE_CSS_DATA_KEY); + if(data) { + if(data.running) { + data.running--; + } + if(!data.running || data.running === 0) { + element.removeData(NG_ANIMATE_CSS_DATA_KEY); + } + } + } + + return { + enter : function(element, animationCompleted) { + return animate('enter', element, 'ng-enter', animationCompleted); + }, + + leave : function(element, animationCompleted) { + return animate('leave', element, 'ng-leave', animationCompleted); + }, + + move : function(element, animationCompleted) { + return animate('move', element, 'ng-move', animationCompleted); + }, + + beforeSetClass : function(element, add, remove, animationCompleted) { + var className = suffixClasses(remove, '-remove') + ' ' + + suffixClasses(add, '-add'); + var cancellationMethod = animateBefore('setClass', element, className, function(fn) { + /* when classes are removed from an element then the transition style + * that is applied is the transition defined on the element without the + * CSS class being there. This is how CSS3 functions outside of ngAnimate. + * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ + var klass = element.attr('class'); + element.removeClass(remove); + element.addClass(add); + var timings = fn(); + element.attr('class', klass); + return timings; + }); + + if(cancellationMethod) { + afterReflow(element, function() { + unblockTransitions(element, className); + unblockKeyframeAnimations(element); + animationCompleted(); + }); + return cancellationMethod; + } + animationCompleted(); + }, + + beforeAddClass : function(element, className, animationCompleted) { + var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) { + + /* when a CSS class is added to an element then the transition style that + * is applied is the transition defined on the element when the CSS class + * is added at the time of the animation. This is how CSS3 functions + * outside of ngAnimate. */ + element.addClass(className); + var timings = fn(); + element.removeClass(className); + return timings; + }); + + if(cancellationMethod) { + afterReflow(element, function() { + unblockTransitions(element, className); + unblockKeyframeAnimations(element); + animationCompleted(); + }); + return cancellationMethod; + } + animationCompleted(); + }, + + setClass : function(element, add, remove, animationCompleted) { + remove = suffixClasses(remove, '-remove'); + add = suffixClasses(add, '-add'); + var className = remove + ' ' + add; + return animateAfter('setClass', element, className, animationCompleted); + }, + + addClass : function(element, className, animationCompleted) { + return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted); + }, + + beforeRemoveClass : function(element, className, animationCompleted) { + var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) { + /* when classes are removed from an element then the transition style + * that is applied is the transition defined on the element without the + * CSS class being there. This is how CSS3 functions outside of ngAnimate. + * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ + var klass = element.attr('class'); + element.removeClass(className); + var timings = fn(); + element.attr('class', klass); + return timings; + }); + + if(cancellationMethod) { + afterReflow(element, function() { + unblockTransitions(element, className); + unblockKeyframeAnimations(element); + animationCompleted(); + }); + return cancellationMethod; + } + animationCompleted(); + }, + + removeClass : function(element, className, animationCompleted) { + return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted); + } + }; + + function suffixClasses(classes, suffix) { + var className = ''; + classes = angular.isArray(classes) ? classes : classes.split(/\s+/); + forEach(classes, function(klass, i) { + if(klass && klass.length > 0) { + className += (i > 0 ? ' ' : '') + klass + suffix; + } + }); + return className; + } + }]); + }]); + + +})(window, window.angular); diff --git a/public/js/lib/angular/angular-animate.min.js b/public/js/lib/angular/angular-animate.min.js new file mode 100644 index 000000000..bc8c7e96f --- /dev/null +++ b/public/js/lib/angular/angular-animate.min.js @@ -0,0 +1,28 @@ +/* + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(F,e,O){'use strict';e.module("ngAnimate",["ng"]).directive("ngAnimateChildren",function(){return function(G,s,g){g=g.ngAnimateChildren;e.isString(g)&&0===g.length?s.data("$$ngAnimateChildren",!0):G.$watch(g,function(e){s.data("$$ngAnimateChildren",!!e)})}}).factory("$$animateReflow",["$$rAF","$document",function(e,s){return function(g){return e(function(){g()})}}]).config(["$provide","$animateProvider",function(G,s){function g(e){for(var g=0;g=y&&b>=v&&e()}var h=g(b);a=b.data(q);if(-1!=h.getAttribute("class").indexOf(d)&&a){var m="";u(d.split(" "),function(a,b){m+=(0
    + * + * See {@link ngCookies.$cookies `$cookies`} and + * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** - * @ngdoc object - * @name ngCookies.$cookies - * @requires $browser + * @ngdoc service + * @name $cookies * * @description * Provides read/write access to browser's cookies. * - * Only a simple Object is exposed and by adding or removing properties to/from - * this object, new cookies are created/deleted at the end of current $eval. + * Only a simple Object is exposed and by adding or removing properties to/from this object, new + * cookies are created/deleted at the end of current $eval. + * The object's properties can only be strings. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example - - - - - + * + * ```js + * angular.module('cookiesExample', ['ngCookies']) + * .controller('ExampleController', ['$cookies', function($cookies) { + * // Retrieving a cookie + * var favoriteCookie = $cookies.myFavorite; + * // Setting a cookie + * $cookies.myFavorite = 'oatmeal'; + * }]); + * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, @@ -68,7 +78,8 @@ angular.module('ngCookies', ['ng']). /** - * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. + * Pushes all the cookies from the service to the browser and verifies if all cookies were + * stored. */ function push() { var name, @@ -87,12 +98,10 @@ angular.module('ngCookies', ['ng']). for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { - if (angular.isDefined(lastCookies[name])) { - cookies[name] = lastCookies[name]; - } else { - delete cookies[name]; - } - } else if (value !== lastCookies[name]) { + value = '' + value; + cookies[name] = value; + } + if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } @@ -120,23 +129,37 @@ angular.module('ngCookies', ['ng']). /** - * @ngdoc object - * @name ngCookies.$cookieStore + * @ngdoc service + * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * * @example + * + * ```js + * angular.module('cookieStoreExample', ['ngCookies']) + * .controller('ExampleController', ['$cookieStore', function($cookieStore) { + * // Put cookie + * $cookieStore.put('myFavorite','oatmeal'); + * // Get cookie + * var favoriteCookie = $cookieStore.get('myFavorite'); + * // Removing a cookie + * $cookieStore.remove('myFavorite'); + * }]); + * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method - * @name ngCookies.$cookieStore#get - * @methodOf ngCookies.$cookieStore + * @name $cookieStore#get * * @description * Returns the value of given cookie key @@ -151,8 +174,7 @@ angular.module('ngCookies', ['ng']). /** * @ngdoc method - * @name ngCookies.$cookieStore#put - * @methodOf ngCookies.$cookieStore + * @name $cookieStore#put * * @description * Sets a value for given cookie key @@ -166,8 +188,7 @@ angular.module('ngCookies', ['ng']). /** * @ngdoc method - * @name ngCookies.$cookieStore#remove - * @methodOf ngCookies.$cookieStore + * @name $cookieStore#remove * * @description * Remove given cookie diff --git a/public/js/lib/angular/angular-cookies.min.js b/public/js/lib/angular/angular-cookies.min.js index f774f8cfd..979b8525d 100644 --- a/public/js/lib/angular/angular-cookies.min.js +++ b/public/js/lib/angular/angular-cookies.min.js @@ -1,7 +1,8 @@ /* - AngularJS v1.0.7 - (c) 2010-2012 Google, Inc. http://angularjs.org + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ -(function(m,f,l){'use strict';f.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(d,b){var c={},g={},h,i=!1,j=f.copy,k=f.isUndefined;b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,j(a,g),j(a,c),i&&d.$apply())})();i=!0;d.$watch(function(){var a,e,d;for(a in g)k(c[a])&&b.cookies(a,l);for(a in c)e=c[a],f.isString(e)?e!==g[a]&&(b.cookies(a,e),d=!0):f.isDefined(g[a])?c[a]=g[a]:delete c[a];if(d)for(a in e=b.cookies(),c)c[a]!==e[a]&&(k(e[a])?delete c[a]:c[a]=e[a])});return c}]).factory("$cookieStore", -["$cookies",function(d){return{get:function(b){return(b=d[b])?f.fromJson(b):b},put:function(b,c){d[b]=f.toJson(c)},remove:function(b){delete d[b]}}}])})(window,window.angular); +(function(p,f,n){'use strict';f.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(e,b){var c={},g={},h,k=!1,l=f.copy,m=f.isUndefined;b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,l(a,g),l(a,c),k&&e.$apply())})();k=!0;e.$watch(function(){var a,d,e;for(a in g)m(c[a])&&b.cookies(a,n);for(a in c)d=c[a],f.isString(d)||(d=""+d,c[a]=d),d!==g[a]&&(b.cookies(a,d),e=!0);if(e)for(a in d=b.cookies(),c)c[a]!==d[a]&&(m(d[a])?delete c[a]:c[a]=d[a])});return c}]).factory("$cookieStore", +["$cookies",function(e){return{get:function(b){return(b=e[b])?f.fromJson(b):b},put:function(b,c){e[b]=f.toJson(c)},remove:function(b){delete e[b]}}}])})(window,window.angular); +//# sourceMappingURL=angular-cookies.min.js.map diff --git a/public/js/lib/angular/angular-cookies.min.js.map b/public/js/lib/angular/angular-cookies.min.js.map new file mode 100644 index 000000000..26f361689 --- /dev/null +++ b/public/js/lib/angular/angular-cookies.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-cookies.min.js", +"lineCount":7, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAmBtCD,CAAAE,OAAA,CAAe,WAAf,CAA4B,CAAC,IAAD,CAA5B,CAAAC,QAAA,CA0BW,UA1BX,CA0BuB,CAAC,YAAD,CAAe,UAAf,CAA2B,QAAS,CAACC,CAAD,CAAaC,CAAb,CAAuB,CAAA,IACxEC,EAAU,EAD8D,CAExEC,EAAc,EAF0D,CAGxEC,CAHwE,CAIxEC,EAAU,CAAA,CAJ8D,CAKxEC,EAAOV,CAAAU,KALiE,CAMxEC,EAAcX,CAAAW,YAGlBN,EAAAO,UAAA,CAAmB,QAAQ,EAAG,CAC5B,IAAIC,EAAiBR,CAAAC,QAAA,EACjBE,EAAJ,EAA0BK,CAA1B,GACEL,CAGA,CAHqBK,CAGrB,CAFAH,CAAA,CAAKG,CAAL,CAAqBN,CAArB,CAEA,CADAG,CAAA,CAAKG,CAAL,CAAqBP,CAArB,CACA,CAAIG,CAAJ,EAAaL,CAAAU,OAAA,EAJf,CAF4B,CAA9B,CAAA,EAUAL,EAAA,CAAU,CAAA,CAKVL,EAAAW,OAAA,CASAC,QAAa,EAAG,CAAA,IACVC,CADU,CAEVC,CAFU,CAIVC,CAGJ,KAAKF,CAAL,GAAaV,EAAb,CACMI,CAAA,CAAYL,CAAA,CAAQW,CAAR,CAAZ,CAAJ,EACEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBhB,CAAvB,CAKJ,KAAIgB,CAAJ,GAAYX,EAAZ,CACEY,CAKA,CALQZ,CAAA,CAAQW,CAAR,CAKR,CAJKjB,CAAAoB,SAAA,CAAiBF,CAAjB,CAIL,GAHEA,CACA,CADQ,EACR,CADaA,CACb,CAAAZ,CAAA,CAAQW,CAAR,CAAA,CAAgBC,CAElB,EAAIA,CAAJ,GAAcX,CAAA,CAAYU,CAAZ,CAAd,GACEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBC,CAAvB,CACA,CAAAC,CAAA,CAAU,CAAA,CAFZ,CAOF,IAAIA,CAAJ,CAIE,IAAKF,CAAL,GAFAI,EAEaf,CAFID,CAAAC,QAAA,EAEJA,CAAAA,CAAb,CACMA,CAAA,CAAQW,CAAR,CAAJ,GAAsBI,CAAA,CAAeJ,CAAf,CAAtB,GAEMN,CAAA,CAAYU,CAAA,CAAeJ,CAAf,CAAZ,CAAJ,CACE,OAAOX,CAAA,CAAQW,CAAR,CADT,CAGEX,CAAA,CAAQW,CAAR,CAHF,CAGkBI,CAAA,CAAeJ,CAAf,CALpB,CAhCU,CAThB,CAEA,OAAOX,EA1BqE,CAA3D,CA1BvB,CAAAH,QAAA,CAoIW,cApIX;AAoI2B,CAAC,UAAD,CAAa,QAAQ,CAACmB,CAAD,CAAW,CAErD,MAAO,KAWAC,QAAQ,CAACC,CAAD,CAAM,CAEjB,MAAO,CADHN,CACG,CADKI,CAAA,CAASE,CAAT,CACL,EAAQxB,CAAAyB,SAAA,CAAiBP,CAAjB,CAAR,CAAkCA,CAFxB,CAXd,KA0BAQ,QAAQ,CAACF,CAAD,CAAMN,CAAN,CAAa,CACxBI,CAAA,CAASE,CAAT,CAAA,CAAgBxB,CAAA2B,OAAA,CAAeT,CAAf,CADQ,CA1BrB,QAuCGU,QAAQ,CAACJ,CAAD,CAAM,CACpB,OAAOF,CAAA,CAASE,CAAT,CADa,CAvCjB,CAF8C,CAAhC,CApI3B,CAnBsC,CAArC,CAAA,CAwMEzB,MAxMF,CAwMUA,MAAAC,QAxMV;", +"sources":["angular-cookies.js"], +"names":["window","angular","undefined","module","factory","$rootScope","$browser","cookies","lastCookies","lastBrowserCookies","runEval","copy","isUndefined","addPollFn","currentCookies","$apply","$watch","push","name","value","updated","isString","browserCookies","$cookies","get","key","fromJson","put","toJson","remove"] +} diff --git a/public/js/lib/angular/angular-csp.css b/public/js/lib/angular/angular-csp.css new file mode 100644 index 000000000..3abb3a0e6 --- /dev/null +++ b/public/js/lib/angular/angular-csp.css @@ -0,0 +1,24 @@ +/* Include this file in your html if you are using the CSP mode. */ + +@charset "UTF-8"; + +[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], +.ng-cloak, .x-ng-cloak, +.ng-hide { + display: none !important; +} + +ng\:form { + display: block; +} + +.ng-animate-block-transitions { + transition:0s all!important; + -webkit-transition:0s all!important; +} + +/* show the element during a show/hide animation when the + * animation is ongoing, but the .ng-hide class is active */ +.ng-hide-add-active, .ng-hide-remove { + display: block!important; +} diff --git a/public/js/lib/angular/angular-loader.js b/public/js/lib/angular/angular-loader.js index 9e66972af..4e6fcf2e1 100644 --- a/public/js/lib/angular/angular-loader.js +++ b/public/js/lib/angular/angular-loader.js @@ -1,14 +1,89 @@ /** - * @license AngularJS v1.0.7 - * (c) 2010-2012 Google, Inc. http://angularjs.org + * @license AngularJS v1.2.22 + * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -( +(function() {'use strict'; /** - * @ngdoc interface + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ + +function minErr(module) { + return function () { + var code = arguments[0], + prefix = '[' + (module ? module + ':' : '') + code + '] ', + template = arguments[1], + templateArgs = arguments, + stringify = function (obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (typeof obj === 'undefined') { + return 'undefined'; + } else if (typeof obj !== 'string') { + return JSON.stringify(obj); + } + return obj; + }, + message, i; + + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; + + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (typeof arg === 'function') { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (typeof arg === 'undefined') { + return 'undefined'; + } else if (typeof arg !== 'string') { + return toJson(arg); + } + return arg; + } + return match; + }); + + message = message + '\nhttp://errors.angularjs.org/1.2.22/' + + (module ? module + '/' : '') + code; + for (i = 2; i < arguments.length; i++) { + message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + + encodeURIComponent(stringify(arguments[i])); + } + + return new Error(message); + }; +} + +/** + * @ngdoc type * @name angular.Module + * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. @@ -16,30 +91,43 @@ function setupModuleLoader(window) { + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } - return ensure(ensure(window, 'angular', Object), 'module', function() { + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function() { /** @type {Object.} */ var modules = {}; /** * @ngdoc function * @name angular.module + * @module ng * @description * - * The `angular.module` is a global place for creating and registering Angular modules. All - * modules (angular core or 3rd party) that should be available to an application must be + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * + * When passed two or more arguments, a new module is created. If passed only one argument, an + * existing module (the name passed as the first argument to `module`) is retrieved. + * * * # Module * - * A module is a collocation of services, directives, filters, and configuration information. Module - * is used to configure the {@link AUTO.$injector $injector}. + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. * - *
    +     * ```js
          * // Create a new module
          * var myModule = angular.module('myModule', []);
          *
    @@ -47,37 +135,45 @@ function setupModuleLoader(window) {
          * myModule.value('appName', 'MyCoolApp');
          *
          * // configure existing services inside initialization blocks.
    -     * myModule.config(function($locationProvider) {
    -'use strict';
    +     * myModule.config(['$locationProvider', function($locationProvider) {
          *   // Configure existing providers
          *   $locationProvider.hashPrefix('!');
    -     * });
    -     * 
    + * }]); + * ``` * * Then you can create an injector and load your modules like this: * - *
    -     * var injector = angular.injector(['ng', 'MyModule'])
    -     * 
    + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. - * @param {Array.=} requires If specified then new module is being created. If unspecified then the - * the module is being retrieved for further configuration. - * @param {Function} configFn Optional configuration function for the module. Same as + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; + + assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { - throw Error('No module: ' + name); + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); } /** @type {!Array.>} */ @@ -97,17 +193,18 @@ function setupModuleLoader(window) { /** * @ngdoc property * @name angular.Module#requires - * @propertyOf angular.Module + * @module ng * @returns {Array.} List of module names which must be loaded before this module. * @description - * Holds the list of modules which the injector will load before the current module is loaded. + * Holds the list of modules which the injector will load before the current module is + * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name - * @propertyOf angular.Module + * @module ng * @returns {string} Name of the module. * @description */ @@ -117,63 +214,98 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#provider - * @methodOf angular.Module + * @module ng * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the service. + * @param {Function} providerType Construction function for creating new instance of the + * service. * @description - * See {@link AUTO.$provide#provider $provide.provider()}. + * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description - * See {@link AUTO.$provide#factory $provide.factory()}. + * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description - * See {@link AUTO.$provide#service $provide.service()}. + * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description - * See {@link AUTO.$provide#value $provide.value()}. + * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant - * @methodOf angular.Module + * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. - * See {@link AUTO.$provide#constant $provide.constant()}. + * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link ngAnimate.$animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), + /** * @ngdoc method * @name angular.Module#filter - * @methodOf angular.Module + * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description @@ -184,8 +316,9 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#controller - * @methodOf angular.Module - * @param {string} name Controller name. + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. @@ -195,8 +328,9 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#directive - * @methodOf angular.Module - * @param {string} name directive name + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description @@ -207,18 +341,20 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#config - * @methodOf angular.Module + * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#providers_provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run - * @methodOf angular.Module + * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description @@ -247,7 +383,7 @@ function setupModuleLoader(window) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; - } + }; } }); }; @@ -255,7 +391,8 @@ function setupModuleLoader(window) { } -)(window); +setupModuleLoader(window); +})(window); /** * Closure compiler type information diff --git a/public/js/lib/angular/angular-loader.min.js b/public/js/lib/angular/angular-loader.min.js index 448dd1d09..06a260f44 100644 --- a/public/js/lib/angular/angular-loader.min.js +++ b/public/js/lib/angular/angular-loader.min.js @@ -1,7 +1,9 @@ /* - AngularJS v1.0.7 - (c) 2010-2012 Google, Inc. http://angularjs.org + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ -(function(i){'use strict';function d(c,b,e){return c[b]||(c[b]=e())}return d(d(i,"angular",Object),"module",function(){var c={};return function(b,e,f){e&&c.hasOwnProperty(b)&&(c[b]=null);return d(c,b,function(){function a(a,b,d){return function(){c[d||"push"]([a,b,arguments]);return g}}if(!e)throw Error("No module: "+b);var c=[],d=[],h=a("$injector","invoke"),g={_invokeQueue:c,_runBlocks:d,requires:e,name:b,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide","service"), -value:a("$provide","value"),constant:a("$provide","constant","unshift"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:h,run:function(a){d.push(a);return this}};f&&h(f);return g})}})})(window); +(function(){'use strict';function d(a){return function(){var c=arguments[0],b,c="["+(a?a+":":"")+c+"] http://errors.angularjs.org/1.2.22/"+(a?a+"/":"")+c;for(b=1;b + * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { @@ -225,7 +223,7 @@ angular.mock.$Browser.prototype = { * }); * }); * }); - * + * ``` */ angular.mock.$ExceptionHandlerProvider = function() { @@ -233,8 +231,7 @@ angular.mock.$ExceptionHandlerProvider = function() { /** * @ngdoc method - * @name ngMock.$exceptionHandlerProvider#mode - * @methodOf ngMock.$exceptionHandlerProvider + * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. @@ -244,10 +241,10 @@ angular.mock.$ExceptionHandlerProvider = function() { * - `rethrow`: If any errors are passed into the handler in tests, it typically * means that there is a bug in the application or test, so this mock will * make these tests fail. - * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` mode stores an - * array of errors in `$exceptionHandler.errors`, to allow later assertion of them. - * See {@link ngMock.$log#assertEmpty assertEmpty()} and - * {@link ngMock.$log#reset reset()} + * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` + * mode stores an array of errors in `$exceptionHandler.errors`, to allow later + * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and + * {@link ngMock.$log#reset reset()} */ this.mode = function(mode) { switch(mode) { @@ -270,7 +267,7 @@ angular.mock.$ExceptionHandlerProvider = function() { handler.errors = errors; break; default: - throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); + throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); } }; @@ -284,7 +281,7 @@ angular.mock.$ExceptionHandlerProvider = function() { /** * @ngdoc service - * @name ngMock.$log + * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays @@ -293,24 +290,37 @@ angular.mock.$ExceptionHandlerProvider = function() { * */ angular.mock.$LogProvider = function() { + var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } + this.debugEnabled = function(flag) { + if (angular.isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; this.$get = function () { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, - error: function() { $log.error.logs.push(concat([], arguments, 0)); } + error: function() { $log.error.logs.push(concat([], arguments, 0)); }, + debug: function() { + if (debug) { + $log.debug.logs.push(concat([], arguments, 0)); + } + } }; /** * @ngdoc method - * @name ngMock.$log#reset - * @methodOf ngMock.$log + * @name $log#reset * * @description * Reset all of the logging arrays to empty. @@ -318,86 +328,97 @@ angular.mock.$LogProvider = function() { $log.reset = function () { /** * @ngdoc property - * @name ngMock.$log#log.logs - * @propertyOf ngMock.$log + * @name $log#log.logs * * @description * Array of messages logged using {@link ngMock.$log#log}. * * @example - *
    +       * ```js
            * $log.log('Some Log');
            * var first = $log.log.logs.unshift();
    -       * 
    + * ``` */ $log.log.logs = []; /** * @ngdoc property - * @name ngMock.$log#warn.logs - * @propertyOf ngMock.$log + * @name $log#info.logs * * @description - * Array of messages logged using {@link ngMock.$log#warn}. + * Array of messages logged using {@link ngMock.$log#info}. * * @example - *
    -       * $log.warn('Some Warning');
    -       * var first = $log.warn.logs.unshift();
    -       * 
    + * ```js + * $log.info('Some Info'); + * var first = $log.info.logs.unshift(); + * ``` */ - $log.warn.logs = []; + $log.info.logs = []; /** * @ngdoc property - * @name ngMock.$log#info.logs - * @propertyOf ngMock.$log + * @name $log#warn.logs * * @description - * Array of messages logged using {@link ngMock.$log#info}. + * Array of messages logged using {@link ngMock.$log#warn}. * * @example - *
    -       * $log.info('Some Info');
    -       * var first = $log.info.logs.unshift();
    -       * 
    + * ```js + * $log.warn('Some Warning'); + * var first = $log.warn.logs.unshift(); + * ``` */ - $log.info.logs = []; + $log.warn.logs = []; /** * @ngdoc property - * @name ngMock.$log#error.logs - * @propertyOf ngMock.$log + * @name $log#error.logs * * @description * Array of messages logged using {@link ngMock.$log#error}. * * @example - *
    -       * $log.log('Some Error');
    +       * ```js
    +       * $log.error('Some Error');
            * var first = $log.error.logs.unshift();
    -       * 
    + * ``` */ $log.error.logs = []; + /** + * @ngdoc property + * @name $log#debug.logs + * + * @description + * Array of messages logged using {@link ngMock.$log#debug}. + * + * @example + * ```js + * $log.debug('Some Error'); + * var first = $log.debug.logs.unshift(); + * ``` + */ + $log.debug.logs = []; }; /** * @ngdoc method - * @name ngMock.$log#assertEmpty - * @methodOf ngMock.$log + * @name $log#assertEmpty * * @description - * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown. + * Assert that the all of the logging methods have no logged messages. If messages present, an + * exception is thrown. */ $log.assertEmpty = function() { var errors = []; - angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) { + angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function (logItem) { - errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); + errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + + (logItem.stack || '')); }); }); }); if (errors.length) { - errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " + - "log message was not checked and removed:"); + errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or "+ + "an expected log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } @@ -409,202 +430,381 @@ angular.mock.$LogProvider = function() { }; -(function() { - var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; +/** + * @ngdoc service + * @name $interval + * + * @description + * Mock implementation of the $interval service. + * + * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to + * move forward by `millis` milliseconds and trigger any functions scheduled to run in that + * time. + * + * @param {function()} fn A function that should be called repeatedly. + * @param {number} delay Number of milliseconds between each function call. + * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat + * indefinitely. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @returns {promise} A promise which will be notified on each iteration. + */ +angular.mock.$IntervalProvider = function() { + this.$get = ['$rootScope', '$q', + function($rootScope, $q) { + var repeatFns = [], + nextRepeatId = 0, + now = 0; + + var $interval = function(fn, delay, count, invokeApply) { + var deferred = $q.defer(), + promise = deferred.promise, + iteration = 0, + skipApply = (angular.isDefined(invokeApply) && !invokeApply); + + count = (angular.isDefined(count)) ? count : 0; + promise.then(null, null, fn); + + promise.$$intervalId = nextRepeatId; + + function tick() { + deferred.notify(iteration++); + + if (count > 0 && iteration >= count) { + var fnIndex; + deferred.resolve(iteration); + + angular.forEach(repeatFns, function(fn, index) { + if (fn.id === promise.$$intervalId) fnIndex = index; + }); + + if (fnIndex !== undefined) { + repeatFns.splice(fnIndex, 1); + } + } + + if (!skipApply) $rootScope.$apply(); + } + + repeatFns.push({ + nextTime:(now + delay), + delay: delay, + fn: tick, + id: nextRepeatId, + deferred: deferred + }); + repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;}); - function jsonStringToDate(string){ - var match; - if (match = string.match(R_ISO8061_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0; - if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); + nextRepeatId++; + return promise; + }; + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {promise} promise A promise from calling the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully cancelled. + */ + $interval.cancel = function(promise) { + if(!promise) return false; + var fnIndex; + + angular.forEach(repeatFns, function(fn, index) { + if (fn.id === promise.$$intervalId) fnIndex = index; + }); + + if (fnIndex !== undefined) { + repeatFns[fnIndex].deferred.reject('canceled'); + repeatFns.splice(fnIndex, 1); + return true; } - date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); - date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); - return date; + + return false; + }; + + /** + * @ngdoc method + * @name $interval#flush + * @description + * + * Runs interval tasks scheduled to be run in the next `millis` milliseconds. + * + * @param {number=} millis maximum timeout amount to flush up until. + * + * @return {number} The amount of time moved forward. + */ + $interval.flush = function(millis) { + now += millis; + while (repeatFns.length && repeatFns[0].nextTime <= now) { + var task = repeatFns[0]; + task.fn(); + task.nextTime += task.delay; + repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;}); + } + return millis; + }; + + return $interval; + }]; +}; + + +/* jshint -W101 */ +/* The R_ISO8061_STR regex is never going to fit into the 100 char limit! + * This directive should go inside the anonymous function but a bug in JSHint means that it would + * not be enacted early enough to prevent the warning. + */ +var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; + +function jsonStringToDate(string) { + var match; + if (match = string.match(R_ISO8061_STR)) { + var date = new Date(0), + tzHour = 0, + tzMin = 0; + if (match[9]) { + tzHour = int(match[9] + match[10]); + tzMin = int(match[9] + match[11]); } - return string; + date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); + date.setUTCHours(int(match[4]||0) - tzHour, + int(match[5]||0) - tzMin, + int(match[6]||0), + int(match[7]||0)); + return date; } + return string; +} - function int(str) { - return parseInt(str, 10); +function int(str) { + return parseInt(str, 10); +} + +function padNumber(num, digits, trim) { + var neg = ''; + if (num < 0) { + neg = '-'; + num = -num; } + num = '' + num; + while(num.length < digits) num = '0' + num; + if (trim) + num = num.substr(num.length - digits); + return neg + num; +} - function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; - } - num = '' + num; - while(num.length < digits) num = '0' + num; - if (trim) - num = num.substr(num.length - digits); - return neg + num; + +/** + * @ngdoc type + * @name angular.mock.TzDate + * @description + * + * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. + * + * Mock of the Date type which has its timezone specified via constructor arg. + * + * The main purpose is to create Date-like instances with timezone fixed to the specified timezone + * offset, so that we can test code that depends on local timezone settings without dependency on + * the time zone settings of the machine where the code is running. + * + * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) + * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* + * + * @example + * !!!! WARNING !!!!! + * This is not a complete Date object so only methods that were implemented can be called safely. + * To make matters worse, TzDate instances inherit stuff from Date via a prototype. + * + * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is + * incomplete we might be missing some non-standard methods. This can result in errors like: + * "Date.prototype.foo called on incompatible Object". + * + * ```js + * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); + * newYearInBratislava.getTimezoneOffset() => -60; + * newYearInBratislava.getFullYear() => 2010; + * newYearInBratislava.getMonth() => 0; + * newYearInBratislava.getDate() => 1; + * newYearInBratislava.getHours() => 0; + * newYearInBratislava.getMinutes() => 0; + * newYearInBratislava.getSeconds() => 0; + * ``` + * + */ +angular.mock.TzDate = function (offset, timestamp) { + var self = new Date(0); + if (angular.isString(timestamp)) { + var tsStr = timestamp; + + self.origDate = jsonStringToDate(timestamp); + + timestamp = self.origDate.getTime(); + if (isNaN(timestamp)) + throw { + name: "Illegal Argument", + message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" + }; + } else { + self.origDate = new Date(timestamp); } + var localOffset = new Date(timestamp).getTimezoneOffset(); + self.offsetDiff = localOffset*60*1000 - offset*1000*60*60; + self.date = new Date(timestamp + self.offsetDiff); - /** - * @ngdoc object - * @name angular.mock.TzDate - * @description - * - * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. - * - * Mock of the Date type which has its timezone specified via constructor arg. - * - * The main purpose is to create Date-like instances with timezone fixed to the specified timezone - * offset, so that we can test code that depends on local timezone settings without dependency on - * the time zone settings of the machine where the code is running. - * - * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) - * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* - * - * @example - * !!!! WARNING !!!!! - * This is not a complete Date object so only methods that were implemented can be called safely. - * To make matters worse, TzDate instances inherit stuff from Date via a prototype. - * - * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is - * incomplete we might be missing some non-standard methods. This can result in errors like: - * "Date.prototype.foo called on incompatible Object". - * - *
    -   * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
    -   * newYearInBratislava.getTimezoneOffset() => -60;
    -   * newYearInBratislava.getFullYear() => 2010;
    -   * newYearInBratislava.getMonth() => 0;
    -   * newYearInBratislava.getDate() => 1;
    -   * newYearInBratislava.getHours() => 0;
    -   * newYearInBratislava.getMinutes() => 0;
    -   * 
    - * - */ - angular.mock.TzDate = function (offset, timestamp) { - var self = new Date(0); - if (angular.isString(timestamp)) { - var tsStr = timestamp; - - self.origDate = jsonStringToDate(timestamp); - - timestamp = self.origDate.getTime(); - if (isNaN(timestamp)) - throw { - name: "Illegal Argument", - message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" - }; - } else { - self.origDate = new Date(timestamp); - } + self.getTime = function() { + return self.date.getTime() - self.offsetDiff; + }; - var localOffset = new Date(timestamp).getTimezoneOffset(); - self.offsetDiff = localOffset*60*1000 - offset*1000*60*60; - self.date = new Date(timestamp + self.offsetDiff); + self.toLocaleDateString = function() { + return self.date.toLocaleDateString(); + }; - self.getTime = function() { - return self.date.getTime() - self.offsetDiff; - }; + self.getFullYear = function() { + return self.date.getFullYear(); + }; - self.toLocaleDateString = function() { - return self.date.toLocaleDateString(); - }; + self.getMonth = function() { + return self.date.getMonth(); + }; - self.getFullYear = function() { - return self.date.getFullYear(); - }; + self.getDate = function() { + return self.date.getDate(); + }; - self.getMonth = function() { - return self.date.getMonth(); - }; + self.getHours = function() { + return self.date.getHours(); + }; - self.getDate = function() { - return self.date.getDate(); - }; + self.getMinutes = function() { + return self.date.getMinutes(); + }; - self.getHours = function() { - return self.date.getHours(); - }; + self.getSeconds = function() { + return self.date.getSeconds(); + }; - self.getMinutes = function() { - return self.date.getMinutes(); - }; + self.getMilliseconds = function() { + return self.date.getMilliseconds(); + }; - self.getSeconds = function() { - return self.date.getSeconds(); - }; + self.getTimezoneOffset = function() { + return offset * 60; + }; - self.getTimezoneOffset = function() { - return offset * 60; - }; + self.getUTCFullYear = function() { + return self.origDate.getUTCFullYear(); + }; - self.getUTCFullYear = function() { - return self.origDate.getUTCFullYear(); - }; + self.getUTCMonth = function() { + return self.origDate.getUTCMonth(); + }; - self.getUTCMonth = function() { - return self.origDate.getUTCMonth(); - }; + self.getUTCDate = function() { + return self.origDate.getUTCDate(); + }; - self.getUTCDate = function() { - return self.origDate.getUTCDate(); - }; + self.getUTCHours = function() { + return self.origDate.getUTCHours(); + }; - self.getUTCHours = function() { - return self.origDate.getUTCHours(); - }; + self.getUTCMinutes = function() { + return self.origDate.getUTCMinutes(); + }; - self.getUTCMinutes = function() { - return self.origDate.getUTCMinutes(); - }; + self.getUTCSeconds = function() { + return self.origDate.getUTCSeconds(); + }; - self.getUTCSeconds = function() { - return self.origDate.getUTCSeconds(); - }; + self.getUTCMilliseconds = function() { + return self.origDate.getUTCMilliseconds(); + }; - self.getUTCMilliseconds = function() { - return self.origDate.getUTCMilliseconds(); + self.getDay = function() { + return self.date.getDay(); + }; + + // provide this method only on browsers that already have it + if (self.toISOString) { + self.toISOString = function() { + return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + + padNumber(self.origDate.getUTCDate(), 2) + 'T' + + padNumber(self.origDate.getUTCHours(), 2) + ':' + + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; + } - self.getDay = function() { - return self.date.getDay(); + //hide all methods not implemented in this mock that the Date prototype exposes + var unimplementedMethods = ['getUTCDay', + 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', + 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', + 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', + 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', + 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; + + angular.forEach(unimplementedMethods, function(methodName) { + self[methodName] = function() { + throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); }; + }); - // provide this method only on browsers that already have it - if (self.toISOString) { - self.toISOString = function() { - return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + - padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + - padNumber(self.origDate.getUTCDate(), 2) + 'T' + - padNumber(self.origDate.getUTCHours(), 2) + ':' + - padNumber(self.origDate.getUTCMinutes(), 2) + ':' + - padNumber(self.origDate.getUTCSeconds(), 2) + '.' + - padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z' - } - } + return self; +}; + +//make "tzDateInstance instanceof Date" return true +angular.mock.TzDate.prototype = Date.prototype; +/* jshint +W101 */ - //hide all methods not implemented in this mock that the Date prototype exposes - var unimplementedMethods = ['getMilliseconds', 'getUTCDay', - 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', - 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', - 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', - 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', - 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; - - angular.forEach(unimplementedMethods, function(methodName) { - self[methodName] = function() { - throw Error("Method '" + methodName + "' is not implemented in the TzDate mock"); +angular.mock.animate = angular.module('ngAnimateMock', ['ng']) + + .config(['$provide', function($provide) { + + var reflowQueue = []; + $provide.value('$$animateReflow', function(fn) { + var index = reflowQueue.length; + reflowQueue.push(fn); + return function cancel() { + reflowQueue.splice(index, 1); }; }); - return self; - }; + $provide.decorator('$animate', function($delegate, $$asyncCallback) { + var animate = { + queue : [], + enabled : $delegate.enabled, + triggerCallbacks : function() { + $$asyncCallback.flush(); + }, + triggerReflow : function() { + angular.forEach(reflowQueue, function(fn) { + fn(); + }); + reflowQueue = []; + } + }; - //make "tzDateInstance instanceof Date" return true - angular.mock.TzDate.prototype = Date.prototype; -})(); + angular.forEach( + ['enter','leave','move','addClass','removeClass','setClass'], function(method) { + animate[method] = function() { + animate.queue.push({ + event : method, + element : arguments[0], + args : arguments + }); + $delegate[method].apply($delegate, arguments); + }; + }); + + return animate; + }); + + }]); /** @@ -614,9 +814,11 @@ angular.mock.$LogProvider = function() { * * *NOTE*: this is not an injectable instance, just a globally available function. * - * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging. + * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for + * debugging. * - * This method is also available on window, where it can be used to display objects on debug console. + * This method is also available on window, where it can be used to display objects on debug + * console. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument @@ -646,6 +848,8 @@ angular.mock.dump = function(object) { } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { + // TODO(i): this prevents methods being logged, + // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { @@ -659,7 +863,7 @@ angular.mock.dump = function(object) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for ( var key in scope ) { - if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) { + if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } @@ -674,8 +878,8 @@ angular.mock.dump = function(object) { }; /** - * @ngdoc object - * @name ngMock.$httpBackend + * @ngdoc service + * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. @@ -684,8 +888,8 @@ angular.mock.dump = function(object) { * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * * During unit testing, we want our unit tests to run quickly and have no external dependencies so - * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or - * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is + * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or + * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. @@ -696,7 +900,7 @@ angular.mock.dump = function(object) { * When an Angular application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify - * the requests and respond with some testing data without sending a request to real server. + * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: @@ -763,89 +967,113 @@ angular.mock.dump = function(object) { * * # Flushing HTTP requests * - * The $httpBackend used in production, always responds to requests with responses asynchronously. - * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are - * hard to write, follow and maintain. At the same time the testing mock, can't respond - * synchronously because that would change the execution of the code under test. For this reason the - * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending - * requests and thus preserving the async api of the backend, while allowing the test to execute - * synchronously. + * The $httpBackend used in production always responds to requests asynchronously. If we preserved + * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, + * to follow and to maintain. But neither can the testing mock respond synchronously; that would + * change the execution of the code under test. For this reason, the mock $httpBackend has a + * `flush()` method, which allows the test to explicitly flush pending requests. This preserves + * the async api of the backend, while allowing the test to execute synchronously. * * * # Unit testing with mock $httpBackend + * The following code shows how to setup and use the mock backend when unit testing a controller. + * First we create the controller under test: * - *
    -   // controller
    -   function MyController($scope, $http) {
    -     $http.get('/auth.py').success(function(data) {
    -       $scope.user = data;
    -     });
    -
    -     this.saveMessage = function(message) {
    -       $scope.status = 'Saving...';
    -       $http.post('/add-msg.py', message).success(function(response) {
    -         $scope.status = '';
    -       }).error(function() {
    -         $scope.status = 'ERROR!';
    -       });
    -     };
    -   }
    +  ```js
    +  // The controller code
    +  function MyController($scope, $http) {
    +    var authToken;
     
    -   // testing controller
    -   var $httpBackend;
    +    $http.get('/auth.py').success(function(data, status, headers) {
    +      authToken = headers('A-Token');
    +      $scope.user = data;
    +    });
     
    -   beforeEach(inject(function($injector) {
    -     $httpBackend = $injector.get('$httpBackend');
    +    $scope.saveMessage = function(message) {
    +      var headers = { 'Authorization': authToken };
    +      $scope.status = 'Saving...';
     
    -     // backend definition common for all tests
    -     $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
    -   }));
    +      $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
    +        $scope.status = '';
    +      }).error(function() {
    +        $scope.status = 'ERROR!';
    +      });
    +    };
    +  }
    +  ```
    + *
    + * Now we setup the mock backend and create the test specs:
    + *
    +  ```js
    +    // testing controller
    +    describe('MyController', function() {
    +       var $httpBackend, $rootScope, createController;
     
    +       beforeEach(inject(function($injector) {
    +         // Set up the mock http service responses
    +         $httpBackend = $injector.get('$httpBackend');
    +         // backend definition common for all tests
    +         $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
     
    -   afterEach(function() {
    -     $httpBackend.verifyNoOutstandingExpectation();
    -     $httpBackend.verifyNoOutstandingRequest();
    -   });
    +         // Get hold of a scope (i.e. the root scope)
    +         $rootScope = $injector.get('$rootScope');
    +         // The $controller service is used to create instances of controllers
    +         var $controller = $injector.get('$controller');
     
    +         createController = function() {
    +           return $controller('MyController', {'$scope' : $rootScope });
    +         };
    +       }));
     
    -   it('should fetch authentication token', function() {
    -     $httpBackend.expectGET('/auth.py');
    -     var controller = scope.$new(MyController);
    -     $httpBackend.flush();
    -   });
     
    +       afterEach(function() {
    +         $httpBackend.verifyNoOutstandingExpectation();
    +         $httpBackend.verifyNoOutstandingRequest();
    +       });
     
    -   it('should send msg to server', function() {
    -     // now you don’t care about the authentication, but
    -     // the controller will still send the request and
    -     // $httpBackend will respond without you having to
    -     // specify the expectation and response for this request
    -     $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
     
    -     var controller = scope.$new(MyController);
    -     $httpBackend.flush();
    -     controller.saveMessage('message content');
    -     expect(controller.status).toBe('Saving...');
    -     $httpBackend.flush();
    -     expect(controller.status).toBe('');
    -   });
    +       it('should fetch authentication token', function() {
    +         $httpBackend.expectGET('/auth.py');
    +         var controller = createController();
    +         $httpBackend.flush();
    +       });
    +
    +
    +       it('should send msg to server', function() {
    +         var controller = createController();
    +         $httpBackend.flush();
    +
    +         // now you don’t care about the authentication, but
    +         // the controller will still send the request and
    +         // $httpBackend will respond without you having to
    +         // specify the expectation and response for this request
    +
    +         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
    +         $rootScope.saveMessage('message content');
    +         expect($rootScope.status).toBe('Saving...');
    +         $httpBackend.flush();
    +         expect($rootScope.status).toBe('');
    +       });
     
     
    -   it('should send auth header', function() {
    -     $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
    -       // check if the header was send, if it wasn't the expectation won't
    -       // match the request and the test will fail
    -       return headers['Authorization'] == 'xxx';
    -     }).respond(201, '');
    +       it('should send auth header', function() {
    +         var controller = createController();
    +         $httpBackend.flush();
     
    -     var controller = scope.$new(MyController);
    -     controller.saveMessage('whatever');
    -     $httpBackend.flush();
    -   });
    -   
    + $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { + // check if the header was send, if it wasn't the expectation won't + // match the request and the test will fail + return headers['Authorization'] == 'xxx'; + }).respond(201, ''); + + $rootScope.saveMessage('whatever'); + $httpBackend.flush(); + }); + }); + ``` */ angular.mock.$HttpBackendProvider = function() { - this.$get = [createHttpBackendMock]; + this.$get = ['$rootScope', createHttpBackendMock]; }; /** @@ -862,24 +1090,25 @@ angular.mock.$HttpBackendProvider = function() { * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ -function createHttpBackendMock($delegate, $browser) { +function createHttpBackendMock($rootScope, $delegate, $browser) { var definitions = [], expectations = [], responses = [], - responsesPush = angular.bind(responses, responses.push); + responsesPush = angular.bind(responses, responses.push), + copy = angular.copy; - function createResponse(status, data, headers) { + function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) - ? [status, data, headers] + ? [status, data, headers, statusText] : [200, status, data]; }; } // TODO(vojta): change params to: method, url, data, headers, callback - function $httpBackend(method, url, data, callback, headers) { + function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; @@ -890,24 +1119,43 @@ function createHttpBackendMock($delegate, $browser) { : angular.toJson(data); } + function wrapResponse(wrapped) { + if (!$browser && timeout && timeout.then) timeout.then(handleTimeout); + + return handleResponse; + + function handleResponse() { + var response = wrapped.response(method, url, data, headers); + xhr.$$respHeaders = response[2]; + callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), + copy(response[3] || '')); + } + + function handleTimeout() { + for (var i = 0, ii = responses.length; i < ii; i++) { + if (responses[i] === handleResponse) { + responses.splice(i, 1); + callback(-1, undefined, ''); + break; + } + } + } + } + if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) - throw Error('Expected ' + expectation + ' with different data\n' + + throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); if (!expectation.matchHeaders(headers)) - throw Error('Expected ' + expectation + ' with different headers\n' + - 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + - prettyPrint(headers)); + throw new Error('Expected ' + expectation + ' with different headers\n' + + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + + prettyPrint(headers)); expectations.shift(); if (expectation.response) { - responses.push(function() { - var response = expectation.response(method, url, data, headers); - xhr.$$respHeaders = response[2]; - callback(response[0], response[1], xhr.getAllResponseHeaders()); - }); + responses.push(wrapResponse(expectation)); return; } wasExpected = true; @@ -918,48 +1166,46 @@ function createHttpBackendMock($delegate, $browser) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests - ($browser ? $browser.defer : responsesPush)(function() { - var response = definition.response(method, url, data, headers); - xhr.$$respHeaders = response[2]; - callback(response[0], response[1], xhr.getAllResponseHeaders()); - }); + ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { - $delegate(method, url, data, callback, headers); - } else throw Error('No response defined !'); + $delegate(method, url, data, callback, headers, timeout, withCredentials); + } else throw new Error('No response defined !'); return; } } throw wasExpected ? - Error('No response defined !') : - Error('Unexpected request: ' + method + ' ' + url + '\n' + - (expectation ? 'Expected ' + expectation : 'No more request expected')); + new Error('No response defined !') : + new Error('Unexpected request: ' + method + ' ' + url + '\n' + + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method - * @name ngMock.$httpBackend#when - * @methodOf ngMock.$httpBackend + * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. - * @returns {requestHandler} Returns an object with `respond` method that control how a matched + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. * - * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` - * – The respond method takes a set of static data to be returned or a function that can return - * an array containing response status (number), response data (string) and response headers - * (Object). + * - respond – + * `{function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers)}` + * – The respond method takes a set of static data to be returned or a function that can + * return an array containing response status (number), response data (string), response + * headers (Object), and the text for the status (string). */ $httpBackend.when = function(method, url, data, headers) { var definition = new MockHttpExpectation(method, url, data, headers), chain = { - respond: function(status, data, headers) { - definition.response = createResponse(status, data, headers); + respond: function(status, data, headers, statusText) { + definition.response = createResponse(status, data, headers, statusText); } }; @@ -975,8 +1221,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenGET - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * @@ -988,8 +1233,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenHEAD - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * @@ -1001,8 +1245,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenDELETE - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * @@ -1014,13 +1257,13 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenPOST - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. @@ -1028,13 +1271,13 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenPUT - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. @@ -1042,8 +1285,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#whenJSONP - * @methodOf ngMock.$httpBackend + * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * @@ -1056,30 +1298,33 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expect - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. * - * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` - * – The respond method takes a set of static data to be returned or a function that can return - * an array containing response status (number), response data (string) and response headers - * (Object). + * - respond – + * `{function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers)}` + * – The respond method takes a set of static data to be returned or a function that can + * return an array containing response status (number), response data (string), response + * headers (Object), and the text for the status (string). */ $httpBackend.expect = function(method, url, data, headers) { var expectation = new MockHttpExpectation(method, url, data, headers); expectations.push(expectation); return { - respond: function(status, data, headers) { - expectation.response = createResponse(status, data, headers); + respond: function (status, data, headers, statusText) { + expectation.response = createResponse(status, data, headers, statusText); } }; }; @@ -1087,8 +1332,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectGET - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * @@ -1100,8 +1344,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectHEAD - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * @@ -1113,8 +1356,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectDELETE - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * @@ -1126,13 +1368,14 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectPOST - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. @@ -1140,13 +1383,14 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectPUT - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. @@ -1154,13 +1398,14 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectPATCH - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. - * @param {(string|RegExp)=} data HTTP request body. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. @@ -1168,8 +1413,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#expectJSONP - * @methodOf ngMock.$httpBackend + * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * @@ -1182,8 +1426,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#flush - * @methodOf ngMock.$httpBackend + * @name $httpBackend#flush * @description * Flushes all pending requests using the trained responses. * @@ -1192,11 +1435,12 @@ function createHttpBackendMock($delegate, $browser) { * is called an exception is thrown (as this typically a sign of programming error). */ $httpBackend.flush = function(count) { - if (!responses.length) throw Error('No pending request to flush !'); + $rootScope.$digest(); + if (!responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count)) { while (count--) { - if (!responses.length) throw Error('No more pending request to flush !'); + if (!responses.length) throw new Error('No more pending request to flush !'); responses.shift()(); } } else { @@ -1210,8 +1454,7 @@ function createHttpBackendMock($delegate, $browser) { /** * @ngdoc method - * @name ngMock.$httpBackend#verifyNoOutstandingExpectation - * @methodOf ngMock.$httpBackend + * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. @@ -1219,42 +1462,41 @@ function createHttpBackendMock($delegate, $browser) { * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * - *
    -   *   afterEach($httpBackend.verifyExpectations);
    -   * 
    + * ```js + * afterEach($httpBackend.verifyNoOutstandingExpectation); + * ``` */ $httpBackend.verifyNoOutstandingExpectation = function() { + $rootScope.$digest(); if (expectations.length) { - throw Error('Unsatisfied requests: ' + expectations.join(', ')); + throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method - * @name ngMock.$httpBackend#verifyNoOutstandingRequest - * @methodOf ngMock.$httpBackend + * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * - *
    +   * ```js
        *   afterEach($httpBackend.verifyNoOutstandingRequest);
    -   * 
    + * ``` */ $httpBackend.verifyNoOutstandingRequest = function() { if (responses.length) { - throw Error('Unflushed requests: ' + responses.length); + throw new Error('Unflushed requests: ' + responses.length); } }; /** * @ngdoc method - * @name ngMock.$httpBackend#resetExpectations - * @methodOf ngMock.$httpBackend + * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of @@ -1271,14 +1513,14 @@ function createHttpBackendMock($delegate, $browser) { function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) { $httpBackend[prefix + method] = function(url, headers) { - return $httpBackend[prefix](method, url, undefined, headers) - } + return $httpBackend[prefix](method, url, undefined, headers); + }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers) { - return $httpBackend[prefix](method, url, data, headers) - } + return $httpBackend[prefix](method, url, data, headers); + }; }); } } @@ -1311,7 +1553,8 @@ function MockHttpExpectation(method, url, data, headers) { this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); - if (data && !angular.isString(data)) return angular.toJson(data) == d; + if (data && angular.isFunction(data)) return data(d); + if (data && !angular.isString(data)) return angular.equals(data, angular.fromJson(d)); return data == d; }; @@ -1320,6 +1563,10 @@ function MockHttpExpectation(method, url, data, headers) { }; } +function createMockXhr() { + return new MockXhr(); +} + function MockXhr() { // hack for testing $http, $httpBackend @@ -1342,7 +1589,8 @@ function MockXhr() { }; this.getResponseHeader = function(name) { - // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last + // the lookup must be case insensitive, + // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; @@ -1371,22 +1619,96 @@ function MockXhr() { /** - * @ngdoc function - * @name ngMock.$timeout + * @ngdoc service + * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service - * that adds a "flush" method. + * that adds a "flush" and "verifyNoPendingTasks" methods. */ -/** - * @ngdoc method - * @name ngMock.$timeout#flush - * @methodOf ngMock.$timeout - * @description - * - * Flushes the queue of pending tasks. - */ +angular.mock.$TimeoutDecorator = function($delegate, $browser) { + + /** + * @ngdoc method + * @name $timeout#flush + * @description + * + * Flushes the queue of pending tasks. + * + * @param {number=} delay maximum timeout amount to flush up until + */ + $delegate.flush = function(delay) { + $browser.defer.flush(delay); + }; + + /** + * @ngdoc method + * @name $timeout#verifyNoPendingTasks + * @description + * + * Verifies that there are no pending tasks that need to be flushed. + */ + $delegate.verifyNoPendingTasks = function() { + if ($browser.deferredFns.length) { + throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + + formatPendingTasksAsString($browser.deferredFns)); + } + }; + + function formatPendingTasksAsString(tasks) { + var result = []; + angular.forEach(tasks, function(task) { + result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); + }); + + return result.join(', '); + } + + return $delegate; +}; + +angular.mock.$RAFDecorator = function($delegate) { + var queue = []; + var rafFn = function(fn) { + var index = queue.length; + queue.push(fn); + return function() { + queue.splice(index, 1); + }; + }; + + rafFn.supported = $delegate.supported; + + rafFn.flush = function() { + if(queue.length === 0) { + throw new Error('No rAF callbacks present'); + } + + var length = queue.length; + for(var i=0;i'); - } + }; }; /** - * @ngdoc overview + * @ngdoc module * @name ngMock + * @packageName angular-mocks * @description * - * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful - * mocks to the {@link AUTO.$injector $injector}. + * # ngMock + * + * The `ngMock` module provides support to inject and mock Angular services into unit tests. + * In addition, ngMock also extends various core ng services such that they can be + * inspected and controlled in a synchronous manner within test code. + * + * + *
    + * */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, + $interval: angular.mock.$IntervalProvider, $httpBackend: angular.mock.$HttpBackendProvider, $rootElement: angular.mock.$RootElementProvider -}).config(function($provide) { - $provide.decorator('$timeout', function($delegate, $browser) { - $delegate.flush = function() { - $browser.defer.flush(); - }; - return $delegate; - }); -}); - +}).config(['$provide', function($provide) { + $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); + $provide.decorator('$$rAF', angular.mock.$RAFDecorator); + $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); +}]); /** - * @ngdoc overview + * @ngdoc module * @name ngMockE2E + * @module ngMockE2E + * @packageName angular-mocks * @description * * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ -angular.module('ngMockE2E', ['ng']).config(function($provide) { +angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); -}); +}]); /** - * @ngdoc object - * @name ngMockE2E.$httpBackend + * @ngdoc service + * @name $httpBackend + * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. @@ -1456,13 +1786,13 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit - * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests + * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * - *
    + * ```js
      *   myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
      *   myAppDev.run(function($httpBackend) {
      *     phones = [{name: 'phone1'}, {name: 'phone2'}];
    @@ -1472,20 +1802,22 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) {
      *
      *     // adds a new phone to the phones array
      *     $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    - *       phones.push(angular.fromJSON(data));
    + *       var phone = angular.fromJson(data);
    + *       phones.push(phone);
    + *       return [200, phone, {}];
      *     });
      *     $httpBackend.whenGET(/^\/templates\//).passThrough();
      *     //...
      *   });
    - * 
    + * ``` * * Afterwards, bootstrap your app with this new module. */ /** * @ngdoc method - * @name ngMockE2E.$httpBackend#when - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#when + * @module ngMockE2E * @description * Creates a new backend definition. * @@ -1497,19 +1829,21 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. * - * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` + * - respond – + * `{function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return - * an array containing response status (number), response data (string) and response headers - * (Object). - * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough` - * handler, will be pass through to the real backend (an XHR request will be made to the - * server. + * an array containing response status (number), response data (string), response headers + * (Object), and the text for the status (string). + * - passThrough – `{function()}` – Any request matching a backend definition with + * `passThrough` handler will be passed through to the real backend (an XHR request will be made + * to the server.) */ /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenGET - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenGET + * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * @@ -1521,8 +1855,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenHEAD - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenHEAD + * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * @@ -1534,8 +1868,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenDELETE - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenDELETE + * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * @@ -1547,8 +1881,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenPOST - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenPOST + * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * @@ -1561,8 +1895,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenPUT - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenPUT + * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * @@ -1575,8 +1909,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenPATCH - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenPATCH + * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * @@ -1589,8 +1923,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { /** * @ngdoc method - * @name ngMockE2E.$httpBackend#whenJSONP - * @methodOf ngMockE2E.$httpBackend + * @name $httpBackend#whenJSONP + * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * @@ -1599,7 +1933,8 @@ angular.module('ngMockE2E', ['ng']).config(function($provide) { * control how a matched request is handled. */ angular.mock.e2e = {}; -angular.mock.e2e.$httpBackendDecorator = ['$delegate', '$browser', createHttpBackendMock]; +angular.mock.e2e.$httpBackendDecorator = + ['$rootScope', '$delegate', '$browser', createHttpBackendMock]; angular.mock.clearDataCache = function() { @@ -1607,44 +1942,43 @@ angular.mock.clearDataCache = function() { cache = angular.element.cache; for(key in cache) { - if (cache.hasOwnProperty(key)) { + if (Object.prototype.hasOwnProperty.call(cache,key)) { var handle = cache[key].handle; - handle && angular.element(handle.elem).unbind(); + handle && angular.element(handle.elem).off(); delete cache[key]; } } }; -window.jstestdriver && (function(window) { - /** - * Global method to output any number of objects into JSTD console. Useful for debugging. - */ - window.dump = function() { - var args = []; - angular.forEach(arguments, function(arg) { - args.push(angular.mock.dump(arg)); - }); - jstestdriver.console.log.apply(jstestdriver.console, args); - if (window.console) { - window.console.log.apply(window.console, args); - } - }; -})(window); +if(window.jasmine || window.mocha) { + var currentSpec = null, + isSpecRunning = function() { + return !!currentSpec; + }; -window.jasmine && (function(window) { - afterEach(function() { - var spec = getCurrentSpec(); - var injector = spec.$injector; + (window.beforeEach || window.setup)(function() { + currentSpec = this; + }); - spec.$injector = null; - spec.$modules = null; + (window.afterEach || window.teardown)(function() { + var injector = currentSpec.$injector; + + angular.forEach(currentSpec.$modules, function(module) { + if (module && module.$$hashKey) { + module.$$hashKey = undefined; + } + }); + + currentSpec.$injector = null; + currentSpec.$modules = null; + currentSpec = null; if (injector) { - injector.get('$rootElement').unbind(); + injector.get('$rootElement').off(); injector.get('$browser').pollFns.length = 0; } @@ -1663,44 +1997,43 @@ window.jasmine && (function(window) { angular.callbacks.counter = 0; }); - function getCurrentSpec() { - return jasmine.getEnv().currentSpec; - } - - function isSpecRunning() { - var spec = getCurrentSpec(); - return spec && spec.queue.running; - } - /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.
    - * *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}. * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * - * @param {...(string|Function)} fns any number of modules which are represented as string + * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to - * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. + * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an + * object literal is passed they will be registered as values in the module, the key being + * the module name and the value being what is returned. */ window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return isSpecRunning() ? workFn() : workFn; ///////////////////// function workFn() { - var spec = getCurrentSpec(); - if (spec.$injector) { - throw Error('Injector already created, can not register a module!'); + if (currentSpec.$injector) { + throw new Error('Injector already created, can not register a module!'); } else { - var modules = spec.$modules || (spec.$modules = []); + var modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { - modules.push(module); + if (angular.isObject(module) && !angular.isArray(module)) { + modules.push(function($provide) { + angular.forEach(module, function(value, key) { + $provide.value(key, value); + }); + }); + } else { + modules.push(module); + } }); } } @@ -1712,16 +2045,47 @@ window.jasmine && (function(window) { * @description * * *NOTE*: This function is also published on window for easy access.
    - * *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}. * * The inject function wraps a function into an injectable function. The inject() creates new - * instance of {@link AUTO.$injector $injector} per test, which is then used for + * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * - * See also {@link angular.mock.module module} * + * ## Resolving References (Underscore Wrapping) + * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this + * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable + * that is declared in the scope of the `describe()` block. Since we would, most likely, want + * the variable to have the same name of the reference we have a problem, since the parameter + * to the `inject()` function would hide the outer variable. + * + * To help with this, the injected parameters can, optionally, be enclosed with underscores. + * These are ignored by the injector when the reference name is resolved. + * + * For example, the parameter `_myService_` would be resolved as the reference `myService`. + * Since it is available in the function body as _myService_, we can then assign it to a variable + * defined in an outer scope. + * + * ``` + * // Defined out reference variable outside + * var myService; + * + * // Wrap the parameter in underscores + * beforeEach( inject( function(_myService_){ + * myService = _myService_; + * })); + * + * // Use myService in a series of tests. + * it('makes use of myService', function() { + * myService.doStuff(); + * }); + * + * ``` + * + * See also {@link angular.mock.module angular.mock.module} + * + * ## Example * Example of what a typical jasmine tests looks like with the inject method. - *
    +   * ```js
        *
        *   angular.module('myApplicationModule', [])
        *       .value('mode', 'app')
    @@ -1752,32 +2116,50 @@ window.jasmine && (function(window) {
        *       inject(function(version) {
        *         expect(version).toEqual('overridden');
        *       });
    -   *     ));
    +   *     });
        *   });
        *
    -   * 
    + * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ + + + + var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { + this.message = e.message; + this.name = e.name; + if (e.line) this.line = e.line; + if (e.sourceId) this.sourceId = e.sourceId; + if (e.stack && errorForStack) + this.stack = e.stack + '\n' + errorForStack.stack; + if (e.stackArray) this.stackArray = e.stackArray; + }; + ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; + window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); - return isSpecRunning() ? workFn() : workFn; + return isSpecRunning() ? workFn.call(currentSpec) : workFn; ///////////////////// function workFn() { - var spec = getCurrentSpec(); - var modules = spec.$modules || []; + var modules = currentSpec.$modules || []; + modules.unshift('ngMock'); modules.unshift('ng'); - var injector = spec.$injector; + var injector = currentSpec.$injector; if (!injector) { - injector = spec.$injector = angular.injector(modules); + injector = currentSpec.$injector = angular.injector(modules); } for(var i = 0, ii = blockFns.length; i < ii; i++) { try { + /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ injector.invoke(blockFns[i] || angular.noop, this); + /* jshint +W040 */ } catch (e) { - if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack; + if (e.stack && errorForStack) { + throw new ErrorAddingDeclarationLocationStack(e, errorForStack); + } throw e; } finally { errorForStack = null; @@ -1785,4 +2167,7 @@ window.jasmine && (function(window) { } } }; -})(window); +} + + +})(window, window.angular); diff --git a/public/js/lib/angular/angular-resource.js b/public/js/lib/angular/angular-resource.js index d67f501c4..a2b1b5251 100644 --- a/public/js/lib/angular/angular-resource.js +++ b/public/js/lib/angular/angular-resource.js @@ -1,20 +1,72 @@ /** - * @license AngularJS v1.0.7 - * (c) 2010-2012 Google, Inc. http://angularjs.org + * @license AngularJS v1.2.22 + * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) { -'use strict'; +(function(window, angular, undefined) {'use strict'; + +var $resourceMinErr = angular.$$minErr('$resource'); + +// Helper functions and regex to lookup a dotted path on an object +// stopping at undefined/null. The path must be composed of ASCII +// identifiers (just like $parse) +var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/; + +function isValidDottedPath(path) { + return (path != null && path !== '' && path !== 'hasOwnProperty' && + MEMBER_NAME_REGEX.test('.' + path)); +} + +function lookupDottedPath(obj, path) { + if (!isValidDottedPath(path)) { + throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); + } + var keys = path.split('.'); + for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) { + var key = keys[i]; + obj = (obj !== null) ? obj[key] : undefined; + } + return obj; +} /** - * @ngdoc overview + * Create a shallow copy of an object and clear other fields from the destination + */ +function shallowClearAndCopy(src, dst) { + dst = dst || {}; + + angular.forEach(dst, function(value, key){ + delete dst[key]; + }); + + for (var key in src) { + if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } + + return dst; +} + +/** + * @ngdoc module * @name ngResource * @description + * + * # ngResource + * + * The `ngResource` module provides interaction support with RESTful services + * via the $resource service. + * + * + *
    + * + * See {@link ngResource.$resource `$resource`} for usage. */ /** - * @ngdoc object - * @name ngResource.$resource + * @ngdoc service + * @name $resource * @requires $http * * @description @@ -24,24 +76,22 @@ * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * - * # Installation - * To use $resource make sure you have included the `angular-resource.js` that comes in Angular - * package. You can also find this file on Google CDN, bower as well as at - * {@link http://code.angularjs.org/ code.angularjs.org}. - * - * Finally load the module in your application: + * Requires the {@link ngResource `ngResource`} module to be installed. * - * angular.module('app', ['ngResource']); + * @param {string} url A parametrized URL template with parameters prefixed by `:` as in + * `/user/:username`. If you are using a URL with a port number (e.g. + * `http://example.com:8080/api`), it will be respected. * - * and you are ready to get started! - * - * @param {string} url A parameterized URL template with parameters prefixed by `:` as in - * `/user/:username`. If you are using a URL with a port number (e.g. - * `http://example.com:8080/api`), you'll need to escape the colon character before the port - * number, like this: `$resource('http://example.com\\:8080/api')`. + * If you are using a url with a suffix, just add the suffix, like this: + * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` + * or even `$resource('http://example.com/resource/:resource_id.:format')` + * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be + * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you + * can escape it with `/\.`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in - * `actions` methods. + * `actions` methods. If any of the parameter value is a function, it will be executed every time + * when a param value needs to be obtained for a request (unless the param was overridden). * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. @@ -49,47 +99,78 @@ * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * - * If the parameter value is prefixed with `@` then the value of that parameter is extracted from - * the data object (useful for non-GET operations). + * If the parameter value is prefixed with `@` then the value for that parameter will be extracted + * from the corresponding property on the `data` object (provided when calling an action method). For + * example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam` + * will be `data.someProp`. * - * @param {Object.=} actions Hash with declaration of custom action that should extend the - * default set of resource actions. The declaration should be created in the following format: + * @param {Object.=} actions Hash with declaration of custom action that should extend + * the default set of resource actions. The declaration should be created in the format of {@link + * ng.$http#usage_parameters $http.config}: * - * {action1: {method:?, params:?, isArray:?}, - * action2: {method:?, params:?, isArray:?}, + * {action1: {method:?, params:?, isArray:?, headers:?, ...}, + * action2: {method:?, params:?, isArray:?, headers:?, ...}, * ...} * * Where: * - * - `action` – {string} – The name of action. This name becomes the name of the method on your - * resource object. - * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, - * and `JSONP` - * - `params` – {object=} – Optional set of pre-bound parameters for this action. - * - isArray – {boolean=} – If true then the returned object for this action is an array, see - * `returns` section. + * - **`action`** – {string} – The name of action. This name becomes the name of the method on + * your resource object. + * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, + * `DELETE`, `JSONP`, etc). + * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of + * the parameter value is a function, it will be executed every time when a param value needs to + * be obtained for a request (unless the param was overridden). + * - **`url`** – {string} – action specific `url` override. The url templating is supported just + * like for the resource-level urls. + * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, + * see `returns` section. + * - **`transformRequest`** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * - **`transformResponse`** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that + * should abort the request when resolved. + * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See + * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) + * for more information. + * - **`responseType`** - `{string}` - see + * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - + * `response` and `responseError`. Both `response` and `responseError` interceptors get called + * with `http response` object. See {@link ng.$http $http interceptors}. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: - * - * { 'get': {method:'GET'}, - * 'save': {method:'POST'}, - * 'query': {method:'GET', isArray:true}, - * 'remove': {method:'DELETE'}, - * 'delete': {method:'DELETE'} }; + * ```js + * { 'get': {method:'GET'}, + * 'save': {method:'POST'}, + * 'query': {method:'GET', isArray:true}, + * 'remove': {method:'DELETE'}, + * 'delete': {method:'DELETE'} }; + * ``` * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class. The actions `save`, `remove` and `delete` are available on it * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, * read, update, delete) on server-side data like this: - *
    -        var User = $resource('/user/:userId', {userId:'@id'});
    -        var user = User.get({userId:123}, function() {
    -          user.abc = true;
    -          user.$save();
    -        });
    -     
    + * ```js + * var User = $resource('/user/:userId', {userId:'@id'}); + * var user = User.get({userId:123}, function() { + * user.abc = true; + * user.$save(); + * }); + * ``` * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the @@ -97,7 +178,7 @@ * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This - * means that in most case one never has to write a callback function for the action methods. + * means that in most cases one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: @@ -106,12 +187,37 @@ * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * + * Success callback is called with (value, responseHeaders) arguments. Error callback is called + * with (httpResponse) argument. + * + * Class actions return empty instance (with additional properties below). + * Instance actions return promise of the action. + * + * The Resource instances and collection have these additional properties: + * + * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this + * instance or collection. + * + * On success, the promise is resolved with the same resource instance or collection object, + * updated with data from server. This makes it easy to use in + * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view + * rendering until the resource(s) are loaded. + * + * On failure, the promise is resolved with the {@link ng.$http http response} object, without + * the `resource` property. + * + * If an interceptor object was provided, the promise will instead be resolved with the value + * returned by the interceptor. + * + * - `$resolved`: `true` after first server interaction is completed (either with success or + * rejection), `false` before that. Knowing if the Resource has been resolved is useful in + * data-binding. * * @example * * # Credit card resource * - *
    + * ```js
          // Define CreditCard class
          var CreditCard = $resource('/user/:userId/card/:cardId',
           {userId:123, cardId:'@id'}, {
    @@ -142,31 +248,32 @@
          newCard.name = "Mike Smith";
          newCard.$save();
          // POST: /user/123/card {number:'0123', name:'Mike Smith'}
    -     // server returns: {id:789, number:'01234', name: 'Mike Smith'};
    +     // server returns: {id:789, number:'0123', name: 'Mike Smith'};
          expect(newCard.id).toEqual(789);
    - * 
    + * ``` * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * - * Calling these methods invoke `$http` on the `url` template with the given `method` and `params`. + * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and + * `headers`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. -
    +   ```js
          var User = $resource('/user/:userId', {userId:'@id'});
    -     var user = User.get({userId:123}, function() {
    +     User.get({userId:123}, function(user) {
            user.abc = true;
            user.$save();
          });
    -   
    + ``` * - * It's worth noting that the success callback for `get`, `query` and other method gets passed + * It's worth noting that the success callback for `get`, `query` and other methods gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * -
    +   ```js
          var User = $resource('/user/:userId', {userId:'@id'});
          User.get({userId:123}, function(u, getResponseHeaders){
            u.abc = true;
    @@ -175,58 +282,50 @@
              //putResponseHeaders => $http header getter
            });
          });
    -   
    - - * # Buzz client - - Let's look at what a buzz client created with the `$resource` service looks like: - - - - -
    - - -
    -
    -

    - - {{item.actor.name}} - Expand replies: {{item.links.replies[0].count}} -

    - {{item.object.content | html}} -
    - - {{reply.actor.name}}: {{reply.content | html}} -
    -
    -
    -
    - - -
    + ``` + * + * You can also access the raw `$http` promise via the `$promise` property on the object returned + * + ``` + var User = $resource('/user/:userId', {userId:'@id'}); + User.get({userId:123}) + .$promise.then(function(user) { + $scope.user = user; + }); + ``` + + * # Creating a custom 'PUT' request + * In this example we create a custom method on our resource to make a PUT request + * ```js + * var app = angular.module('app', ['ngResource', 'ngRoute']); + * + * // Some APIs expect a PUT request in the format URL/object/ID + * // Here we are creating an 'update' method + * app.factory('Notes', ['$resource', function($resource) { + * return $resource('/notes/:id', null, + * { + * 'update': { method:'PUT' } + * }); + * }]); + * + * // In our controller we get the ID from the URL using ngRoute and $routeParams + * // We pass in $routeParams and our Notes factory along with $scope + * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', + function($scope, $routeParams, Notes) { + * // First get a note object from the factory + * var note = Notes.get({ id:$routeParams.id }); + * $id = note.id; + * + * // Now call update passing in the ID first then the object you are updating + * Notes.update({ id:$id }, note); + * + * // This will PUT /notes/ID with the note object in the request payload + * }]); + * ``` */ angular.module('ngResource', ['ng']). - factory('$resource', ['$http', '$parse', function($http, $parse) { + factory('$resource', ['$http', '$q', function($http, $q) { + var DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, @@ -238,10 +337,7 @@ angular.module('ngResource', ['ng']). forEach = angular.forEach, extend = angular.extend, copy = angular.copy, - isFunction = angular.isFunction, - getter = function(obj, path) { - return $parse(path)(obj); - }; + isFunction = angular.isFunction; /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow @@ -263,9 +359,9 @@ angular.module('ngResource', ['ng']). /** - * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be - * encoded per http://tools.ietf.org/html/rfc3986: + * This method is intended for encoding *key* or *value* parts of query component. We need a + * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't + * have to be encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" @@ -283,32 +379,40 @@ angular.module('ngResource', ['ng']). } function Route(template, defaults) { - this.template = template = template + '#'; + this.template = template; this.defaults = defaults || {}; - var urlParams = this.urlParams = {}; - forEach(template.split(/\W/), function(param){ - if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) { - urlParams[param] = true; - } - }); - this.template = template.replace(/\\:/g, ':'); + this.urlParams = {}; } Route.prototype = { - url: function(params) { + setUrlParams: function(config, params, actionUrl) { var self = this, - url = this.template, + url = actionUrl || self.template, val, encodedVal; + var urlParams = self.urlParams = {}; + forEach(url.split(/\W/), function(param){ + if (param === 'hasOwnProperty') { + throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); + } + if (!(new RegExp("^\\d+$").test(param)) && param && + (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { + urlParams[param] = true; + } + }); + url = url.replace(/\\:/g, ':'); + params = params || {}; - forEach(this.urlParams, function(_, urlParam){ + forEach(self.urlParams, function(_, urlParam){ val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; if (angular.isDefined(val) && val !== null) { encodedVal = encodeUriSegment(val); - url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); + url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { + return encodedVal + p1; + }); } else { - url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match, + url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, leadingSlashes, tail) { if (tail.charAt(0) == '/') { return tail; @@ -318,21 +422,28 @@ angular.module('ngResource', ['ng']). }); } }); - url = url.replace(/\/?#$/, ''); - var query = []; + + // strip trailing slashes and set the url + url = url.replace(/\/+$/, '') || '/'; + // then replace collapse `/.` if found in the last URL path segment before the query + // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` + url = url.replace(/\/\.(?=\w+($|\?))/, '.'); + // replace escaped `/\.` with `/.` + config.url = url.replace(/\/\\\./, '/.'); + + + // set params - delegate param encoding to $http forEach(params, function(value, key){ if (!self.urlParams[key]) { - query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); + config.params = config.params || {}; + config.params[key] = value; } }); - query.sort(); - url = url.replace(/\/*$/, ''); - return url + (query.length ? '?' + query.join('&') : ''); } }; - function ResourceFactory(url, paramDefaults, actions) { + function resourceFactory(url, paramDefaults, actions) { var route = new Route(url); actions = extend({}, DEFAULT_ACTIONS, actions); @@ -341,23 +452,28 @@ angular.module('ngResource', ['ng']). var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key){ - ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; + if (isFunction(value)) { value = value(); } + ids[key] = value && value.charAt && value.charAt(0) == '@' ? + lookupDottedPath(data, value.substr(1)) : value; }); return ids; } + function defaultResponseInterceptor(response) { + return response.resource; + } + function Resource(value){ - copy(value || {}, this); + shallowClearAndCopy(value || {}, this); } forEach(actions, function(action, name) { - action.method = angular.uppercase(action.method); - var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; + var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); + Resource[name] = function(a1, a2, a3, a4) { - var params = {}; - var data; - var success = noop; - var error = null; + var params = {}, data, success, error; + + /* jshint -W086 */ /* (purposefully fall through case statements) */ switch(arguments.length) { case 4: error = a4; @@ -388,69 +504,117 @@ angular.module('ngResource', ['ng']). break; case 0: break; default: - throw "Expected between 0-4 arguments [params, data, success, error], got " + - arguments.length + " arguments."; + throw $resourceMinErr('badargs', + "Expected up to 4 arguments [params, data, success, error], got {0} arguments", + arguments.length); } - - var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); - $http({ - method: action.method, - url: route.url(extend({}, extractParams(data, action.params || {}), params)), - data: data - }).then(function(response) { - var data = response.data; - - if (data) { - if (action.isArray) { - value.length = 0; - forEach(data, function(item) { + /* jshint +W086 */ /* (purposefully fall through case statements) */ + + var isInstanceCall = this instanceof Resource; + var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); + var httpConfig = {}; + var responseInterceptor = action.interceptor && action.interceptor.response || + defaultResponseInterceptor; + var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || + undefined; + + forEach(action, function(value, key) { + if (key != 'params' && key != 'isArray' && key != 'interceptor') { + httpConfig[key] = copy(value); + } + }); + + if (hasBody) httpConfig.data = data; + route.setUrlParams(httpConfig, + extend({}, extractParams(data, action.params || {}), params), + action.url); + + var promise = $http(httpConfig).then(function (response) { + var data = response.data, + promise = value.$promise; + + if (data) { + // Need to convert action.isArray to boolean in case it is undefined + // jshint -W018 + if (angular.isArray(data) !== (!!action.isArray)) { + throw $resourceMinErr('badcfg', + 'Error in resource configuration. Expected ' + + 'response to contain an {0} but got an {1}', + action.isArray ? 'array' : 'object', + angular.isArray(data) ? 'array' : 'object'); + } + // jshint +W018 + if (action.isArray) { + value.length = 0; + forEach(data, function (item) { + if (typeof item === "object") { value.push(new Resource(item)); - }); - } else { - copy(data, value); - } + } else { + // Valid JSON values may be string literals, and these should not be converted + // into objects. These items will not have access to the Resource prototype + // methods, but unfortunately there + value.push(item); + } + }); + } else { + shallowClearAndCopy(data, value); + value.$promise = promise; } - (success||noop)(value, response.headers); - }, error); + } - return value; - }; + value.$resolved = true; + response.resource = value; - Resource.prototype['$' + name] = function(a1, a2, a3) { - var params = extractParams(this), - success = noop, - error; + return response; + }, function(response) { + value.$resolved = true; - switch(arguments.length) { - case 3: params = a1; success = a2; error = a3; break; - case 2: - case 1: - if (isFunction(a1)) { - success = a1; - error = a2; - } else { - params = a1; - success = a2 || noop; - } - case 0: break; - default: - throw "Expected between 1-3 arguments [params, success, error], got " + - arguments.length + " arguments."; + (error||noop)(response); + + return $q.reject(response); + }); + + promise = promise.then( + function(response) { + var value = responseInterceptor(response); + (success||noop)(value, response.headers); + return value; + }, + responseErrorInterceptor); + + if (!isInstanceCall) { + // we are creating instance / collection + // - set the initial promise + // - return the instance / collection + value.$promise = promise; + value.$resolved = false; + + return value; + } + + // instance call + return promise; + }; + + + Resource.prototype['$' + name] = function(params, success, error) { + if (isFunction(params)) { + error = success; success = params; params = {}; } - var data = hasBody ? this : undefined; - Resource[name].call(this, params, data, success, error); + var result = Resource[name].call(this, params, this, success, error); + return result.$promise || result; }; }); Resource.bind = function(additionalParamDefaults){ - return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); + return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; return Resource; } - return ResourceFactory; + return resourceFactory; }]); diff --git a/public/js/lib/angular/angular-resource.min.js b/public/js/lib/angular/angular-resource.min.js index 20982fdee..033b640d1 100644 --- a/public/js/lib/angular/angular-resource.min.js +++ b/public/js/lib/angular/angular-resource.min.js @@ -1,10 +1,13 @@ /* - AngularJS v1.0.7 - (c) 2010-2012 Google, Inc. http://angularjs.org + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ -(function(C,d,w){'use strict';d.module("ngResource",["ng"]).factory("$resource",["$http","$parse",function(x,y){function s(b,e){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,e?"%20":"+")}function t(b,e){this.template=b+="#";this.defaults=e||{};var a=this.urlParams={};h(b.split(/\W/),function(f){f&&RegExp("(^|[^\\\\]):"+f+"\\W").test(b)&&(a[f]=!0)});this.template=b.replace(/\\:/g,":")}function u(b,e,a){function f(m,a){var b= -{},a=o({},e,a);h(a,function(a,z){var c;a.charAt&&a.charAt(0)=="@"?(c=a.substr(1),c=y(c)(m)):c=a;b[z]=c});return b}function g(a){v(a||{},this)}var k=new t(b),a=o({},A,a);h(a,function(a,b){a.method=d.uppercase(a.method);var e=a.method=="POST"||a.method=="PUT"||a.method=="PATCH";g[b]=function(b,c,d,B){var j={},i,l=p,q=null;switch(arguments.length){case 4:q=B,l=d;case 3:case 2:if(r(c)){if(r(b)){l=b;q=c;break}l=c;q=d}else{j=b;i=c;l=d;break}case 1:r(b)?l=b:e?i=b:j=b;break;case 0:break;default:throw"Expected between 0-4 arguments [params, data, success, error], got "+ -arguments.length+" arguments.";}var n=this instanceof g?this:a.isArray?[]:new g(i);x({method:a.method,url:k.url(o({},f(i,a.params||{}),j)),data:i}).then(function(b){var c=b.data;if(c)a.isArray?(n.length=0,h(c,function(a){n.push(new g(a))})):v(c,n);(l||p)(n,b.headers)},q);return n};g.prototype["$"+b]=function(a,d,h){var m=f(this),j=p,i;switch(arguments.length){case 3:m=a;j=d;i=h;break;case 2:case 1:r(a)?(j=a,i=d):(m=a,j=d||p);case 0:break;default:throw"Expected between 1-3 arguments [params, success, error], got "+ -arguments.length+" arguments.";}g[b].call(this,m,e?this:w,j,i)}});g.bind=function(d){return u(b,o({},e,d),a)};return g}var A={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}},p=d.noop,h=d.forEach,o=d.extend,v=d.copy,r=d.isFunction;t.prototype={url:function(b){var e=this,a=this.template,f,g,b=b||{};h(this.urlParams,function(h,c){f=b.hasOwnProperty(c)?b[c]:e.defaults[c];d.isDefined(f)&&f!==null?(g=s(f,!0).replace(/%26/gi,"&").replace(/%3D/gi, -"=").replace(/%2B/gi,"+"),a=a.replace(RegExp(":"+c+"(\\W)","g"),g+"$1")):a=a.replace(RegExp("(/?):"+c+"(\\W)","g"),function(a,b,c){return c.charAt(0)=="/"?c:b+c})});var a=a.replace(/\/?#$/,""),k=[];h(b,function(a,b){e.urlParams[b]||k.push(s(b)+"="+s(a))});k.sort();a=a.replace(/\/*$/,"");return a+(k.length?"?"+k.join("&"):"")}};return u}])})(window,window.angular); +(function(H,a,A){'use strict';function D(p,g){g=g||{};a.forEach(g,function(a,c){delete g[c]});for(var c in p)!p.hasOwnProperty(c)||"$"===c.charAt(0)&&"$"===c.charAt(1)||(g[c]=p[c]);return g}var v=a.$$minErr("$resource"),C=/^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;a.module("ngResource",["ng"]).factory("$resource",["$http","$q",function(p,g){function c(a,c){this.template=a;this.defaults=c||{};this.urlParams={}}function t(n,w,l){function r(h,d){var e={};d=x({},w,d);s(d,function(b,d){u(b)&&(b=b());var k;if(b&& +b.charAt&&"@"==b.charAt(0)){k=h;var a=b.substr(1);if(null==a||""===a||"hasOwnProperty"===a||!C.test("."+a))throw v("badmember",a);for(var a=a.split("."),f=0,c=a.length;f + */ + /* global -ngRouteModule */ +var ngRouteModule = angular.module('ngRoute', ['ng']). + provider('$route', $RouteProvider); + +/** + * @ngdoc provider + * @name $routeProvider + * @kind function + * + * @description + * + * Used for configuring routes. + * + * ## Example + * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. + * + * ## Dependencies + * Requires the {@link ngRoute `ngRoute`} module to be installed. + */ +function $RouteProvider(){ + function inherit(parent, extra) { + return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); + } + + var routes = {}; + + /** + * @ngdoc method + * @name $routeProvider#when + * + * @param {string} path Route path (matched against `$location.path`). If `$location.path` + * contains redundant trailing slash or is missing one, the route will still match and the + * `$location.path` will be updated to add or drop the trailing slash to exactly match the + * route definition. + * + * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up + * to the next slash are matched and stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain named groups starting with a colon and ending with a star: + * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain optional named groups with a question mark: e.g.`:name?`. + * + * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match + * `/color/brown/largecode/code/with/slashes/edit` and extract: + * + * * `color: brown` + * * `largecode: code/with/slashes`. + * + * + * @param {Object} route Mapping information to be assigned to `$route.current` on route + * match. + * + * Object properties: + * + * - `controller` – `{(string|function()=}` – Controller fn that should be associated with + * newly created scope or the name of a {@link angular.Module#controller registered + * controller} if passed as a string. + * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be + * published to scope under the `controllerAs` name. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used by {@link + * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. + * This property takes precedence over `templateUrl`. + * + * If `template` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used by {@link ngRoute.directive:ngView ngView}. + * + * If `templateUrl` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `resolve` - `{Object.=}` - An optional map of dependencies which should + * be injected into the controller. If any of these dependencies are promises, the router + * will wait for them all to be resolved or one to be rejected before the controller is + * instantiated. + * If all the promises are resolved successfully, the values of the resolved promises are + * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is + * fired. If any of the promises are rejected the + * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object + * is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|function}`: If `string` then it is an alias for a service. + * Otherwise if function, then it is {@link auto.$injector#invoke injected} + * and the return value is treated as the dependency. If the result is a promise, it is + * resolved before its value is injected into the controller. Be aware that + * `ngRoute.$routeParams` will still refer to the previous route within these resolve + * functions. Use `$route.current.params` to access the new route parameters, instead. + * + * - `redirectTo` – {(string|function())=} – value to update + * {@link ng.$location $location} path with and trigger route redirection. + * + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current + * `$location.path()` by applying the current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used + * to update `$location.path()` and `$location.search()`. + * + * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` + * or `$location.hash()` changes. + * + * If the option is set to `false` and url in the browser changes, then + * `$routeUpdate` event is broadcasted on the root scope. + * + * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive + * + * If the option is set to `true`, then the particular route can be matched without being + * case sensitive + * + * @returns {Object} self + * + * @description + * Adds a new route definition to the `$route` service. + */ + this.when = function(path, route) { + routes[path] = angular.extend( + {reloadOnSearch: true}, + route, + path && pathRegExp(path, route) + ); + + // create redirection for trailing slashes + if (path) { + var redirectPath = (path[path.length-1] == '/') + ? path.substr(0, path.length-1) + : path +'/'; + + routes[redirectPath] = angular.extend( + {redirectTo: path}, + pathRegExp(redirectPath, route) + ); + } + + return this; + }; + + /** + * @param path {string} path + * @param opts {Object} options + * @return {?Object} + * + * @description + * Normalizes the given path, returning a regular expression + * and the original path. + * + * Inspired by pathRexp in visionmedia/express/lib/utils.js. + */ + function pathRegExp(path, opts) { + var insensitive = opts.caseInsensitiveMatch, + ret = { + originalPath: path, + regexp: path + }, + keys = ret.keys = []; + + path = path + .replace(/([().])/g, '\\$1') + .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ + var optional = option === '?' ? option : null; + var star = option === '*' ? option : null; + keys.push({ name: key, optional: !!optional }); + slash = slash || ''; + return '' + + (optional ? '' : slash) + + '(?:' + + (optional ? slash : '') + + (star && '(.+?)' || '([^/]+)') + + (optional || '') + + ')' + + (optional || ''); + }) + .replace(/([\/$\*])/g, '\\$1'); + + ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); + return ret; + } + + /** + * @ngdoc method + * @name $routeProvider#otherwise + * + * @description + * Sets route definition that will be used on route change when no other route definition + * is matched. + * + * @param {Object} params Mapping information to be assigned to `$route.current`. + * @returns {Object} self + */ + this.otherwise = function(params) { + this.when(null, params); + return this; + }; + + + this.$get = ['$rootScope', + '$location', + '$routeParams', + '$q', + '$injector', + '$http', + '$templateCache', + '$sce', + function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { + + /** + * @ngdoc service + * @name $route + * @requires $location + * @requires $routeParams + * + * @property {Object} current Reference to the current route definition. + * The route definition contains: + * + * - `controller`: The controller constructor as define in route definition. + * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for + * controller instantiation. The `locals` contain + * the resolved values of the `resolve` map. Additionally the `locals` also contain: + * + * - `$scope` - The current route scope. + * - `$template` - The current route template HTML. + * + * @property {Object} routes Object with all route configuration Objects as its properties. + * + * @description + * `$route` is used for deep-linking URLs to controllers and views (HTML partials). + * It watches `$location.url()` and tries to map the path to an existing route definition. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. + * + * The `$route` service is typically used in conjunction with the + * {@link ngRoute.directive:ngView `ngView`} directive and the + * {@link ngRoute.$routeParams `$routeParams`} service. + * + * @example + * This example shows how changing the URL hash causes the `$route` to match a route against the + * URL, and the `ngView` pulls in the partial. + * + * Note that this example is using {@link ng.directive:script inlined templates} + * to get it working on jsfiddle as well. + * + * + * + *
    + * Choose: + * Moby | + * Moby: Ch1 | + * Gatsby | + * Gatsby: Ch4 | + * Scarlet Letter
    + * + *
    + * + *
    + * + *
    $location.path() = {{$location.path()}}
    + *
    $route.current.templateUrl = {{$route.current.templateUrl}}
    + *
    $route.current.params = {{$route.current.params}}
    + *
    $route.current.scope.name = {{$route.current.scope.name}}
    + *
    $routeParams = {{$routeParams}}
    + *
    + *
    + * + * + * controller: {{name}}
    + * Book Id: {{params.bookId}}
    + *
    + * + * + * controller: {{name}}
    + * Book Id: {{params.bookId}}
    + * Chapter Id: {{params.chapterId}} + *
    + * + * + * angular.module('ngRouteExample', ['ngRoute']) + * + * .controller('MainController', function($scope, $route, $routeParams, $location) { + * $scope.$route = $route; + * $scope.$location = $location; + * $scope.$routeParams = $routeParams; + * }) + * + * .controller('BookController', function($scope, $routeParams) { + * $scope.name = "BookController"; + * $scope.params = $routeParams; + * }) + * + * .controller('ChapterController', function($scope, $routeParams) { + * $scope.name = "ChapterController"; + * $scope.params = $routeParams; + * }) + * + * .config(function($routeProvider, $locationProvider) { + * $routeProvider + * .when('/Book/:bookId', { + * templateUrl: 'book.html', + * controller: 'BookController', + * resolve: { + * // I will cause a 1 second delay + * delay: function($q, $timeout) { + * var delay = $q.defer(); + * $timeout(delay.resolve, 1000); + * return delay.promise; + * } + * } + * }) + * .when('/Book/:bookId/ch/:chapterId', { + * templateUrl: 'chapter.html', + * controller: 'ChapterController' + * }); + * + * // configure html5 to get links working on jsfiddle + * $locationProvider.html5Mode(true); + * }); + * + * + * + * + * it('should load and compile correct template', function() { + * element(by.linkText('Moby: Ch1')).click(); + * var content = element(by.css('[ng-view]')).getText(); + * expect(content).toMatch(/controller\: ChapterController/); + * expect(content).toMatch(/Book Id\: Moby/); + * expect(content).toMatch(/Chapter Id\: 1/); + * + * element(by.partialLinkText('Scarlet')).click(); + * + * content = element(by.css('[ng-view]')).getText(); + * expect(content).toMatch(/controller\: BookController/); + * expect(content).toMatch(/Book Id\: Scarlet/); + * }); + * + *
    + */ + + /** + * @ngdoc event + * @name $route#$routeChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a route change. At this point the route services starts + * resolving all of the dependencies needed for the route change to occur. + * Typically this involves fetching the view template as well as any dependencies + * defined in `resolve` route property. Once all of the dependencies are resolved + * `$routeChangeSuccess` is fired. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} next Future route information. + * @param {Route} current Current route information. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a route dependencies are resolved. + * {@link ngRoute.directive:ngView ngView} listens for the directive + * to instantiate the controller and render the view. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} current Current route information. + * @param {Route|Undefined} previous Previous route information, or undefined if current is + * first route entered. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeError + * @eventType broadcast on root scope + * @description + * Broadcasted if any of the resolve promises are rejected. + * + * @param {Object} angularEvent Synthetic event object + * @param {Route} current Current route information. + * @param {Route} previous Previous route information. + * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. + */ + + /** + * @ngdoc event + * @name $route#$routeUpdate + * @eventType broadcast on root scope + * @description + * + * The `reloadOnSearch` property has been set to false, and we are reusing the same + * instance of the Controller. + */ + + var forceReload = false, + $route = { + routes: routes, + + /** + * @ngdoc method + * @name $route#reload + * + * @description + * Causes `$route` service to reload the current route even if + * {@link ng.$location $location} hasn't changed. + * + * As a result of that, {@link ngRoute.directive:ngView ngView} + * creates new scope, reinstantiates the controller. + */ + reload: function() { + forceReload = true; + $rootScope.$evalAsync(updateRoute); + } + }; + + $rootScope.$on('$locationChangeSuccess', updateRoute); + + return $route; + + ///////////////////////////////////////////////////// + + /** + * @param on {string} current url + * @param route {Object} route regexp to match the url against + * @return {?Object} + * + * @description + * Check if the route matches the current url. + * + * Inspired by match in + * visionmedia/express/lib/router/router.js. + */ + function switchRouteMatcher(on, route) { + var keys = route.keys, + params = {}; + + if (!route.regexp) return null; + + var m = route.regexp.exec(on); + if (!m) return null; + + for (var i = 1, len = m.length; i < len; ++i) { + var key = keys[i - 1]; + + var val = m[i]; + + if (key && val) { + params[key.name] = val; + } + } + return params; + } + + function updateRoute() { + var next = parseRoute(), + last = $route.current; + + if (next && last && next.$$route === last.$$route + && angular.equals(next.pathParams, last.pathParams) + && !next.reloadOnSearch && !forceReload) { + last.params = next.params; + angular.copy(last.params, $routeParams); + $rootScope.$broadcast('$routeUpdate', last); + } else if (next || last) { + forceReload = false; + $rootScope.$broadcast('$routeChangeStart', next, last); + $route.current = next; + if (next) { + if (next.redirectTo) { + if (angular.isString(next.redirectTo)) { + $location.path(interpolate(next.redirectTo, next.params)).search(next.params) + .replace(); + } else { + $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) + .replace(); + } + } + } + + $q.when(next). + then(function() { + if (next) { + var locals = angular.extend({}, next.resolve), + template, templateUrl; + + angular.forEach(locals, function(value, key) { + locals[key] = angular.isString(value) ? + $injector.get(value) : $injector.invoke(value); + }); + + if (angular.isDefined(template = next.template)) { + if (angular.isFunction(template)) { + template = template(next.params); + } + } else if (angular.isDefined(templateUrl = next.templateUrl)) { + if (angular.isFunction(templateUrl)) { + templateUrl = templateUrl(next.params); + } + templateUrl = $sce.getTrustedResourceUrl(templateUrl); + if (angular.isDefined(templateUrl)) { + next.loadedTemplateUrl = templateUrl; + template = $http.get(templateUrl, {cache: $templateCache}). + then(function(response) { return response.data; }); + } + } + if (angular.isDefined(template)) { + locals['$template'] = template; + } + return $q.all(locals); + } + }). + // after route change + then(function(locals) { + if (next == $route.current) { + if (next) { + next.locals = locals; + angular.copy(next.params, $routeParams); + } + $rootScope.$broadcast('$routeChangeSuccess', next, last); + } + }, function(error) { + if (next == $route.current) { + $rootScope.$broadcast('$routeChangeError', next, last, error); + } + }); + } + } + + + /** + * @returns {Object} the current active route, by matching it against the URL + */ + function parseRoute() { + // Match a route + var params, match; + angular.forEach(routes, function(route, path) { + if (!match && (params = switchRouteMatcher($location.path(), route))) { + match = inherit(route, { + params: angular.extend({}, $location.search(), params), + pathParams: params}); + match.$$route = route; + } + }); + // No route matched; fallback to "otherwise" route + return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); + } + + /** + * @returns {string} interpolation of the redirect path with the parameters + */ + function interpolate(string, params) { + var result = []; + angular.forEach((string||'').split(':'), function(segment, i) { + if (i === 0) { + result.push(segment); + } else { + var segmentMatch = segment.match(/(\w+)(.*)/); + var key = segmentMatch[1]; + result.push(params[key]); + result.push(segmentMatch[2] || ''); + delete params[key]; + } + }); + return result.join(''); + } + }]; +} + +ngRouteModule.provider('$routeParams', $RouteParamsProvider); + + +/** + * @ngdoc service + * @name $routeParams + * @requires $route + * + * @description + * The `$routeParams` service allows you to retrieve the current set of route parameters. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * The route parameters are a combination of {@link ng.$location `$location`}'s + * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. + * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. + * + * In case of parameter name collision, `path` params take precedence over `search` params. + * + * The service guarantees that the identity of the `$routeParams` object will remain unchanged + * (but its properties will likely change) even when a route change occurs. + * + * Note that the `$routeParams` are only updated *after* a route change completes successfully. + * This means that you cannot rely on `$routeParams` being correct in route resolve functions. + * Instead you can use `$route.current.params` to access the new route's parameters. + * + * @example + * ```js + * // Given: + * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby + * // Route: /Chapter/:chapterId/Section/:sectionId + * // + * // Then + * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} + * ``` + */ +function $RouteParamsProvider() { + this.$get = function() { return {}; }; +} + +ngRouteModule.directive('ngView', ngViewFactory); +ngRouteModule.directive('ngView', ngViewFillContentFactory); + + +/** + * @ngdoc directive + * @name ngView + * @restrict ECA + * + * @description + * # Overview + * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by + * including the rendered template of the current route into the main layout (`index.html`) file. + * Every time the current route changes, the included view changes with it according to the + * configuration of the `$route` service. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * @priority 400 + * @param {string=} onload Expression to evaluate whenever the view updates. + * + * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the view is updated. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated + * as an expression yields a truthy value. + * @example + + +
    + Choose: + Moby | + Moby: Ch1 | + Gatsby | + Gatsby: Ch4 | + Scarlet Letter
    + +
    +
    +
    +
    + +
    $location.path() = {{main.$location.path()}}
    +
    $route.current.templateUrl = {{main.$route.current.templateUrl}}
    +
    $route.current.params = {{main.$route.current.params}}
    +
    $route.current.scope.name = {{main.$route.current.scope.name}}
    +
    $routeParams = {{main.$routeParams}}
    +
    +
    + + +
    + controller: {{book.name}}
    + Book Id: {{book.params.bookId}}
    +
    +
    + + +
    + controller: {{chapter.name}}
    + Book Id: {{chapter.params.bookId}}
    + Chapter Id: {{chapter.params.chapterId}} +
    +
    + + + .view-animate-container { + position:relative; + height:100px!important; + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .view-animate { + padding:10px; + } + + .view-animate.ng-enter, .view-animate.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + + display:block; + width:100%; + border-left:1px solid black; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + padding:10px; + } + + .view-animate.ng-enter { + left:100%; + } + .view-animate.ng-enter.ng-enter-active { + left:0; + } + .view-animate.ng-leave.ng-leave-active { + left:-100%; + } + + + + angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) + .config(['$routeProvider', '$locationProvider', + function($routeProvider, $locationProvider) { + $routeProvider + .when('/Book/:bookId', { + templateUrl: 'book.html', + controller: 'BookCtrl', + controllerAs: 'book' + }) + .when('/Book/:bookId/ch/:chapterId', { + templateUrl: 'chapter.html', + controller: 'ChapterCtrl', + controllerAs: 'chapter' + }); + + // configure html5 to get links working on jsfiddle + $locationProvider.html5Mode(true); + }]) + .controller('MainCtrl', ['$route', '$routeParams', '$location', + function($route, $routeParams, $location) { + this.$route = $route; + this.$location = $location; + this.$routeParams = $routeParams; + }]) + .controller('BookCtrl', ['$routeParams', function($routeParams) { + this.name = "BookCtrl"; + this.params = $routeParams; + }]) + .controller('ChapterCtrl', ['$routeParams', function($routeParams) { + this.name = "ChapterCtrl"; + this.params = $routeParams; + }]); + + + + + it('should load and compile correct template', function() { + element(by.linkText('Moby: Ch1')).click(); + var content = element(by.css('[ng-view]')).getText(); + expect(content).toMatch(/controller\: ChapterCtrl/); + expect(content).toMatch(/Book Id\: Moby/); + expect(content).toMatch(/Chapter Id\: 1/); + + element(by.partialLinkText('Scarlet')).click(); + + content = element(by.css('[ng-view]')).getText(); + expect(content).toMatch(/controller\: BookCtrl/); + expect(content).toMatch(/Book Id\: Scarlet/); + }); + +
    + */ + + +/** + * @ngdoc event + * @name ngView#$viewContentLoaded + * @eventType emit on the current ngView scope + * @description + * Emitted every time the ngView content is reloaded. + */ +ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; +function ngViewFactory( $route, $anchorScroll, $animate) { + return { + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + link: function(scope, $element, attr, ctrl, $transclude) { + var currentScope, + currentElement, + previousElement, + autoScrollExp = attr.autoscroll, + onloadExp = attr.onload || ''; + + scope.$on('$routeChangeSuccess', update); + update(); + + function cleanupLastView() { + if(previousElement) { + previousElement.remove(); + previousElement = null; + } + if(currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement, function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + } + + function update() { + var locals = $route.current && $route.current.locals, + template = locals && locals.$template; + + if (angular.isDefined(template)) { + var newScope = scope.$new(); + var current = $route.current; + + // Note: This will also link all children of ng-view that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-view on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { + if (angular.isDefined(autoScrollExp) + && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }); + cleanupLastView(); + }); + + currentElement = clone; + currentScope = current.scope = newScope; + currentScope.$emit('$viewContentLoaded'); + currentScope.$eval(onloadExp); + } else { + cleanupLastView(); + } + } + } + }; +} + +// This directive is called during the $transclude call of the first `ngView` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngView +// is called. +ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; +function ngViewFillContentFactory($compile, $controller, $route) { + return { + restrict: 'ECA', + priority: -400, + link: function(scope, $element) { + var current = $route.current, + locals = current.locals; + + $element.html(locals.$template); + + var link = $compile($element.contents()); + + if (current.controller) { + locals.$scope = scope; + var controller = $controller(current.controller, locals); + if (current.controllerAs) { + scope[current.controllerAs] = controller; + } + $element.data('$ngControllerController', controller); + $element.children().data('$ngControllerController', controller); + } + + link(scope); + } + }; +} + + +})(window, window.angular); diff --git a/public/js/lib/angular/angular-route.min.js b/public/js/lib/angular/angular-route.min.js new file mode 100644 index 000000000..8b3d39bea --- /dev/null +++ b/public/js/lib/angular/angular-route.min.js @@ -0,0 +1,14 @@ +/* + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(n,e,A){'use strict';function x(s,g,h){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,w){function y(){p&&(p.remove(),p=null);k&&(k.$destroy(),k=null);l&&(h.leave(l,function(){p=null}),p=l,l=null)}function v(){var b=s.current&&s.current.locals;if(e.isDefined(b&&b.$template)){var b=a.$new(),d=s.current;l=w(b,function(d){h.enter(d,null,l||c,function(){!e.isDefined(t)||t&&!a.$eval(t)||g()});y()});k=d.scope=b;k.$emit("$viewContentLoaded");k.$eval(u)}else y()} +var k,l,p,t=b.autoscroll,u=b.onload||"";a.$on("$routeChangeSuccess",v);v()}}}function z(e,g,h){return{restrict:"ECA",priority:-400,link:function(a,c){var b=h.current,f=b.locals;c.html(f.$template);var w=e(c.contents());b.controller&&(f.$scope=a,f=g(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));w(a)}}}n=e.module("ngRoute",["ng"]).provider("$route",function(){function s(a,c){return e.extend(new (e.extend(function(){}, +{prototype:a})),c)}function g(a,e){var b=e.caseInsensitiveMatch,f={originalPath:a,regexp:a},h=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,e,b,c){a="?"===c?c:null;c="*"===c?c:null;h.push({name:b,optional:!!a});e=e||"";return""+(a?"":e)+"(?:"+(a?e:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=RegExp("^"+a+"$",b?"i":"");return f}var h={};this.when=function(a,c){h[a]=e.extend({reloadOnSearch:!0},c,a&&g(a,c));if(a){var b= +"/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";h[b]=e.extend({redirectTo:a},g(b,c))}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,b,f,g,n,v,k){function l(){var d=p(),m=r.current;if(d&&m&&d.$$route===m.$$route&&e.equals(d.pathParams,m.pathParams)&&!d.reloadOnSearch&&!u)m.params=d.params,e.copy(m.params,b),a.$broadcast("$routeUpdate",m);else if(d||m)u=!1,a.$broadcast("$routeChangeStart", +d,m),(r.current=d)&&d.redirectTo&&(e.isString(d.redirectTo)?c.path(t(d.redirectTo,d.params)).search(d.params).replace():c.url(d.redirectTo(d.pathParams,c.path(),c.search())).replace()),f.when(d).then(function(){if(d){var a=e.extend({},d.resolve),c,b;e.forEach(a,function(d,c){a[c]=e.isString(d)?g.get(d):g.invoke(d)});e.isDefined(c=d.template)?e.isFunction(c)&&(c=c(d.params)):e.isDefined(b=d.templateUrl)&&(e.isFunction(b)&&(b=b(d.params)),b=k.getTrustedResourceUrl(b),e.isDefined(b)&&(d.loadedTemplateUrl= +b,c=n.get(b,{cache:v}).then(function(a){return a.data})));e.isDefined(c)&&(a.$template=c);return f.all(a)}}).then(function(c){d==r.current&&(d&&(d.locals=c,e.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,m))},function(c){d==r.current&&a.$broadcast("$routeChangeError",d,m,c)})}function p(){var a,b;e.forEach(h,function(f,h){var q;if(q=!b){var g=c.path();q=f.keys;var l={};if(f.regexp)if(g=f.regexp.exec(g)){for(var k=1,p=g.length;k + * + * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* @@ -31,8 +41,8 @@ /** * @ngdoc service - * @name ngSanitize.$sanitize - * @function + * @name $sanitize + * @kind function * * @description * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are @@ -40,97 +50,126 @@ * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. + * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and + * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html Html input. * @returns {string} Sanitized html. * * @example - - - -
    - Snippet: - - - - - - - - - - - - - - - - - - - - - -
    FilterSourceRendered
    html filter -
    <div ng-bind-html="snippet">
    </div>
    -
    -
    -
    no filter
    <div ng-bind="snippet">
    </div>
    unsafe html filter
    <div ng-bind-html-unsafe="snippet">
    </div>
    -
    -
    - - it('should sanitize the html snippet ', function() { - expect(using('#html-filter').element('div').html()). - toBe('

    an html\nclick here\nsnippet

    '); - }); - - it('should escape snippet without any filter', function() { - expect(using('#escaped-html').element('div').html()). - toBe("<p style=\"color:blue\">an html\n" + - "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + - "snippet</p>"); - }); - - it('should inline raw snippet if filtered as unsafe', function() { - expect(using('#html-unsafe-filter').element("div").html()). - toBe("

    an html\n" + - "click here\n" + - "snippet

    "); - }); - - it('should update', function() { - input('snippet').enter('new text'); - expect(using('#html-filter').binding('snippet')).toBe('new text'); - expect(using('#escaped-html').element('div').html()).toBe("new <b>text</b>"); - expect(using('#html-unsafe-filter').binding("snippet")).toBe('new text'); - }); -
    -
    + + + +
    + Snippet: + + + + + + + + + + + + + + + + + + + + + + + + + +
    DirectiveHowSourceRendered
    ng-bind-htmlAutomatically uses $sanitize
    <div ng-bind-html="snippet">
    </div>
    ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value +
    <div ng-bind-html="deliberatelyTrustDangerousSnippet()">
    +</div>
    +
    ng-bindAutomatically escapes
    <div ng-bind="snippet">
    </div>
    +
    +
    + + it('should sanitize the html snippet by default', function() { + expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + toBe('

    an html\nclick here\nsnippet

    '); + }); + + it('should inline raw snippet if bound to a trusted value', function() { + expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). + toBe("

    an html\n" + + "click here\n" + + "snippet

    "); + }); + + it('should escape snippet without any filter', function() { + expect(element(by.css('#bind-default div')).getInnerHtml()). + toBe("<p style=\"color:blue\">an html\n" + + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + + "snippet</p>"); + }); + + it('should update', function() { + element(by.model('snippet')).clear(); + element(by.model('snippet')).sendKeys('new text'); + expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + toBe('new text'); + expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( + 'new text'); + expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( + "new <b onclick=\"alert(1)\">text</b>"); + }); +
    +
    */ -var $sanitize = function(html) { +function $SanitizeProvider() { + this.$get = ['$$sanitizeUri', function($$sanitizeUri) { + return function(html) { + var buf = []; + htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { + return !/^unsafe/.test($$sanitizeUri(uri, isImage)); + })); + return buf.join(''); + }; + }]; +} + +function sanitizeText(chars) { var buf = []; - htmlParser(html, htmlSanitizeWriter(buf)); - return buf.join(''); -}; + var writer = htmlSanitizeWriter(buf, angular.noop); + writer.chars(chars); + return buf.join(''); +} // Regular Expressions for parsing tags and attributes -var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, - END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, +var START_TAG_REGEXP = + /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/, + END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^/g, + DOCTYPE_REGEXP = /]*?)>/i, CDATA_REGEXP = //g, - URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, - NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) + SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, + // Match everything outside of normal chars and " (quote character) + NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes @@ -145,23 +184,29 @@ var voidElements = makeMap("area,br,col,hr,img,wbr"); // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), - optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); + optionalEndTagElements = angular.extend({}, + optionalEndTagInlineElements, + optionalEndTagBlockElements); // Safe Block Elements - HTML5 -var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + - "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + - "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); +var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 -var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + - "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + - "span,strike,strong,sub,sup,time,tt,u,var")); +var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); -var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); +var validElements = angular.extend({}, + voidElements, + blockElements, + inlineElements, + optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); @@ -169,7 +214,7 @@ var validAttrs = angular.extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ - 'scope,scrolling,shape,span,start,summary,target,title,type,'+ + 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); function makeMap(str) { @@ -192,10 +237,18 @@ function makeMap(str) { * @param {object} handler */ function htmlParser( html, handler ) { - var index, chars, match, stack = [], last = html; + if (typeof html !== 'string') { + if (html === null || typeof html === 'undefined') { + html = ''; + } else { + html = '' + html; + } + } + var index, chars, match, stack = [], last = html, text; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { + text = ''; chars = true; // Make sure we're not in a script or style element @@ -203,14 +256,22 @@ function htmlParser( html, handler ) { // Comment if ( html.indexOf(""); + // comments containing -- are not allowed unless they terminate the comment + index = html.indexOf("--", 4); - if ( index >= 0 ) { + if ( index >= 0 && html.lastIndexOf("-->", index) === index) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } + // DOCTYPE + } else if ( DOCTYPE_REGEXP.test(html) ) { + match = html.match( DOCTYPE_REGEXP ); + if ( match ) { + html = html.replace( match[0], ''); + chars = false; + } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); @@ -226,37 +287,44 @@ function htmlParser( html, handler ) { match = html.match( START_TAG_REGEXP ); if ( match ) { - html = html.substring( match[0].length ); - match[0].replace( START_TAG_REGEXP, parseStartTag ); + // We only have a valid start-tag if there is a '>'. + if ( match[4] ) { + html = html.substring( match[0].length ); + match[0].replace( START_TAG_REGEXP, parseStartTag ); + } chars = false; + } else { + // no ending tag found --- this piece should be encoded as an entity. + text += '<'; + html = html.substring(1); } } if ( chars ) { index = html.indexOf("<"); - var text = index < 0 ? html : html.substring( 0, index ); + text += index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { - html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ - text = text. - replace(COMMENT_REGEXP, "$1"). - replace(CDATA_REGEXP, "$1"); + html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), + function(all, text){ + text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); - if (handler.chars) handler.chars( decodeEntities(text) ); + if (handler.chars) handler.chars( decodeEntities(text) ); - return ""; + return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { - throw "Parse Error: " + html; + throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + + "of html: {0}", html); } last = html; } @@ -283,13 +351,14 @@ function htmlParser( html, handler ) { var attrs = {}; - rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { - var value = doubleQuotedValue - || singleQoutedValue - || unqoutedValue - || ''; + rest.replace(ATTR_REGEXP, + function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { + var value = doubleQuotedValue + || singleQuotedValue + || unquotedValue + || ''; - attrs[name] = decodeEntities(value); + attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } @@ -314,15 +383,32 @@ function htmlParser( html, handler ) { } } +var hiddenPre=document.createElement("pre"); +var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ -var hiddenPre=document.createElement("pre"); function decodeEntities(value) { - hiddenPre.innerHTML=value.replace(/ * * @example - - + + -
    +
    Snippet: @@ -468,52 +545,66 @@ angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($san
    + + + + +
    linky target +
    <div ng-bind-html="snippetWithTarget | linky:'_blank'">
    </div>
    +
    +
    +
    no filter
    <div ng-bind="snippet">
    </div>
    - - + + it('should linkify the snippet with urls', function() { - expect(using('#linky-filter').binding('snippet | linky')). - toBe('Pretty text with some links: ' + - 'http://angularjs.org/, ' + - 'us@somewhere.org, ' + - 'another@somewhere.org, ' + - 'and one more: ftp://127.0.0.1/.'); + expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). + toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); + expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); - it ('should not linkify snippet without the linky filter', function() { - expect(using('#escaped-html').binding('snippet')). - toBe("Pretty text with some links:\n" + - "http://angularjs.org/,\n" + - "mailto:us@somewhere.org,\n" + - "another@somewhere.org,\n" + - "and one more: ftp://127.0.0.1/."); + it('should not linkify snippet without the linky filter', function() { + expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). + toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); + expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { - input('snippet').enter('new http://link.'); - expect(using('#linky-filter').binding('snippet | linky')). - toBe('new http://link.'); - expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); + element(by.model('snippet')).clear(); + element(by.model('snippet')).sendKeys('new http://link.'); + expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). + toBe('new http://link.'); + expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); + expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) + .toBe('new http://link.'); + }); + + it('should work with the target property', function() { + expect(element(by.id('linky-target')). + element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). + toBe('http://angularjs.org/'); + expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); - - + + */ -angular.module('ngSanitize').filter('linky', function() { - var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/, +angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { + var LINKY_URL_REGEXP = + /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, MAILTO_REGEXP = /^mailto:/; - return function(text) { + return function(text, target) { if (!text) return text; var match; var raw = text; var html = []; - // TODO(vojta): use $sanitize instead - var writer = htmlSanitizeWriter(html); var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { @@ -522,16 +613,35 @@ angular.module('ngSanitize').filter('linky', function() { // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; - writer.chars(raw.substr(0, i)); - writer.start('a', {href:url}); - writer.chars(match[0].replace(MAILTO_REGEXP, '')); - writer.end('a'); + addText(raw.substr(0, i)); + addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } - writer.chars(raw); - return html.join(''); + addText(raw); + return $sanitize(html.join('')); + + function addText(text) { + if (!text) { + return; + } + html.push(sanitizeText(text)); + } + + function addLink(url, text) { + html.push(''); + addText(text); + html.push(''); + } }; -}); +}]); })(window, window.angular); diff --git a/public/js/lib/angular/angular-sanitize.min.js b/public/js/lib/angular/angular-sanitize.min.js index dbe1d1388..5cd583689 100644 --- a/public/js/lib/angular/angular-sanitize.min.js +++ b/public/js/lib/angular/angular-sanitize.min.js @@ -1,13 +1,15 @@ /* - AngularJS v1.0.7 - (c) 2010-2012 Google, Inc. http://angularjs.org + AngularJS v1.2.22 + (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ -(function(I,g){'use strict';function i(a){var d={},a=a.split(","),b;for(b=0;b=0;e--)if(f[e]==b)break;if(e>=0){for(c=f.length-1;c>=e;c--)d.end&&d.end(f[c]);f.length= -e}}var c,h,f=[],j=a;for(f.last=function(){return f[f.length-1]};a;){h=!0;if(!f.last()||!q[f.last()]){if(a.indexOf("<\!--")===0)c=a.indexOf("--\>"),c>=0&&(d.comment&&d.comment(a.substring(4,c)),a=a.substring(c+3),h=!1);else if(B.test(a)){if(c=a.match(r))a=a.substring(c[0].length),c[0].replace(r,e),h=!1}else if(C.test(a)&&(c=a.match(s)))a=a.substring(c[0].length),c[0].replace(s,b),h=!1;h&&(c=a.indexOf("<"),h=c<0?a:a.substring(0,c),a=c<0?"":a.substring(c),d.chars&&d.chars(k(h)))}else a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+ -f.last()+"[^>]*>","i"),function(b,a){a=a.replace(D,"$1").replace(E,"$1");d.chars&&d.chars(k(a));return""}),e("",f.last());if(a==j)throw"Parse Error: "+a;j=a}e()}function k(a){l.innerHTML=a.replace(//g,">")}function u(a){var d=!1,b=g.bind(a,a.push);return{start:function(a,c,h){a=g.lowercase(a);!d&&q[a]&&(d=a);!d&&v[a]== -!0&&(b("<"),b(a),g.forEach(c,function(a,c){var e=g.lowercase(c);if(G[e]==!0&&(w[e]!==!0||a.match(H)))b(" "),b(c),b('="'),b(t(a)),b('"')}),b(h?"/>":">"))},end:function(a){a=g.lowercase(a);!d&&v[a]==!0&&(b(""));a==d&&(d=!1)},chars:function(a){d||b(t(a))}}}var s=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,r=/^<\s*\/\s*([\w:-]+)[^>]*>/,A=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,C=/^/g, -E=//g,H=/^((ftp|https?):\/\/|mailto:|#)/,F=/([^\#-~| |!])/g,p=i("area,br,col,hr,img,wbr"),x=i("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),y=i("rp,rt"),o=g.extend({},y,x),m=g.extend({},x,i("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")),n=g.extend({},y,i("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")), -q=i("script,style"),v=g.extend({},p,m,n,o),w=i("background,cite,href,longdesc,src,usemap"),G=g.extend({},w,i("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,span,start,summary,target,title,type,valign,value,vspace,width")),l=document.createElement("pre");g.module("ngSanitize",[]).value("$sanitize",function(a){var d=[]; -z(a,u(d));return d.join("")});g.module("ngSanitize").directive("ngBindHtml",["$sanitize",function(a){return function(d,b,e){b.addClass("ng-binding").data("$binding",e.ngBindHtml);d.$watch(e.ngBindHtml,function(c){c=a(c);b.html(c||"")})}}]);g.module("ngSanitize").filter("linky",function(){var a=/((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/,d=/^mailto:/;return function(b){if(!b)return b;for(var e=b,c=[],h=u(c),f,g;b=e.match(a);)f=b[0],b[2]==b[3]&&(f="mailto:"+f),g=b.index, -h.chars(e.substr(0,g)),h.start("a",{href:f}),h.chars(b[0].replace(d,"")),h.end("a"),e=e.substring(g+b[0].length);h.chars(e);return c.join("")}})})(window,window.angular); +(function(q,g,r){'use strict';function F(a){var d=[];t(d,g.noop).chars(a);return d.join("")}function m(a){var d={};a=a.split(",");var c;for(c=0;c=c;e--)d.end&&d.end(f[e]);f.length=c}}"string"!==typeof a&&(a=null===a||"undefined"===typeof a?"":""+a);var b,l,f=[],n=a,h;for(f.last=function(){return f[f.length-1]};a;){h="";l=!0;if(f.last()&&y[f.last()])a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+f.last()+"[^>]*>","i"),function(a,b){b=b.replace(I,"$1").replace(J,"$1");d.chars&&d.chars(s(b));return""}),e("",f.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--",4),0<=b&&a.lastIndexOf("--\x3e",b)===b&&(d.comment&&d.comment(a.substring(4, +b)),a=a.substring(b+3),l=!1);else if(z.test(a)){if(b=a.match(z))a=a.replace(b[0],""),l=!1}else if(K.test(a)){if(b=a.match(A))a=a.substring(b[0].length),b[0].replace(A,e),l=!1}else L.test(a)&&((b=a.match(B))?(b[4]&&(a=a.substring(b[0].length),b[0].replace(B,c)),l=!1):(h+="<",a=a.substring(1)));l&&(b=a.indexOf("<"),h+=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),d.chars&&d.chars(s(h)))}if(a==n)throw M("badparse",a);n=a}e()}function s(a){if(!a)return"";var d=N.exec(a);a=d[1];var c=d[3];if(d=d[2])p.innerHTML= +d.replace(//g,">")}function t(a,d){var c=!1,e=g.bind(a,a.push);return{start:function(a,l,f){a=g.lowercase(a);!c&&y[a]&&(c=a);c||!0!==D[a]||(e("<"),e(a),g.forEach(l,function(c,f){var k= +g.lowercase(f),l="img"===a&&"src"===k||"background"===k;!0!==Q[k]||!0===E[k]&&!d(c,l)||(e(" "),e(f),e('="'),e(C(c)),e('"'))}),e(f?"/>":">"))},end:function(a){a=g.lowercase(a);c||!0!==D[a]||(e(""));a==c&&(c=!1)},chars:function(a){c||e(C(a))}}}var M=g.$$minErr("$sanitize"),B=/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,A=/^<\/\s*([\w:-]+)[^>]*>/,H=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,L=/^]*?)>/i,J=/]/,c=/^mailto:/;return function(e,b){function l(a){a&&k.push(F(a))}function f(a,c){k.push("');l(c);k.push("")} +if(!e)return e;for(var n,h=e,k=[],m,p;n=h.match(d);)m=n[0],n[2]==n[3]&&(m="mailto:"+m),p=n.index,l(h.substr(0,p)),f(m,n[0].replace(c,"")),h=h.substring(p+n[0].length);l(h);return a(k.join(""))}}])})(window,window.angular); +//# sourceMappingURL=angular-sanitize.min.js.map diff --git a/public/js/lib/angular/angular-sanitize.min.js.map b/public/js/lib/angular/angular-sanitize.min.js.map new file mode 100644 index 000000000..deadf39d5 --- /dev/null +++ b/public/js/lib/angular/angular-sanitize.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-sanitize.min.js", +"lineCount":14, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAkJtCC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBN,CAAAO,KAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CAoE7BC,QAASA,EAAO,CAACC,CAAD,CAAM,CAAA,IAChBC,EAAM,EAAIC,EAAAA,CAAQF,CAAAG,MAAA,CAAU,GAAV,CAAtB,KAAsCC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CAAmCH,CAAA,CAAIC,CAAA,CAAME,CAAN,CAAJ,CAAA,CAAgB,CAAA,CACnD,OAAOH,EAHa,CAmBtBK,QAASA,EAAU,CAAEC,CAAF,CAAQC,CAAR,CAAkB,CAgGnCC,QAASA,EAAa,CAAEC,CAAF,CAAOC,CAAP,CAAgBC,CAAhB,CAAsBC,CAAtB,CAA8B,CAClDF,CAAA,CAAUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,IAAKI,CAAA,CAAeJ,CAAf,CAAL,CACE,IAAA,CAAQK,CAAAC,KAAA,EAAR,EAAwBC,CAAA,CAAgBF,CAAAC,KAAA,EAAhB,CAAxB,CAAA,CACEE,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAICG,EAAA,CAAwBT,CAAxB,CAAL,EAA0CK,CAAAC,KAAA,EAA1C,EAA0DN,CAA1D,EACEQ,CAAA,CAAa,EAAb,CAAiBR,CAAjB,CAKF,EAFAE,CAEA,CAFQQ,CAAA,CAAcV,CAAd,CAER,EAFmC,CAAC,CAACE,CAErC,GACEG,CAAAM,KAAA,CAAYX,CAAZ,CAEF,KAAIY,EAAQ,EAEZX,EAAAY,QAAA,CAAaC,CAAb,CACE,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAcC,CAAd,CAAiCC,CAAjC,CAAoDC,CAApD,CAAmE,CAMzEP,CAAA,CAAMI,CAAN,CAAA,CAAcI,CAAA,CALFH,CAKE,EAJTC,CAIS,EAHTC,CAGS,EAFT,EAES,CAN2D,CAD7E,CASItB,EAAAwB,MAAJ,EAAmBxB,CAAAwB,MAAA,CAAerB,CAAf,CAAwBY,CAAxB,CAA+BV,CAA/B,CA5B+B,CA+BpDM,QAASA,EAAW,CAAET,CAAF,CAAOC,CAAP,CAAiB,CAAA,IAC/BsB,EAAM,CADyB,CACtB7B,CAEb,IADAO,CACA,CADUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,CAEE,IAAMsB,CAAN,CAAYjB,CAAAX,OAAZ,CAA2B,CAA3B,CAAqC,CAArC,EAA8B4B,CAA9B,EACOjB,CAAA,CAAOiB,CAAP,CADP,EACuBtB,CADvB,CAAwCsB,CAAA,EAAxC;AAIF,GAAY,CAAZ,EAAKA,CAAL,CAAgB,CAEd,IAAM7B,CAAN,CAAUY,CAAAX,OAAV,CAAyB,CAAzB,CAA4BD,CAA5B,EAAiC6B,CAAjC,CAAsC7B,CAAA,EAAtC,CACMI,CAAA0B,IAAJ,EAAiB1B,CAAA0B,IAAA,CAAalB,CAAA,CAAOZ,CAAP,CAAb,CAGnBY,EAAAX,OAAA,CAAe4B,CAND,CATmB,CA9HjB,QAApB,GAAI,MAAO1B,EAAX,GAEIA,CAFJ,CACe,IAAb,GAAIA,CAAJ,EAAqC,WAArC,GAAqB,MAAOA,EAA5B,CACS,EADT,CAGS,EAHT,CAGcA,CAJhB,CADmC,KAQ/B4B,CAR+B,CAQxB1C,CARwB,CAQVuB,EAAQ,EARE,CAQEC,EAAOV,CART,CAQe6B,CAGlD,KAFApB,CAAAC,KAEA,CAFaoB,QAAQ,EAAG,CAAE,MAAOrB,EAAA,CAAOA,CAAAX,OAAP,CAAsB,CAAtB,CAAT,CAExB,CAAQE,CAAR,CAAA,CAAe,CACb6B,CAAA,CAAO,EACP3C,EAAA,CAAQ,CAAA,CAGR,IAAMuB,CAAAC,KAAA,EAAN,EAAuBqB,CAAA,CAAiBtB,CAAAC,KAAA,EAAjB,CAAvB,CA0DEV,CASA,CATOA,CAAAiB,QAAA,CAAiBe,MAAJ,CAAW,kBAAX,CAAgCvB,CAAAC,KAAA,EAAhC,CAA+C,QAA/C,CAAyD,GAAzD,CAAb,CACL,QAAQ,CAACuB,CAAD,CAAMJ,CAAN,CAAW,CACjBA,CAAA,CAAOA,CAAAZ,QAAA,CAAaiB,CAAb,CAA6B,IAA7B,CAAAjB,QAAA,CAA2CkB,CAA3C,CAAyD,IAAzD,CAEHlC,EAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeK,CAAf,CAAf,CAEnB,OAAO,EALU,CADd,CASP,CAAAjB,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAnEF,KAAyD,CAGvD,GAA8B,CAA9B,GAAKV,CAAAoC,QAAA,CAAa,SAAb,CAAL,CAEER,CAEA,CAFQ5B,CAAAoC,QAAA,CAAa,IAAb,CAAmB,CAAnB,CAER,CAAc,CAAd,EAAKR,CAAL,EAAmB5B,CAAAqC,YAAA,CAAiB,QAAjB,CAAwBT,CAAxB,CAAnB,GAAsDA,CAAtD,GACM3B,CAAAqC,QAEJ,EAFqBrC,CAAAqC,QAAA,CAAiBtC,CAAAuC,UAAA,CAAgB,CAAhB;AAAmBX,CAAnB,CAAjB,CAErB,CADA5B,CACA,CADOA,CAAAuC,UAAA,CAAgBX,CAAhB,CAAwB,CAAxB,CACP,CAAA1C,CAAA,CAAQ,CAAA,CAHV,CAJF,KAUO,IAAKsD,CAAAC,KAAA,CAAoBzC,CAApB,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYqB,CAAZ,CAER,CACExC,CACA,CADOA,CAAAiB,QAAA,CAAcE,CAAA,CAAM,CAAN,CAAd,CAAwB,EAAxB,CACP,CAAAjC,CAAA,CAAQ,CAAA,CAFV,CAHK,IAQA,IAAKwD,CAAAD,KAAA,CAA4BzC,CAA5B,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYwB,CAAZ,CAER,CACE3C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB0B,CAAlB,CAAkC/B,CAAlC,CACA,CAAA1B,CAAA,CAAQ,CAAA,CAHV,CAHK,IAUK0D,EAAAH,KAAA,CAAsBzC,CAAtB,CAAL,GAGL,CAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAY0B,CAAZ,CAER,GAEO1B,CAAA,CAAM,CAAN,CAIL,GAHEnB,CACA,CADOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CACP,CAAAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB4B,CAAlB,CAAoC3C,CAApC,CAEF,EAAAhB,CAAA,CAAQ,CAAA,CANV,GASE2C,CACA,EADQ,GACR,CAAA7B,CAAA,CAAOA,CAAAuC,UAAA,CAAe,CAAf,CAVT,CAHK,CAiBFrD,EAAL,GACE0C,CAKA,CALQ5B,CAAAoC,QAAA,CAAa,GAAb,CAKR,CAHAP,CAGA,EAHgB,CAAR,CAAAD,CAAA,CAAY5B,CAAZ,CAAmBA,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAG3B,CAFA5B,CAEA,CAFe,CAAR,CAAA4B,CAAA,CAAY,EAAZ,CAAiB5B,CAAAuC,UAAA,CAAgBX,CAAhB,CAExB,CAAI3B,CAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeK,CAAf,CAAf,CANrB,CAhDuD,CAsEzD,GAAK7B,CAAL,EAAaU,CAAb,CACE,KAAMoC,EAAA,CAAgB,UAAhB,CAC4C9C,CAD5C,CAAN,CAGFU,CAAA,CAAOV,CA/EM,CAmFfY,CAAA,EA9FmC,CA0JrCY,QAASA,EAAc,CAACuB,CAAD,CAAQ,CAC7B,GAAI,CAACA,CAAL,CAAc,MAAO,EAIrB,KAAIC,EAAQC,CAAAC,KAAA,CAAaH,CAAb,CACRI,EAAAA,CAAcH,CAAA,CAAM,CAAN,CAClB,KAAII,EAAaJ,CAAA,CAAM,CAAN,CAEjB,IADIK,CACJ,CADcL,CAAA,CAAM,CAAN,CACd,CACEM,CAAAC,UAKA;AALoBF,CAAApC,QAAA,CAAgB,IAAhB,CAAqB,MAArB,CAKpB,CAAAoC,CAAA,CAAU,aAAA,EAAiBC,EAAjB,CACRA,CAAAE,YADQ,CACgBF,CAAAG,UAE5B,OAAON,EAAP,CAAqBE,CAArB,CAA+BD,CAlBF,CA4B/BM,QAASA,EAAc,CAACX,CAAD,CAAQ,CAC7B,MAAOA,EAAA9B,QAAA,CACG,IADH,CACS,OADT,CAAAA,QAAA,CAEG0C,CAFH,CAE0B,QAAS,CAACZ,CAAD,CAAQ,CAC9C,IAAIa,EAAKb,CAAAc,WAAA,CAAiB,CAAjB,CACLC,EAAAA,CAAMf,CAAAc,WAAA,CAAiB,CAAjB,CACV,OAAO,IAAP,EAAgC,IAAhC,EAAiBD,CAAjB,CAAsB,KAAtB,GAA0CE,CAA1C,CAAgD,KAAhD,EAA0D,KAA1D,EAAqE,GAHvB,CAF3C,CAAA7C,QAAA,CAOG8C,CAPH,CAO4B,QAAQ,CAAChB,CAAD,CAAO,CAC9C,MAAO,IAAP,CAAcA,CAAAc,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADU,CAP3C,CAAA5C,QAAA,CAUG,IAVH,CAUS,MAVT,CAAAA,QAAA,CAWG,IAXH,CAWS,MAXT,CADsB,CAyB/B7B,QAASA,EAAkB,CAACD,CAAD,CAAM6E,CAAN,CAAmB,CAC5C,IAAIC,EAAS,CAAA,CAAb,CACIC,EAAMnF,CAAAoF,KAAA,CAAahF,CAAb,CAAkBA,CAAA4B,KAAlB,CACV,OAAO,OACEU,QAAQ,CAACtB,CAAD,CAAMa,CAAN,CAAaV,CAAb,CAAmB,CAChCH,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD8D,EAAAA,CAAL,EAAelC,CAAA,CAAgB5B,CAAhB,CAAf,GACE8D,CADF,CACW9D,CADX,CAGK8D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAcjE,CAAd,CAAf,GACE+D,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAI/D,CAAJ,CAaA,CAZApB,CAAAsF,QAAA,CAAgBrD,CAAhB,CAAuB,QAAQ,CAAC+B,CAAD,CAAQuB,CAAR,CAAY,CACzC,IAAIC;AAAKxF,CAAAwB,UAAA,CAAkB+D,CAAlB,CAAT,CACIE,EAAmB,KAAnBA,GAAWrE,CAAXqE,EAAqC,KAArCA,GAA4BD,CAA5BC,EAAyD,YAAzDA,GAAgDD,CAC3B,EAAA,CAAzB,GAAIE,CAAA,CAAWF,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGG,CAAA,CAASH,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAajB,CAAb,CAAoByB,CAApB,CAD9B,GAEEN,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIR,CAAA,CAAeX,CAAf,CAAJ,CACA,CAAAmB,CAAA,CAAI,GAAJ,CANF,CAHyC,CAA3C,CAYA,CAAAA,CAAA,CAAI5D,CAAA,CAAQ,IAAR,CAAe,GAAnB,CAfF,CALgC,CAD7B,KAwBAqB,QAAQ,CAACxB,CAAD,CAAK,CACdA,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD8D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAcjE,CAAd,CAAf,GACE+D,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAI/D,CAAJ,CACA,CAAA+D,CAAA,CAAI,GAAJ,CAHF,CAKI/D,EAAJ,EAAW8D,CAAX,GACEA,CADF,CACW,CAAA,CADX,CAPc,CAxBb,OAmCE/E,QAAQ,CAACA,CAAD,CAAO,CACb+E,CAAL,EACEC,CAAA,CAAIR,CAAA,CAAexE,CAAf,CAAJ,CAFgB,CAnCjB,CAHqC,CAtb9C,IAAI4D,EAAkB/D,CAAA4F,SAAA,CAAiB,WAAjB,CAAtB,CAyJI9B,EACG,wGA1JP,CA2JEF,EAAiB,wBA3JnB,CA4JEzB,EAAc,yEA5JhB,CA6JE0B,EAAmB,IA7JrB;AA8JEF,EAAyB,MA9J3B,CA+JER,EAAiB,qBA/JnB,CAgKEM,EAAiB,qBAhKnB,CAiKEL,EAAe,yBAjKjB,CAkKEwB,EAAwB,iCAlK1B,CAoKEI,EAA0B,gBApK5B,CA6KIjD,EAAetB,CAAA,CAAQ,wBAAR,CAIfoF,EAAAA,CAA8BpF,CAAA,CAAQ,gDAAR,CAC9BqF,EAAAA,CAA+BrF,CAAA,CAAQ,OAAR,CADnC,KAEIqB,EAAyB9B,CAAA+F,OAAA,CAAe,EAAf,CACeD,CADf,CAEeD,CAFf,CAF7B,CAOIpE,EAAgBzB,CAAA+F,OAAA,CAAe,EAAf,CAAmBF,CAAnB,CAAgDpF,CAAA,CAAQ,4KAAR,CAAhD,CAPpB,CAYImB,EAAiB5B,CAAA+F,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiDrF,CAAA,CAAQ,2JAAR,CAAjD,CAZrB;AAkBIuC,EAAkBvC,CAAA,CAAQ,cAAR,CAlBtB,CAoBI4E,EAAgBrF,CAAA+F,OAAA,CAAe,EAAf,CACehE,CADf,CAEeN,CAFf,CAGeG,CAHf,CAIeE,CAJf,CApBpB,CA2BI6D,EAAWlF,CAAA,CAAQ,0CAAR,CA3Bf,CA4BIiF,EAAa1F,CAAA+F,OAAA,CAAe,EAAf,CAAmBJ,CAAnB,CAA6BlF,CAAA,CAC1C,ySAD0C,CAA7B,CA5BjB,CAyMI8D,EAAUyB,QAAAC,cAAA,CAAuB,KAAvB,CAzMd,CA0MI/B,EAAU,wBA2GdlE,EAAAkG,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CAA0C,WAA1C;AAlWAC,QAA0B,EAAG,CAC3B,IAAAC,KAAA,CAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CACpD,MAAO,SAAQ,CAACrF,CAAD,CAAO,CACpB,IAAIb,EAAM,EACVY,EAAA,CAAWC,CAAX,CAAiBZ,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACmG,CAAD,CAAMd,CAAN,CAAe,CAC9D,MAAO,CAAC,SAAA/B,KAAA,CAAe4C,CAAA,CAAcC,CAAd,CAAmBd,CAAnB,CAAf,CADsD,CAA/C,CAAjB,CAGA,OAAOrF,EAAAI,KAAA,CAAS,EAAT,CALa,CAD8B,CAA1C,CADe,CAkW7B,CAwGAR,EAAAkG,OAAA,CAAe,YAAf,CAAAM,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,mEAFuE,CAGzEC,EAAgB,UAEpB,OAAO,SAAQ,CAAC7D,CAAD,CAAO8D,CAAP,CAAe,CAoB5BC,QAASA,EAAO,CAAC/D,CAAD,CAAO,CAChBA,CAAL,EAGA7B,CAAAe,KAAA,CAAU9B,CAAA,CAAa4C,CAAb,CAAV,CAJqB,CAOvBgE,QAASA,EAAO,CAACC,CAAD,CAAMjE,CAAN,CAAY,CAC1B7B,CAAAe,KAAA,CAAU,KAAV,CACIhC,EAAAgH,UAAA,CAAkBJ,CAAlB,CAAJ,GACE3F,CAAAe,KAAA,CAAU,UAAV,CAEA,CADAf,CAAAe,KAAA,CAAU4E,CAAV,CACA,CAAA3F,CAAAe,KAAA,CAAU,IAAV,CAHF,CAKAf,EAAAe,KAAA,CAAU,QAAV,CACAf,EAAAe,KAAA,CAAU+E,CAAV,CACA9F,EAAAe,KAAA,CAAU,IAAV,CACA6E,EAAA,CAAQ/D,CAAR,CACA7B,EAAAe,KAAA,CAAU,MAAV,CAX0B,CA3BA;AAC5B,GAAI,CAACc,CAAL,CAAW,MAAOA,EAMlB,KALA,IAAIV,CAAJ,CACI6E,EAAMnE,CADV,CAEI7B,EAAO,EAFX,CAGI8F,CAHJ,CAIIjG,CACJ,CAAQsB,CAAR,CAAgB6E,CAAA7E,MAAA,CAAUsE,CAAV,CAAhB,CAAA,CAEEK,CAMA,CANM3E,CAAA,CAAM,CAAN,CAMN,CAJIA,CAAA,CAAM,CAAN,CAIJ,EAJgBA,CAAA,CAAM,CAAN,CAIhB,GAJ0B2E,CAI1B,CAJgC,SAIhC,CAJ4CA,CAI5C,EAHAjG,CAGA,CAHIsB,CAAAS,MAGJ,CAFAgE,CAAA,CAAQI,CAAAC,OAAA,CAAW,CAAX,CAAcpG,CAAd,CAAR,CAEA,CADAgG,CAAA,CAAQC,CAAR,CAAa3E,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAiByE,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAM,CAAA,CAAMA,CAAAzD,UAAA,CAAc1C,CAAd,CAAkBsB,CAAA,CAAM,CAAN,CAAArB,OAAlB,CAER8F,EAAA,CAAQI,CAAR,CACA,OAAOR,EAAA,CAAUxF,CAAAT,KAAA,CAAU,EAAV,CAAV,CAlBqB,CAL+C,CAAlC,CAA7C,CAhlBsC,CAArC,CAAA,CAioBET,MAjoBF,CAioBUA,MAAAC,QAjoBV;", +"sources":["angular-sanitize.js"], +"names":["window","angular","undefined","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","makeMap","str","obj","items","split","i","length","htmlParser","html","handler","parseStartTag","tag","tagName","rest","unary","lowercase","blockElements","stack","last","inlineElements","parseEndTag","optionalEndTagElements","voidElements","push","attrs","replace","ATTR_REGEXP","match","name","doubleQuotedValue","singleQuotedValue","unquotedValue","decodeEntities","start","pos","end","index","text","stack.last","specialElements","RegExp","all","COMMENT_REGEXP","CDATA_REGEXP","indexOf","lastIndexOf","comment","substring","DOCTYPE_REGEXP","test","BEGING_END_TAGE_REGEXP","END_TAG_REGEXP","BEGIN_TAG_REGEXP","START_TAG_REGEXP","$sanitizeMinErr","value","parts","spaceRe","exec","spaceBefore","spaceAfter","content","hiddenPre","innerHTML","textContent","innerText","encodeEntities","SURROGATE_PAIR_REGEXP","hi","charCodeAt","low","NON_ALPHANUMERIC_REGEXP","uriValidator","ignore","out","bind","validElements","forEach","key","lkey","isImage","validAttrs","uriAttrs","$$minErr","optionalEndTagBlockElements","optionalEndTagInlineElements","extend","document","createElement","module","provider","$SanitizeProvider","$get","$$sanitizeUri","uri","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","target","addText","addLink","url","isDefined","raw","substr"] +} diff --git a/public/js/lib/angular/angular-scenario.js b/public/js/lib/angular/angular-scenario.js index f0e5c7d51..367ca566f 100644 --- a/public/js/lib/angular/angular-scenario.js +++ b/public/js/lib/angular/angular-scenario.js @@ -1,32 +1,39 @@ /*! - * jQuery JavaScript Library v1.7.2 + * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * * Includes Sizzle.js * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. * - * Date: Wed Mar 21 12:46:34 2012 -0700 + * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-07-03T13:48Z */ -(function( window, undefined ) { -'use strict'; +(function( window, undefined ) {'use strict'; -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +// -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, +var + // The deferred used on DOM ready + readyList, + + // A central reference to the root jQuery(document) + rootjQuery, + + // Support: IE<10 + // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` + core_strundefined = typeof undefined, + + // Use the correct document accordingly with window argument (sandbox) + location = window.location, + document = window.document, + docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, @@ -34,133 +41,136 @@ var jQuery = function( selector, context ) { // Map over the $ in case of overwrite _$ = window.$, - // A central reference to the root jQuery(document) - rootjQuery, + // [[Class]] -> type pairs + class2type = {}, - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "1.10.2", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + 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.]+))?/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { - return ( letter + "" ).toUpperCase(); + 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, + completed = function( event ) { - // 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, + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } + }, + // Clean-up method for dom ready events + detach = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); - // [[Class]] -> type pairs - class2type = {}; + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } + }; jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + constructor: jQuery, init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; + var match, elem; - // Handle $(""), $(null), or $(undefined) + // HANDLE: $(""), $(null), $(undefined), $(false) 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 ); + match = rquickExpr.exec( selector ); } - // Verify a match, and that no context was specified for #id + // Match html or make sure no context is 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] ) ]; + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } - return jQuery.merge( this, selector ); + return this; - // HANDLE: $("#id") + // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); @@ -193,6 +203,12 @@ jQuery.fn = jQuery.prototype = { return this.constructor( context ).find( selector ); } + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { @@ -210,19 +226,11 @@ jQuery.fn = jQuery.prototype = { // Start with an empty selector selector: "", - // The current version of jQuery being used - jquery: "1.7.2", - // 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 ); + return core_slice.call( this ); }, // Get the Nth element in the matched element set OR @@ -239,28 +247,15 @@ jQuery.fn = jQuery.prototype = { // 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(); + pushStack: function( elems ) { - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), 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; }, @@ -273,20 +268,14 @@ jQuery.fn = jQuery.prototype = { }, ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - // Add the callback - readyList.add( fn ); + jQuery.ready.promise().done( fn ); return this; }, - eq: function( i ) { - i = +i; - return i === -1 ? - this.slice( i ) : - this.slice( i, i + 1 ); + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { @@ -297,9 +286,10 @@ jQuery.fn = jQuery.prototype = { return this.eq( -1 ); }, - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { @@ -314,7 +304,7 @@ jQuery.fn = jQuery.prototype = { // For internal use only. // Behaves like an Array's method, not like a jQuery method. - push: push, + push: core_push, sort: [].sort, splice: [].splice }; @@ -323,7 +313,7 @@ jQuery.fn = jQuery.prototype = { jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, + var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, @@ -387,6 +377,10 @@ jQuery.extend = jQuery.fn.extend = function() { }; jQuery.extend({ + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; @@ -417,73 +411,31 @@ jQuery.extend({ // 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.fireWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).off( "ready" ); - } - } - }, - bindReady: function() { - if ( readyList ) { + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } - readyList = jQuery.Callbacks( "once memory" ); - - // 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 ); + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); } - // 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 ); + // Remember that the DOM is ready + jQuery.isReady = true; - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } - try { - toplevel = window.frameElement == null; - } catch(e) {} + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); } }, @@ -499,6 +451,7 @@ jQuery.extend({ }, isWindow: function( obj ) { + /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, @@ -507,12 +460,17 @@ jQuery.extend({ }, type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; + if ( obj == null ) { + return String( obj ); + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; }, isPlainObject: function( obj ) { + var key; + // 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 @@ -523,8 +481,8 @@ jQuery.extend({ try { // Not own constructor property must be Object if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { @@ -532,17 +490,24 @@ jQuery.extend({ return false; } + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( jQuery.support.ownLast ) { + for ( key in obj ) { + return core_hasOwn.call( obj, key ); + } + } + // 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 ); + return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { - for ( var name in obj ) { + var name; + for ( name in obj ) { return false; } return true; @@ -552,37 +517,70 @@ jQuery.extend({ throw new Error( msg ); }, - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { return null; } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); + parsed = jQuery.buildFragment( [ data ], context, scripts ); + if ( scripts ) { + jQuery( scripts ).remove(); + } + return jQuery.merge( [], parsed.childNodes ); + }, + parseJSON: function( 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, "")) ) { + if ( data === null ) { + return data; + } + + if ( typeof data === "string" ) { + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); - return ( new Function( "return " + data ) )(); + if ( 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 ) { - if ( typeof data !== "string" || !data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { return null; } - var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); @@ -607,7 +605,7 @@ jQuery.extend({ // 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 ) ) { + if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox @@ -624,25 +622,30 @@ jQuery.extend({ }, nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { break; } } } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { break; } } @@ -650,72 +653,75 @@ jQuery.extend({ // 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 ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { break; } } } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { break; } } } } - return object; + return obj; }, // Use native String.trim function wherever possible - trim: trim ? + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : - trim.call( text ); + core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only - makeArray: function( array, results ) { + makeArray: function( arr, results ) { var ret = results || []; - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // 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 ); + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); } else { - jQuery.merge( ret, array ); + core_push.call( ret, arr ); } } return ret; }, - inArray: function( elem, array, i ) { + inArray: function( elem, arr, i ) { var len; - if ( array ) { - if ( indexOf ) { - return indexOf.call( array, elem, i ); + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); } - len = array.length; + len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays - if ( i in array && array[ i ] === elem ) { + if ( i in arr && arr[ i ] === elem ) { return i; } } @@ -725,14 +731,14 @@ jQuery.extend({ }, merge: function( first, second ) { - var i = first.length, + var l = second.length, + i = first.length, j = 0; - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } - } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; @@ -745,12 +751,15 @@ jQuery.extend({ }, grep: function( elems, callback, inv ) { - var ret = [], retVal; + var retVal, + ret = [], + i = 0, + length = elems.length; 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++ ) { + for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); @@ -762,11 +771,11 @@ jQuery.extend({ // arg is for internal usage only map: function( elems, callback, arg ) { - var value, key, ret = [], + var value, 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 ) ) ; + isArray = isArraylike( elems ), + ret = []; // Go through the array, translating each of the items to their if ( isArray ) { @@ -780,8 +789,8 @@ jQuery.extend({ // Go through every key on the object, } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; @@ -790,7 +799,7 @@ jQuery.extend({ } // Flatten any nested arrays - return ret.concat.apply( [], ret ); + return core_concat.apply( [], ret ); }, // A global GUID counter for objects @@ -799,8 +808,10 @@ jQuery.extend({ // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { + var args, proxy, tmp; + if ( typeof context === "string" ) { - var tmp = fn[ context ]; + tmp = fn[ context ]; context = fn; fn = tmp; } @@ -812,59 +823,59 @@ jQuery.extend({ } // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_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++; + proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, - // Mutifunctional method to get and set values to a collection + // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, pass ) { - var exec, - bulk = key == null, - i = 0, - length = elems.length; + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; // Sets many values - if ( key && typeof key === "object" ) { + if ( jQuery.type( key ) === "object" ) { + chainable = true; for ( i in key ) { - jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } - chainable = 1; // Sets one value } else if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = pass === undefined && jQuery.isFunction( value ); + chainable = true; - if ( bulk ) { - // Bulk operations only iterate when executing function values - if ( exec ) { - exec = fn; - fn = function( elem, key, value ) { - return exec.call( jQuery( elem ), value ); - }; + if ( !jQuery.isFunction( value ) ) { + raw = true; + } - // Otherwise they run against the entire set - } else { + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { fn.call( elems, value ); fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; } } if ( fn ) { - for (; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } - - chainable = 1; } return chainable ? @@ -880,4665 +891,4928 @@ jQuery.extend({ 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 ) || - []; + // A method for quickly swapping in/out CSS properties to get correct calculations. + // Note: this method belongs to the css module but it's needed here for the support module. + // If support gets modularized, this method should be moved back to the css module. + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; - return { browser: match[1] || "", version: match[2] || "0" }; - }, + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } - 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 ); - } + ret = callback.apply( elem, args || [] ); - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } - browser: {} + return ret; + } }); -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} + readyList = jQuery.Deferred(); -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); -// All jQuery objects should point back to these -rootjQuery = jQuery(document); + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); -} 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(); - } - }; -} + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } + // If IE and not a frame + // continually check to see if the document is ready + var top = false; - 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; - } + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} - // and execute any waiting functions - jQuery.ready(); -} + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { -return jQuery; + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } -})(); + // detach all dom ready events + detach(); + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); -// String to Object flags format cache -var flagsCache = {}; +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); -// Convert String-formatted flags into Object-formatted ones and store in cache -function createFlags( flags ) { - var object = flagsCache[ flags ] = {}, - i, length; - flags = flags.split( /\s+/ ); - for ( i = 0, length = flags.length; i < length; i++ ) { - object[ flags[i] ] = true; + if ( jQuery.isWindow( obj ) ) { + return false; } - return object; + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } -/* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +/*! + * Sizzle CSS Selector Engine v1.10.2 + * http://sizzlejs.com/ * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license * + * Date: 2013-07-03 */ -jQuery.Callbacks = function( flags ) { +(function( window, undefined ) { - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; +var i, + support, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + return 0; + }, - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function( args ) { - var i, - length, - elem, - type, - actual; - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - // Inspect recursively - add( elem ); - } else if ( type === "function" ) { - // Add if not in unique mode and callback is not in - if ( !flags.unique || !self.has( elem ) ) { - list.push( elem ); - } - } - } - }, - // Fire callbacks - fire = function( context, args ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - fired = true; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - self.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - var length = list.length; - add( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if ( memory && memory !== true ) { - firingStart = length; - fire( memory[ 0 ], memory[ 1 ] ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for ( ; argIndex < argLength ; argIndex++ ) { - for ( var i = 0; i < list.length; i++ ) { - if ( args[ argIndex ] === list[ i ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; - } - } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique ) { - break; - } - } - } - } - } - return this; - }, - // Control if a given callback is in the list - has: function( fn ) { - if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( fn === list[ i ] ) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory || memory === true ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( stack ) { - if ( firing ) { - if ( !flags.once ) { - stack.push( [ context, args ] ); - } - } else if ( !( flags.once && memory ) ) { - fire( context, args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; } - }; + } + return -1; + }, - return self; -}; + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rsibling = new RegExp( whitespace + "*[+~]" ), + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} -var // Static reference to slice - sliceDeferred = [].slice; +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; -jQuery.extend({ + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } - Deferred: function( func ) { - var doneList = jQuery.Callbacks( "once memory" ), - failList = jQuery.Callbacks( "once memory" ), - progressList = jQuery.Callbacks( "memory" ), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, + context = context || document; + results = results || []; - state: function() { - return state; - }, + if ( !selector || typeof selector !== "string" ) { + return results; + } - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } - then: function( doneCallbacks, failCallbacks, progressCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); - return this; - }, - always: function() { - deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); - return this; - }, - pipe: function( fnDone, fnFail, fnProgress ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ], - progress: [ fnProgress, "notify" ] - }, 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, newDefer.notify ); - } 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 ) { - obj = promise; - } else { - for ( var key in promise ) { - obj[ key ] = promise[ key ]; + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // 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, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; } - return obj; } - }, - deferred = promise.promise({}), - key; - - for ( key in lists ) { - deferred[ key ] = lists[ key ].fire; - deferred[ key + "With" ] = lists[ key ].fireWith; - } - // Handle state - deferred.done( function() { - state = "resolved"; - }, failList.disable, progressList.lock ).fail( function() { - state = "rejected"; - }, doneList.disable, progressList.lock ); + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } } - // All done! - return deferred; - }, + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; - // Deferred helper - when: function( firstParam ) { - var args = sliceDeferred.call( arguments, 0 ), - i = 0, - length = args.length, - pValues = new Array( length ), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( deferred, args ); - } - }; - } - function progressFunc( i ) { - return function( value ) { - pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - deferred.notifyWith( promise, pValues ); - }; - } - if ( length > 1 ) { - for ( ; i < length; i++ ) { - if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + // 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 + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); } else { - --count; + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); } - if ( !count ) { - deferred.resolveWith( deferred, args ); + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } - return promise; } -}); + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + } + return cache; +} -jQuery.support = (function() { +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} - var support, - all, - a, - select, - opt, - input, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement( "div" ), - documentElement = document.documentElement; +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; } +} - // 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", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - pixelMargin: true - }; +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } - // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead - jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; + return a ? 1 : -1; +} - // 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; +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} - // 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; +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ +isXML = 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).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; } - 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; + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent.attachEvent && parent !== parent.top ) { + parent.attachEvent( "onbeforeunload", function() { + setDocument(); }); - div.cloneNode( true ).fireEvent( "onclick" ); } - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; + /* Attributes + ---------------------------------------------------------------------- */ - input.setAttribute("checked", "checked"); + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "name", "t" ); + /* getElement(s)By* + ---------------------------------------------------------------------- */ - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = assert(function( div ) { + div.innerHTML = "
    "; - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); - fragment.removeChild( input ); - fragment.appendChild( div ); + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); - // Technique from Juriy Zaytsev - // http://perfectionkills.com/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" ); + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; } - support[ i + "Bubbles" ] = isSupported; - } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; } - fragment.removeChild( div ); + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); - // Null elements to avoid leaks in IE - fragment = select = opt = div = input = null; + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, - paddingMarginBorderVisibility, paddingMarginBorder, - body = document.getElementsByTagName("body")[0]; + return tmp; + } + return results; + }; - if ( !body ) { - // Return for frameset docs that don't have a body - return; + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); } + }; - conMarginTop = 1; - paddingMarginBorder = "padding:0;margin:0;border:"; - positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; - paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; - style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; - html = "
    " + - "" + - "
    "; - - container = document.createElement("div"); - container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); + // QSA and matchesSelector support - // 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) - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + 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 ( window.getComputedStyle ) { - div.innerHTML = ""; - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } - if ( typeof div.style.zoom !== "undefined" ) { - // 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.innerHTML = ""; - div.style.width = div.style.padding = "1px"; - div.style.border = 0; - div.style.overflow = "hidden"; - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = "block"; - div.style.overflow = "visible"; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - } + assert(function( div ) { - div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; - div.innerHTML = html; + // Support: Opera 10-12/IE8 + // ^= $= *= and empty values + // Should not select anything + // Support: Windows 8 Native Apps + // The type attribute is restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "t", "" ); - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; + if ( div.querySelectorAll("[t^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) - }; + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } - inner.style.position = "fixed"; - inner.style.top = "20px"; + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; + if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { - outer.style.overflow = "hidden"; - outer.style.position = "relative"; + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } - if ( window.getComputedStyle ) { - div.style.marginTop = "1%"; - support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; - } + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; - if ( typeof container.style.zoom !== "undefined" ) { - container.style.zoom = 1; - } + /* Sorting + ---------------------------------------------------------------------- */ - body.removeChild( container ); - marginDiv = div = container = null; + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { - jQuery.extend( support, offsetSupport ); - }); + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } - return support; -})(); + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; + return compare & 4 ? -1 : 1; + } -jQuery.extend({ - cache: {}, + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; - // Please use with caution - uuid: 0, + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 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, "" ), + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; - // 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 - }, + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; } - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : - // 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, + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; - // 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, + return doc; +}; - // 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[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; - // 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 || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } - 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[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); - if ( !cache[ id ] ) { - cache[ id ] = {}; + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } + try { + var ret = matches.call( elem, expr ); - // 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 ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; } - } + } catch(e) {} + } - privateCache = thisCache = cache[ id ]; + return Sizzle( expr, document, null, [elem] ).length > 0; +}; - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; - thisCache = thisCache.data; - } +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } + return val === undefined ? + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null : + val; +}; - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; - // First Try to find as-is property data - ret = thisCache[ name ]; +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; - // Test for null|undefined property data - if ( ret == null ) { + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); } - } else { - ret = thisCache; } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } - return ret; - }, + return results; +}; - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes - var thisCache, i, l, + return ret; +}; - // Reference to internal data cache key - internalKey = jQuery.expando, +Expr = Sizzle.selectors = { - isNode = elem.nodeType, + // Can be adjusted by the user + cacheLength: 50, - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, + createPseudo: markFunction, - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; + match: matchExpr, - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } + attrHandle: {}, - if ( name ) { + find: {}, - thisCache = pvt ? cache[ id ] : cache[ id ].data; + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, - if ( thisCache ) { + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } - } - } + return match.slice( 0, 4 ); + }, - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); } - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); } - } - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; + return match; + }, - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; } - } - // 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; - } + // Accept quoted arguments as-is + if ( match[3] && match[4] !== undefined ) { + match[2] = match[4]; - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - 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[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); } }, - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, + filter: { - // 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() ]; + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; - return true; - } -}); + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, -jQuery.fn.extend({ - data: function( key, value ) { - var parts, part, attr, name, l, - elem = this[0], - i = 0, - data = null; + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attr = elem.attributes; - for ( l = attr.length; i < l; i++ ) { - name = attr[i].name; + result += ""; - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, - dataAttr( elem, name, data[ name ] ); + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); } - jQuery._data( elem, "parsedAttrs", true ); - } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; } - return data; + return fn; } + }, - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), - parts = key.split( ".", 2 ); - parts[1] = parts[1] ? "." + parts[1] : ""; - part = parts[1] + "!"; + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), - return jQuery.access( this, function( value ) { + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, - if ( value === undefined ) { - data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } - // Try to fetch any internally stored data first - if ( data === undefined && elem ) { - data = jQuery.data( elem, key ); - data = dataAttr( elem, key, data ); + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; + "text": function( elem ) { + var attr; + // 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" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); } + return matchIndexes; + }), - parts[1] = value; - this.each(function() { - var self = jQuery( this ); + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), - self.triggerHandler( "setData" + part, parts ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + part, parts ); - }); - }, null, value, arguments.length > 1, null, false ); - }, + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) } -}); +}; -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 ) { +Expr.pseudos["nth"] = Expr.pseudos["eq"]; - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} - data = elem.getAttribute( name ); +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } - } else { - data = undefined; + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); } - } - return data; -} + matched = false; -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } } - if ( name !== "toJSON" ) { - return false; + + if ( !matched ) { + break; } } - return true; + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); } +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // 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 ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } } - }, 0 ); - } + }; } -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} - _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 ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } } } - }, + } - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); + return newUnmatched; +} - // 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) ); - } else { - q.push( data ); +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } - return q || []; } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); + seed[temp] = !(results[temp] = elem); + } + } } - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } } + }); +} - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); } } -}); -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; + return elementMatcher( matchers ); +} - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } } - }); - }, - 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( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - 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.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); } - } - resolve(); - return defer.promise( object ); - } -}); - - - -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, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } - 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 ) {} - }); - }, + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; + // Add matches to results + push.apply( results, setMatched ); - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); + Sizzle.uniqueSort( results ); + } + } - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; + return unmatched; + }; - } else { - setClass = " " + elem.className + " "; + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); } } - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { - 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 ); + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { - } else { - elem.className = ""; - } + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; } + selector = selector.slice( tokens.shift().value.length ); } - } - - 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 ); + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); + break; + } } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; } } + } - return false; - }, + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; +// One-time assignments - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = hasDuplicate; - ret = elem.value; +// Initialize against the default document +setDocument(); - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); - return; +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } + }); +} - isFunction = jQuery.isFunction( value ); +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} - return this.each(function( i ) { - var self = jQuery(this), val; +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + elem[ name ] === true ? name.toLowerCase() : null; + } + }); +} - if ( this.nodeType !== 1 ) { - return; - } +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; - 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 + ""; - }); - } +})( window ); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); -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; + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } } }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - 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; + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } } - - // Multi-Selects return an array - values.push( value ); + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); } } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } + return self; +}; +jQuery.extend({ - return values; + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } }, + deferred = {}; - set: function( elem, value ) { - var values = jQuery.makeArray( value ); + // Keep pipe for back-compat + promise.pipe = promise.then; - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); } - }, - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true + // All done! + return deferred; }, - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } + progressValues, progressContexts, resolveContexts; - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } } - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); } - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } + return deferred.promise(); + } +}); +jQuery.support = (function( support ) { - if ( value !== undefined ) { + var all, a, input, select, fragment, opt, eventName, isSupported, i, + div = document.createElement("div"); - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
    a"; - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; + // Finish early in limited (non-browser) environments + all = div.getElementsByTagName("*") || []; + a = div.getElementsByTagName("a")[ 0 ]; + if ( !a || !a.style || !all.length ) { + return support; + } - } else { - elem.setAttribute( name, "" + value ); - return value; - } + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; + a.style.cssText = "top:1px;float:left;opacity:.5"; - } else { + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + support.getSetAttribute = div.className !== "t"; - ret = elem.getAttribute( name ); + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName("tbody").length; - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, isBool, - i = 0; + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName("link").length; - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; + // Get the style information from getAttribute + // (IE uses .cssText instead) + support.style = /top/.test( a.getAttribute("style") ); - for ( ; i < l; i++ ) { - name = attrNames[ i ]; + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + support.hrefNormalized = a.getAttribute("href") === "/a"; - if ( name ) { - propName = jQuery.propFix[ name ] || name; - isBool = rboolean.test( name ); + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + support.opacity = /^0.5/.test( a.style.opacity ); - // See #9699 for explanation of this approach (setting first, then removal) - // Do not do this for boolean attributes (see #10870) - if ( !isBool ) { - jQuery.attr( elem, name, "" ); - } - elem.removeAttribute( getSetAttribute ? name : propName ); + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + support.cssFloat = !!a.style.cssFloat; - // Set corresponding property to false for boolean attributes - if ( isBool && propName in elem ) { - elem[ propName ] = false; - } - } - } - } - }, + // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) + support.checkOn = !!input.value; - 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; - } - } - }, + // 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) + support.optSelected = opt.selected; - 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" - }, + // Tests for enctype support on a form (#6743) + support.enctype = !!document.createElement("form").enctype; - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>"; - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } + // Will be defined later + support.inlineBlockNeedsLayout = false; + support.shrinkWrapBlocks = false; + support.pixelPosition = false; + support.deleteExpando = true; + support.noCloneEvent = true; + support.reliableMarginRight = true; + support.boxSizingReliable = true; - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } + // 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; - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; + // Support: IE<9 + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } - } else { - return ( elem[ name ] = value ); - } + // Check if we can trust getAttribute("value") + input = document.createElement("input"); + input.setAttribute( "value", "" ); + support.input = input.getAttribute( "value" ) === ""; - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; + // Check if an input maintains its value after becoming a radio + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; - } else { - return elem[ name ]; - } - } - }, + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); - 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"); + fragment = document.createDocumentFragment(); + fragment.appendChild( input ); - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; -// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; -// 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, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( 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; - } + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); - elem.setAttribute( name, name.toLowerCase() ); - } - return name; + div.cloneNode( true ).click(); } -}; -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { + // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + for ( i in { submit: true, change: true, focusin: true }) { + div.setAttribute( eventName = "on" + i, "t" ); - fixSpecified = { - name: true, - id: true, - coords: true - }; + support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; + } - // 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 ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - 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 + "" ); - } - }; + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; + // Support: IE<9 + // Iteration over object's inherited properties before its own. + for ( i in jQuery( support ) ) { + break; + } + support.ownLast = i !== "0"; - // 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; - } - } - }); - }); + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, tds, + divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", + body = document.getElementsByTagName("body")[0]; - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; - } - nodeHook.set( elem, value, name ); + if ( !body ) { + // Return for frameset docs that don't have a body + return; } - }; -} + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + body.appendChild( container ).appendChild( div ); -// 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; - } + // Support: IE8 + // 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). + div.innerHTML = "
    t
    "; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Support: IE8 + // Check if empty table cells still have offsetWidth/Height + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior. + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + + // Workaround failing boxSizing test due to offsetWidth returning wrong value + // with some non-1 values of body zoom, ticket #13543 + jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { + support.boxSizing = div.offsetWidth === 4; }); - }); -} -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 ); + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } - }; -} -// 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 ( typeof div.style.zoom !== core_strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - if ( parent ) { - parent.selectedIndex; + // Support: IE6 + // Check if elements with layout shrink-wrap their children + div.style.display = "block"; + div.innerHTML = "
    "; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } + if ( support.inlineBlockNeedsLayout ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; } - return null; } - }); -} -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} + body.removeChild( container ); -// 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 ); - } - } + // Null elements to avoid leaks in IE + container = div = tds = marginDiv = null; }); -}); + // Null elements to avoid leaks in IE + all = select = fragment = opt = a = input = null; + return support; +})({}); +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; +function internalData( elem, name, data, pvt /* Internal Use Only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { + var ret, thisCache, + internalKey = jQuery.expando, - add: function( elem, types, handler, data, selector ) { + // 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, - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; + // 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, - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } + // 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[ internalKey ] : elem[ internalKey ] && internalKey; - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } + // 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 || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; } + } - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - 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.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { 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 ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } + } - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { + thisCache = cache[ id ]; - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; + thisCache = thisCache.data; + } - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: selector && quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); + // First Try to find as-is property data + ret = thisCache[ name ]; - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; + // Test for null|undefined property data + if ( ret == null ) { - // 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 ); + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } - } 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 to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, + return ret; +} - global: {}, +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { + var thisCache, i, + isNode = elem.nodeType, - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - if ( !elemData || !(events = elemData.events) ) { - return; - } + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; + if ( name ) { - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } + thisCache = pvt ? cache[ id ] : cache[ id ].data; - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + if ( thisCache ) { - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); } } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } - delete events[ type ]; + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; } } + } - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "applet": true, + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, - // 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 + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); }, - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + }, - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + // Do not set data on non-element because it will not be cleared (#8335). + if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { + return false; } - 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; - } + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; - // 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 ); + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + data = null, + i = 0, + elem = this[0]; - // Handle a global trigger - if ( !elem ) { + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[i].name; - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + if ( name.indexOf("data-") === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); } } - return; + + return data; } - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); } - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); + return arguments.length > 1 ? - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; + }, - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } +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 ) { - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - cur = eventPath[i][0]; - event.type = eventPath[i][1]; + data = elem.getAttribute( name ); - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + } else { + data = undefined; + } + } - // 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. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + return data; +} - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { - if ( old ) { - elem[ ontype ] = null; - } + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; - if ( old ) { - elem[ ontype ] = old; - } + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); } } + return queue || []; } - - return event.result; }, - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - special = jQuery.event.special[ event.type ] || {}, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + dequeue: function( elem, type ) { + type = type || "fx"; - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; } - // Determine handlers that should run if there are delegated events - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - - // Don't process events on disabled elements (#6911, #8165) - if ( cur.disabled !== true ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; + if ( fn ) { - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); } - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + if ( !startLength && hooks ) { + hooks.empty.fire(); } + }, - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } - event.data = handleObj.data; - event.handleObj = handleObj; + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + 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( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + 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, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; } + type = type || "fx"; - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, + rclass = /[\t\r\n\f]/g, + rreturn = /\r/g, + rfocusable = /^(?:input|select|textarea|button|object)$/i, + rclickable = /^(?:a|area)$/i, + ruseDefault = /^(?:checked|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + getSetInput = jQuery.support.input; - return event.result; +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, - fixHooks: {}, + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { + 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 ) {} + }); + }, - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; - return event; + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; } - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); + return this; + }, - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } } - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + return this; }, - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, + toggleClass: function( value, stateVal ) { + var type = typeof value; - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } } - }, - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; + // Toggle whole class name + } else if ( type === core_strundefined || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } - } + }); }, - simulate: function( type, elem, event, bubble ) { - // 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. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); } - } -}; -// Some plugins are using, but it's undocumented/deprecated and will be removed. -// The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; + return false; + }, -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 ); + val: function( value ) { + var ret, hooks, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + 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; } - }; -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } + isFunction = jQuery.isFunction( value ); - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; + return this.each(function( i ) { + var val; - // 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; + if ( this.nodeType !== 1 ) { + return; + } - // Event type - } else { - this.type = src; - } + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); + // 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.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); } +}); - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // Use proper attribute retrieval(#6932, #12072) + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; - // Mark it as fixed - this[ jQuery.expando ] = true; -}; + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { -// 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; + // Get the specific value for the option + value = jQuery( option ).val(); - var e = this.originalEvent; - if ( !e ) { - return; - } + // We don't need an array for one selects + if ( one ) { + return value; + } - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); + // Multi-Selects return an array + values.push( value ); + } + } - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { + optionSet = true; + } + } + + // force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } } }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - var e = this.originalEvent; - if ( !e ) { + attr: function( elem, name, value ) { + var hooks, ret, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === core_strundefined ) { + return jQuery.prop( elem, name, value ); } - // 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 -}; -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); + } - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; + if ( value !== undefined ) { - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); + if ( value === null ) { + jQuery.removeAttr( elem, name ); -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { + } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; + } else { + elem.setAttribute( name, value + "" ); + return value; } - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, + } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } + } else { + ret = jQuery.find.attr( elem, name ); - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; } - }; -} + }, -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); - jQuery.event.special.change = { + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; - setup: function() { + // Boolean attributes get special treatment (#10870) + if ( jQuery.expr.match.bool.test( name ) ) { + // Set corresponding property to false + if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + elem[ propName ] = false; + // Support: IE<9 + // Also clear defaultChecked/defaultSelected (if appropriate) + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = + elem[ propName ] = false; + } - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; + // See #9699 for explanation of this approach (setting first, then removal) + } else { + jQuery.attr( elem, name, "" ); } - }); - }, - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); + elem.removeAttribute( getSetAttribute ? name : propName ); } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); } - }; -} - -// 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, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; + }, - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); + attrHooks: { + type: { + set: function( elem, value ) { + 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 default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; } } - }; - }); -} + } + }, -jQuery.fn.extend({ + propFix: { + "for": "htmlFor", + "class": "className" + }, - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { // && selector != null - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; } - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, + if ( value !== undefined ) { + return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? + ret : + ( elem[ name ] = value ); - 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 ); + } else { + return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? + ret : + elem[ name ]; } }, - 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 ); + 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/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); - // Make sure that clicks stop - event.preventDefault(); + return tabindex ? + parseInt( tabindex, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + -1; + } + } + } +}); - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + // IE<8 needs the *property* name + elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; + // Use defaultChecked and defaultSelected for oldIE + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + return name; } +}; +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; + + jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? + function( elem, name, isXML ) { + var fn = jQuery.expr.attrHandle[ name ], + ret = isXML ? + undefined : + /* jshint eqeqeq: false */ + (jQuery.expr.attrHandle[ name ] = undefined) != + getter( elem, name, isXML ) ? + + name.toLowerCase() : + null; + jQuery.expr.attrHandle[ name ] = fn; + return ret; + } : + function( elem, name, isXML ) { + return isXML ? + undefined : + elem[ jQuery.camelCase( "default-" + name ) ] ? + name.toLowerCase() : + null; + }; }); -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 contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; +// fix oldIE attroperties +if ( !getSetInput || !getSetAttribute ) { + jQuery.attrHooks.value = { + set: function( elem, value, name ) { + if ( jQuery.nodeName( elem, "input" ) ) { + // Does not return so that setAttribute is also used + elem.defaultValue = value; + } else { + // Use nodeHook if defined (#1954); otherwise setAttribute is fine + return nodeHook && nodeHook.set( elem, value, name ); + } } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); }; +} - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = { + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + elem.setAttributeNode( + (ret = elem.ownerDocument.createAttribute( name )) + ); + } + ret.value = value += ""; + // Break association with cloned elements by also using setAttribute (#9646) + return name === "value" || value === elem.getAttribute( name ) ? + value : + undefined; + } + }; + jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = + // Some attributes are constructed with empty-string values when not defined + function( elem, name, isXML ) { + var ret; + return isXML ? + undefined : + (ret = elem.getAttributeNode( name )) && ret.value !== "" ? + ret.value : + null; + }; + jQuery.valHooks.button = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return ret && ret.specified ? + ret.value : + undefined; + }, + set: nodeHook.set + }; -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + set: function( elem, value, name ) { + nodeHook.set( elem, value === "" ? false : value, name ); + } + }; -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/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; -}); + // 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 ] = { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }; + }); +} -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - var origContext = context; +// Some attributes require a special call on IE +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !jQuery.support.hrefNormalized ) { + // href/src property should get the full normalized URL (#10299/#12915) + jQuery.each([ "href", "src" ], function( i, name ) { + jQuery.propHooks[ name ] = { + get: function( elem ) { + return elem.getAttribute( name, 4 ); + } + }; + }); +} - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Note: IE uppercases css property names, but if we were to .toLowerCase() + // .cssText, that would destroy case senstitivity in URL's, like in "background" + return elem.style.cssText || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} - if ( !selector || typeof selector !== "string" ) { - return results; - } +// 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 = { + get: function( elem ) { + var parent = elem.parentNode; - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; + if ( parent ) { + parent.selectedIndex; - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }; +} - if ( m ) { - soFar = m[3]; +jQuery.each([ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +}); - parts.push( m[1] ); +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} - if ( m[2] ) { - extra = m[3]; - break; +// Radios and checkboxes getter/setter +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { + }; + if ( !jQuery.support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + // Support: Webkit + // "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + }; + } +}); +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); +function returnTrue() { + return true; +} - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); +function returnFalse() { + return false; +} - while ( parts.length ) { - selector = parts.shift(); +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { - set = posProcess( selector, set, seed ); - } - } + global: {}, - } 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]) ) { + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; } - 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 ); + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } - if ( parts.length > 0 ) { - checkSet = makeArray( set ); + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = 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 !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } - } else { - prune = false; + // Handle multiple events separated by a space + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; } - while ( parts.length ) { - cur = parts.pop(); - pop = cur; + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; - if ( pop == null ) { - pop = context; - } + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); - } else { - checkSet = parts = []; - } - } + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; - if ( !checkSet ) { - checkSet = set; - } + // 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 ); - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); + if ( special.add ) { + special.add.call( elem, handleObj ); - } 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] ); + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; } } - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); } - } - } else { - makeArray( checkSet, results ); - } + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } + // Nullify elem to prevent memory leaks in IE + elem = null; + }, - return results; -}; + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); -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 ); - } - } + if ( !elemData || !(events = elemData.events) ) { + return; } - } - - 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; -}; + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } - if ( !expr ) { - return []; - } + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); } + + delete events[ type ]; } } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - return { set: set, expr: expr }; -}; + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = core_hasOwn.call( event, "type" ) ? event.type : event, + namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - anyFound = false; + cur = tmp = elem = elem || document; - match.splice(1,1); + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } - 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; - } - } + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); - } else { - curLoop[i] = false; - } + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); - expr = expr.replace( Expr.match[ type ], "" ); + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } - if ( !anyFound ) { - return []; - } + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - break; - } + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - } else { - break; + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } - old = expr; - } - - return curLoop; -}; + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; + event.type = i > 1 ? + bubbleType : + special.bindType || type; -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); } } - } - return ret; -}; - -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\))?/ - }, + event.type = type; - leftMatch: {}, + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { - attrMap: { - "class": "className", - "for": "htmlFor" - }, + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, + // 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. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; - if ( isTag ) { - part = part.toLowerCase(); - } + if ( tmp ) { + elem[ ontype ] = null; + } - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; + if ( tmp ) { + elem[ ontype ] = tmp; + } } } + } - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, + return event.result; + }, - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; + dispatch: function( event ) { - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); - for ( ; i < l; i++ ) { - elem = checkSet[i]; + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, + event.handleObj = handleObj; + event.data = handleObj.data; - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } } + } - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); } - }, - 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] : []; - } - }, + return event.result; + }, - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - return ret.length === 0 ? null : ret; - } - }, + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ - 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, "" ) + " "; + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; - if ( isXML ) { - return match; - } + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; - 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 ); + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; } - - } else if ( inplace ) { - curLoop[i] = false; + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); } } } + } - return false; - }, + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, + return handlerQueue; + }, - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; - match[2] = match[2].replace(/^\+|\s*/g, ''); + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - // 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]); + event = new jQuery.Event( originalEvent ); - // 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] ); - } + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } - // TODO: Move to normal caching system - match[0] = done++; + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } - return match; - }, + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } + fixHooks: {}, - return match; - }, + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { - 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); + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + return event; + } + }, - if ( !inplace ) { - result.push.apply( result, ret ); - } + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; - return false; - } + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } - return match; - }, + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } - POS: function( match ) { - match.unshift( true ); + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } - return match; + return event; } }, - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true }, - - disabled: function( elem ) { - return elem.disabled === true; + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" }, - - checked: function( elem ) { - return elem.checked === true; + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); } - - 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 ); - }, + beforeunload: { + postDispatch: function( event ) { - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; + // Even when returnValue equals to undefined Firefox will still show alert + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } } }, - 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; - }, + simulate: function( type, elem, event, bubble ) { + // 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. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; - eq: function( elem, i, match ) { - return match[3] - 0 === i; +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; + } : + function( elem, type, handle ) { + var name = "on" + type; - if ( filter ) { - return filter( elem, i, match, array ); + if ( elem.detachEvent ) { - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === core_strundefined ) { + elem[ name ] = null; + } - } else if ( name === "not" ) { - var not = match[3]; + elem.detachEvent( name, handle ); + } + }; - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } - return true; + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; - } else { - Sizzle.error( name ); - } - }, + // 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; - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } + // Event type + } else { + this.type = src; + } - if ( type === "first" ) { - return true; - } + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } - node = elem; + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); - /* falls through */ - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } + // Mark it as fixed + this[ jQuery.expando ] = true; +}; - 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 = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, - case "nth": - first = match[2]; - last = match[3]; + preventDefault: function() { + var e = this.originalEvent; - if ( first === 1 && last === 0 ) { - return true; - } + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } - doneName = match[0]; - parent = elem.parentNode; + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } - parent[ expando ] = doneName; - } + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; - diff = elem.nodeIndex - last; +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, - if ( first === 0 ) { - return diff === 0; + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; } - }, + return ret; + } + }; +}); - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener }, - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - 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 && Sizzle.attr ? - result != null : - 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; + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } }, - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; } - } - } -}; -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } }; - -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) ); } -// Expose origPOS -// "global" as in regardless of relation to brackets/parens -Expr.match.globalPOS = origPOS; - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - if ( results ) { - results.push.apply( results, array ); - return results; - } +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { - return array; -}; + jQuery.event.special.change = { -// 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; + setup: function() { -// 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] ); + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); } - } - } + }); + }, - return ret; - }; -} + handle: function( event ) { + var elem = event.target; -var sortOrder, siblingCheck; + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } + teardown: function() { + jQuery.event.remove( this, "._change" ); - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; + return !rformElems.test( this.nodeName ); } - - 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; +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); +jQuery.fn.extend({ - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; - } else if ( !bup ) { - return 1; + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; } - // 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; + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; } - 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] ); - } + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } - - // 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; + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); } - - cur = cur.nextSibling; + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, - return 1; + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); +var isSimple = /^.[^:#\[\.,]*$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true }; -} - -// 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 = ""; +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } - // 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]); + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, - root.removeChild( form ); + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, - // release memory in IE - root = form = null; -})(); + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + }, - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } + cur = ret.push( cur ); + break; } - - 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__"; + return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); + }, - div.innerHTML = "

    "; + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } - 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[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = 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[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = 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, seed ) { - 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, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -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.globalPOS, - // 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" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], 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 ) ); - } + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } // Locate the position of the desired element return jQuery.inArray( @@ -5552,20 +5826,22 @@ jQuery.fn.extend({ 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 ) ); + return this.pushStack( jQuery.unique(all) ); }, - andSelf: function() { - return this.add( this.prevObject ); + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); } }); -// 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; +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; } jQuery.each({ @@ -5580,10 +5856,10 @@ jQuery.each({ return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); + return sibling( elem, "nextSibling" ); }, prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); + return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); @@ -5606,13 +5882,13 @@ jQuery.each({ contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); + jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); - if ( !runtil.test( name ) ) { + if ( name.slice( -5 ) !== "Until" ) { selector = until; } @@ -5620,25 +5896,35 @@ jQuery.each({ ret = jQuery.filter( selector, ret ); } - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } } - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { + var elem = elems[ 0 ]; + if ( not ) { expr = ":not(" + expr + ")"; } - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); }, dir: function( elem, dir, until ) { @@ -5654,19 +5940,6 @@ jQuery.extend({ 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 = []; @@ -5681,46 +5954,37 @@ jQuery.extend({ }); // 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; - +function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; }); - } 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 ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; }); + } + + if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); + return jQuery.filter( qualifier, elements, not ); } + + qualifier = jQuery.filter( qualifier, elements ); } - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } - - - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { @@ -5734,40 +5998,43 @@ function createSafeFragment( document ) { var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /]", "i"), + rnoInnerhtml = /<(?:script|style|link)/i, + manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /\/(java|ecma)script/i, - rcleanScript = /^\s*\s*$/g, + + // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "" ], legend: [ 1, "
    ", "
    " ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], thead: [ 1, "", "
    " ], tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] + td: [ 3, "", "
    " ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
    ", "
    " ] }, - safeFragment = createSafeFragment( document ); + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; -// IE can't serialize and + + */ -function copy(source, destination){ - if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); +function copy(source, destination, stackSource, stackDest) { + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', + "Can't copy! Making copies of Window or Scope instances is not supported."); + } + if (!destination) { destination = source; if (source) { if (isArray(source)) { - destination = copy(source, []); + destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); + } else if (isRegExp(source)) { + destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); + destination.lastIndex = source.lastIndex; } else if (isObject(source)) { - destination = copy(source, {}); + destination = copy(source, {}, stackSource, stackDest); } } } else { - if (source === destination) throw Error("Can't copy equivalent objects or arrays"); + if (source === destination) throw ngMinErr('cpi', + "Can't copy! Source and destination are identical."); + + stackSource = stackSource || []; + stackDest = stackDest || []; + + if (isObject(source)) { + var index = indexOf(stackSource, source); + if (index !== -1) return stackDest[index]; + + stackSource.push(source); + stackDest.push(destination); + } + + var result; if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { - destination.push(copy(source[i])); + result = copy(source[i], null, stackSource, stackDest); + if (isObject(source[i])) { + stackSource.push(source[i]); + stackDest.push(result); + } + destination.push(result); } } else { var h = destination.$$hashKey; - forEach(destination, function(value, key){ + forEach(destination, function(value, key) { delete destination[key]; }); for ( var key in source) { - destination[key] = copy(source[key]); + result = copy(source[key], null, stackSource, stackDest); + if (isObject(source[key])) { + stackSource.push(source[key]); + stackDest.push(result); + } + destination[key] = result; } setHashKey(destination,h); } + } return destination; } /** - * Create a shallow copy of an object + * Creates a shallow copy of an object, an array or a primitive */ function shallowCopy(src, dst) { - dst = dst || {}; + if (isArray(src)) { + dst = dst || []; + + for ( var i = 0; i < src.length; i++) { + dst[i] = src[i]; + } + } else if (isObject(src)) { + dst = dst || {}; - for(var key in src) { - if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { - dst[key] = src[key]; + for (var key in src) { + if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } } } - return dst; + return dst || src; } /** * @ngdoc function * @name angular.equals - * @function + * @module ng + * @kind function * * @description - * Determines if two objects or two values are equivalent. Supports value types, arrays and - * objects. + * Determines if two objects or two values are equivalent. Supports value types, regular + * expressions, arrays and objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. - * * Both objects or values are of the same type and all of their properties pass `===` comparison. - * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) - * - * During a property comparision, properties of `function` type and properties with names + * * Both objects or values are of the same type and all of their properties are equal by + * comparing them with `angular.equals`. + * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) + * * Both values represent the same regular expression (In JavaScript, + * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual + * representation matches). + * + * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). @@ -10060,6 +10770,7 @@ function equals(o1, o2) { if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { + if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for(key=0; key 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { @@ -10138,7 +10875,7 @@ function bind(self, fn) { function toJsonReplacer(key, value) { var val = value; - if (/^\$+/.test(key)) { + if (typeof key === 'string' && key.charAt(0) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; @@ -10155,16 +10892,19 @@ function toJsonReplacer(key, value) { /** * @ngdoc function * @name angular.toJson - * @function + * @module ng + * @kind function * * @description - * Serializes input into a JSON-formatted string. + * Serializes input into a JSON-formatted string. Properties with leading $ characters will be + * stripped since angular uses this notation internally. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. - * @returns {string} Jsonified string representing `obj`. + * @returns {string|undefined} JSON-ified string representing `obj`. */ function toJson(obj, pretty) { + if (typeof obj === 'undefined') return undefined; return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } @@ -10172,13 +10912,14 @@ function toJson(obj, pretty) { /** * @ngdoc function * @name angular.fromJson - * @function + * @module ng + * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. - * @returns {Object|Array|Date|string|number} Deserialized thingy. + * @returns {Object|Array|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) @@ -10188,7 +10929,9 @@ function fromJson(json) { function toBoolean(value) { - if (value && value.length !== 0) { + if (typeof value === 'function') { + value = true; + } else if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { @@ -10205,7 +10948,7 @@ function startingTag(element) { try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. - element.html(''); + element.empty(); } catch(e) {} // As Per DOM Standards var TEXT_NODE = 3; @@ -10224,17 +10967,43 @@ function startingTag(element) { ///////////////////////////////////////////////// +/** + * Tries to decode the URI component without throwing an exception. + * + * @private + * @param str value potential URI component to check. + * @returns {boolean} True if `value` can be decoded + * with the decodeURIComponent function. + */ +function tryDecodeURIComponent(value) { + try { + return decodeURIComponent(value); + } catch(e) { + // Ignore any invalid uri component + } +} + + /** * Parses an escaped url query string into key-value pairs. - * @returns Object.<(string|boolean)> + * @returns {Object.} */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue){ - if (keyValue) { - key_value = keyValue.split('='); - key = decodeURIComponent(key_value[0]); - obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; + forEach((keyValue || "").split('&'), function(keyValue) { + if ( keyValue ) { + key_value = keyValue.replace(/\+/g,'%20').split('='); + key = tryDecodeURIComponent(key_value[0]); + if ( isDefined(key) ) { + var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + if (!hasOwnProperty.call(obj, key)) { + obj[key] = val; + } else if(isArray(obj[key])) { + obj[key].push(val); + } else { + obj[key] = [obj[key],val]; + } + } } }); return obj; @@ -10243,14 +11012,22 @@ function parseKeyValue(/**string*/keyValue) { function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { - parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); + if (isArray(value)) { + forEach(value, function(arrayValue) { + parts.push(encodeUriQuery(key, true) + + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); + }); + } else { + parts.push(encodeUriQuery(key, true) + + (value === true ? '' : '=' + encodeUriQuery(value, true))); + } }); return parts.length ? parts.join('&') : ''; } /** - * We need our custom method because encodeURIComponent is too agressive and doesn't follow + * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar @@ -10270,7 +11047,7 @@ function encodeUriSegment(val) { /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be + * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" @@ -10291,7 +11068,8 @@ function encodeUriQuery(val, pctEncodeSpaces) { /** * @ngdoc directive - * @name ng.directive:ngApp + * @name ngApp + * @module ng * * @element ANY * @param {angular.Module} ngApp an optional application @@ -10299,22 +11077,39 @@ function encodeUriQuery(val, pctEncodeSpaces) { * * @description * - * Use this directive to auto-bootstrap an application. Only - * one directive can be used per HTML document. The directive - * designates the root of the application and is typically placed - * at the root of the page. - * - * In the example below if the `ngApp` directive would not be placed - * on the `html` element then the document would not be compiled - * and the `{{ 1+2 }}` would not be resolved to `3`. - * - * `ngApp` is the easiest way to bootstrap an application. - * - - - I can add: 1 + 2 = {{ 1+2 }} - - + * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive + * designates the **root element** of the application and is typically placed near the root element + * of the page - e.g. on the `` or `` tags. + * + * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` + * found in the document will be used to define the root element to auto-bootstrap as an + * application. To run multiple applications in an HTML document you must manually bootstrap them using + * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. + * + * You can specify an **AngularJS module** to be used as the root module for the application. This + * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and + * should contain the application code needed or have dependencies on other modules that will + * contain the code. See {@link angular.module} for more information. + * + * In the example below if the `ngApp` directive were not placed on the `html` element then the + * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` + * would not be resolved to `3`. + * + * `ngApp` is the easiest, and most common, way to bootstrap an application. + * + + +
    + I can add: {{a}} + {{b}} = {{ a+b }} +
    +
    + + angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { + $scope.a = 1; + $scope.b = 2; + }); + +
    * */ function angularInit(element, bootstrap) { @@ -10364,26 +11159,74 @@ function angularInit(element, bootstrap) { /** * @ngdoc function * @name angular.bootstrap + * @module ng * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * - * @param {Element} element DOM element which is the root of angular application. - * @param {Array=} modules an array of module declarations. See: {@link angular.module modules} - * @returns {AUTO.$injector} Returns the newly created injector for this app. + * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually. + * They must use {@link ng.directive:ngApp ngApp}. + * + * Angular will detect if it has been loaded into the browser more than once and only allow the + * first loaded script to be bootstrapped and will report a warning to the browser console for + * each of the subsequent scripts. This prevents strange results in applications, where otherwise + * multiple instances of Angular try to work on the DOM. + * + * + * + * + *
    + * + * + * + * + * + * + * + *
    {{heading}}
    {{fill}}
    + *
    + *
    + * + * var app = angular.module('multi-bootstrap', []) + * + * .controller('BrokenTable', function($scope) { + * $scope.headings = ['One', 'Two', 'Three']; + * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]]; + * }); + * + * + * it('should only insert one table cell for each item in $scope.fillings', function() { + * expect(element.all(by.css('td')).count()) + * .toBe(9); + * }); + * + *
    + * + * @param {DOMElement} element DOM element which is the root of angular application. + * @param {Array=} modules an array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * See: {@link angular.module modules} + * @returns {auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { - var resumeBootstrapInternal = function() { + var doBootstrap = function() { element = jqLite(element); + + if (element.injector()) { + var tag = (element[0] === document) ? 'document' : startingTag(element); + throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); + } + modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', - function(scope, element, compile, injector) { + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', + function(scope, element, compile, injector, animate) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); @@ -10396,7 +11239,7 @@ function bootstrap(element, modules) { var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { - return resumeBootstrapInternal(); + return doBootstrap(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); @@ -10404,12 +11247,12 @@ function bootstrap(element, modules) { forEach(extraModules, function(module) { modules.push(module); }); - resumeBootstrapInternal(); + doBootstrap(); }; } var SNAKE_CASE_REGEXP = /[A-Z]/g; -function snake_case(name, separator){ +function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); @@ -10419,18 +11262,22 @@ function snake_case(name, separator){ function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; - // reset to jQuery or default to us. - if (jQuery) { + // Use jQuery if it exists with proper functionality, otherwise default to us. + // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support. + if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, + isolateScope: JQLitePrototype.isolateScope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); - JQLitePatchJQueryRemove('remove', true); - JQLitePatchJQueryRemove('empty'); - JQLitePatchJQueryRemove('html'); + // Method signature: + // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) + jqLitePatchJQueryRemove('remove', true, true, false); + jqLitePatchJQueryRemove('empty', false, false, false); + jqLitePatchJQueryRemove('html', false, false, true); } else { jqLite = JQLite; } @@ -10442,7 +11289,7 @@ function bindJQuery() { */ function assertArg(arg, name, reason) { if (!arg) { - throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); + throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); } return arg; } @@ -10453,13 +11300,76 @@ function assertArgFn(arg, name, acceptArrayAnnotation) { } assertArg(isFunction(arg), name, 'not a function, got ' + - (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** - * @ngdoc interface + * throw error if the name given is hasOwnProperty + * @param {String} name the name to test + * @param {String} context the context in which the name is used, such as module or directive + */ +function assertNotHasOwnProperty(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); + } +} + +/** + * Return the value accessible from the object by path. Any undefined traversals are ignored + * @param {Object} obj starting object + * @param {String} path path to traverse + * @param {boolean} [bindFnToScope=true] + * @returns {Object} value as accessible by path + */ +//TODO(misko): this function needs to be removed +function getter(obj, path, bindFnToScope) { + if (!path) return obj; + var keys = path.split('.'); + var key; + var lastInstance = obj; + var len = keys.length; + + for (var i = 0; i < len; i++) { + key = keys[i]; + if (obj) { + obj = (lastInstance = obj)[key]; + } + } + if (!bindFnToScope && isFunction(obj)) { + return bind(lastInstance, obj); + } + return obj; +} + +/** + * Return the DOM siblings between the first and last node in the given array. + * @param {Array} array like object + * @returns {DOMElement} object containing the elements + */ +function getBlockElements(nodes) { + var startNode = nodes[0], + endNode = nodes[nodes.length - 1]; + if (startNode === endNode) { + return jqLite(startNode); + } + + var element = startNode; + var elements = [element]; + + do { + element = element.nextSibling; + if (!element) break; + elements.push(element); + } while (element !== endNode); + + return jqLite(elements); +} + +/** + * @ngdoc type * @name angular.Module + * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. @@ -10467,30 +11377,43 @@ function assertArgFn(arg, name, acceptArrayAnnotation) { function setupModuleLoader(window) { + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } - return ensure(ensure(window, 'angular', Object), 'module', function() { + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function() { /** @type {Object.} */ var modules = {}; /** * @ngdoc function * @name angular.module + * @module ng * @description * - * The `angular.module` is a global place for creating and registering Angular modules. All - * modules (angular core or 3rd party) that should be available to an application must be + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * + * When passed two or more arguments, a new module is created. If passed only one argument, an + * existing module (the name passed as the first argument to `module`) is retrieved. + * * * # Module * - * A module is a collocation of services, directives, filters, and configuration information. Module - * is used to configure the {@link AUTO.$injector $injector}. + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. * - *
    +     * ```js
          * // Create a new module
          * var myModule = angular.module('myModule', []);
          *
    @@ -10498,36 +11421,45 @@ function setupModuleLoader(window) {
          * myModule.value('appName', 'MyCoolApp');
          *
          * // configure existing services inside initialization blocks.
    -     * myModule.config(function($locationProvider) {
    +     * myModule.config(['$locationProvider', function($locationProvider) {
          *   // Configure existing providers
          *   $locationProvider.hashPrefix('!');
    -     * });
    -     * 
    + * }]); + * ``` * * Then you can create an injector and load your modules like this: * - *
    -     * var injector = angular.injector(['ng', 'MyModule'])
    -     * 
    + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. - * @param {Array.=} requires If specified then new module is being created. If unspecified then the - * the module is being retrieved for further configuration. - * @param {Function} configFn Optional configuration function for the module. Same as + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; + + assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { - throw Error('No module: ' + name); + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); } /** @type {!Array.>} */ @@ -10547,17 +11479,18 @@ function setupModuleLoader(window) { /** * @ngdoc property * @name angular.Module#requires - * @propertyOf angular.Module + * @module ng * @returns {Array.} List of module names which must be loaded before this module. * @description - * Holds the list of modules which the injector will load before the current module is loaded. + * Holds the list of modules which the injector will load before the current module is + * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name - * @propertyOf angular.Module + * @module ng * @returns {string} Name of the module. * @description */ @@ -10567,63 +11500,98 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#provider - * @methodOf angular.Module + * @module ng * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the service. + * @param {Function} providerType Construction function for creating new instance of the + * service. * @description - * See {@link AUTO.$provide#provider $provide.provider()}. + * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description - * See {@link AUTO.$provide#factory $provide.factory()}. + * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description - * See {@link AUTO.$provide#service $provide.service()}. + * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value - * @methodOf angular.Module + * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description - * See {@link AUTO.$provide#value $provide.value()}. + * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant - * @methodOf angular.Module + * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. - * See {@link AUTO.$provide#constant $provide.constant()}. + * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link ngAnimate.$animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), + /** * @ngdoc method * @name angular.Module#filter - * @methodOf angular.Module + * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description @@ -10634,8 +11602,9 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#controller - * @methodOf angular.Module - * @param {string} name Controller name. + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. @@ -10645,8 +11614,9 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#directive - * @methodOf angular.Module - * @param {string} name directive name + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description @@ -10657,18 +11627,20 @@ function setupModuleLoader(window) { /** * @ngdoc method * @name angular.Module#config - * @methodOf angular.Module + * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#providers_provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run - * @methodOf angular.Module + * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description @@ -10697,7 +11669,7 @@ function setupModuleLoader(window) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; - } + }; } }); }; @@ -10705,9 +11677,87 @@ function setupModuleLoader(window) { } +/* global angularModule: true, + version: true, + + $LocaleProvider, + $CompileProvider, + + htmlAnchorDirective, + inputDirective, + inputDirective, + formDirective, + scriptDirective, + selectDirective, + styleDirective, + optionDirective, + ngBindDirective, + ngBindHtmlDirective, + ngBindTemplateDirective, + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective, + ngCspDirective, + ngCloakDirective, + ngControllerDirective, + ngFormDirective, + ngHideDirective, + ngIfDirective, + ngIncludeDirective, + ngIncludeFillContentDirective, + ngInitDirective, + ngNonBindableDirective, + ngPluralizeDirective, + ngRepeatDirective, + ngShowDirective, + ngStyleDirective, + ngSwitchDirective, + ngSwitchWhenDirective, + ngSwitchDefaultDirective, + ngOptionsDirective, + ngTranscludeDirective, + ngModelDirective, + ngListDirective, + ngChangeDirective, + requiredDirective, + requiredDirective, + ngValueDirective, + ngAttributeAliasDirectives, + ngEventDirectives, + + $AnchorScrollProvider, + $AnimateProvider, + $BrowserProvider, + $CacheFactoryProvider, + $ControllerProvider, + $DocumentProvider, + $ExceptionHandlerProvider, + $FilterProvider, + $InterpolateProvider, + $IntervalProvider, + $HttpProvider, + $HttpBackendProvider, + $LocationProvider, + $LogProvider, + $ParseProvider, + $RootScopeProvider, + $QProvider, + $$SanitizeUriProvider, + $SceProvider, + $SceDelegateProvider, + $SnifferProvider, + $TemplateCacheProvider, + $TimeoutProvider, + $$RAFProvider, + $$AsyncCallbackProvider, + $WindowProvider +*/ + + /** - * @ngdoc property + * @ngdoc object * @name angular.version + * @module ng * @description * An object that contains information about the current AngularJS version. This object has the * following properties: @@ -10719,11 +11769,11 @@ function setupModuleLoader(window) { * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { - full: '1.0.7', // all of these placeholder strings will be replaced by grunt's + full: '1.2.22', // all of these placeholder strings will be replaced by grunt's major: 1, // package task - minor: 0, - dot: 7, - codeName: 'monochromatic-rainbow' + minor: 2, + dot: 22, + codeName: 'finicky-pleasure' }; @@ -10736,11 +11786,11 @@ function publishExternalAPI(angular){ 'element': jqLite, 'forEach': forEach, 'injector': createInjector, - 'noop':noop, - 'bind':bind, + 'noop': noop, + 'bind': bind, 'toJson': toJson, 'fromJson': fromJson, - 'identity':identity, + 'identity': identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, @@ -10753,7 +11803,9 @@ function publishExternalAPI(angular){ 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, - 'callbacks': {counter: 0} + 'callbacks': {counter: 0}, + '$$minErr': minErr, + '$$csp': csp }); angularModule = setupModuleLoader(window); @@ -10765,6 +11817,10 @@ function publishExternalAPI(angular){ angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { + // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. + $provide.provider({ + $$sanitizeUri: $$SanitizeUriProvider + }); $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, @@ -10776,29 +11832,27 @@ function publishExternalAPI(angular){ style: styleDirective, option: optionDirective, ngBind: ngBindDirective, - ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, + ngBindHtml: ngBindHtmlDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, - ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, + ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, - ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, - ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, @@ -10807,10 +11861,14 @@ function publishExternalAPI(angular){ ngRequired: requiredDirective, ngValue: ngValueDirective }). + directive({ + ngInclude: ngIncludeFillContentDirective + }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, + $animate: $AnimateProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, @@ -10818,24 +11876,33 @@ function publishExternalAPI(angular){ $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, + $interval: $IntervalProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, - $route: $RouteProvider, - $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, + $sce: $SceProvider, + $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, - $window: $WindowProvider + $window: $WindowProvider, + $$rAF: $$RAFProvider, + $$asyncCallback : $$AsyncCallbackProvider }); } ]); } +/* global JQLitePrototype: true, + addEventListenerFn: true, + removeEventListenerFn: true, + BOOLEAN_ATTR: true +*/ + ////////////////////////////////// //JQLite ////////////////////////////////// @@ -10843,67 +11910,82 @@ function publishExternalAPI(angular){ /** * @ngdoc function * @name angular.element - * @function + * @module ng + * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. - * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if - * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite - * implementation (commonly referred to as jqLite). - * - * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` - * event fired. - * - * jqLite is a tiny, API-compatible subset of jQuery that allows - * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality - * within a very small footprint, so only a subset of the jQuery API - methods, arguments and - * invocation styles - are supported. - * - * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never - * raw DOM references. - * - * ## Angular's jQuery lite provides the following methods: - * - * - [addClass()](http://api.jquery.com/addClass/) - * - [after()](http://api.jquery.com/after/) - * - [append()](http://api.jquery.com/append/) - * - [attr()](http://api.jquery.com/attr/) - * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces - * - [children()](http://api.jquery.com/children/) - Does not support selectors - * - [clone()](http://api.jquery.com/clone/) - * - [contents()](http://api.jquery.com/contents/) - * - [css()](http://api.jquery.com/css/) - * - [data()](http://api.jquery.com/data/) - * - [eq()](http://api.jquery.com/eq/) - * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name - * - [hasClass()](http://api.jquery.com/hasClass/) - * - [html()](http://api.jquery.com/html/) - * - [next()](http://api.jquery.com/next/) - Does not support selectors - * - [parent()](http://api.jquery.com/parent/) - Does not support selectors - * - [prepend()](http://api.jquery.com/prepend/) - * - [prop()](http://api.jquery.com/prop/) - * - [ready()](http://api.jquery.com/ready/) - * - [remove()](http://api.jquery.com/remove/) - * - [removeAttr()](http://api.jquery.com/removeAttr/) - * - [removeClass()](http://api.jquery.com/removeClass/) - * - [removeData()](http://api.jquery.com/removeData/) - * - [replaceWith()](http://api.jquery.com/replaceWith/) - * - [text()](http://api.jquery.com/text/) - * - [toggleClass()](http://api.jquery.com/toggleClass/) - * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers. - * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces - * - [val()](http://api.jquery.com/val/) - * - [wrap()](http://api.jquery.com/wrap/) - * - * ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite: * + * If jQuery is available, `angular.element` is an alias for the + * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` + * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + * + *
    jqLite is a tiny, API-compatible subset of jQuery that allows + * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most + * commonly needed functionality with the goal of having a very small footprint.
    + * + * To use jQuery, simply load it before `DOMContentLoaded` event fired. + * + *
    **Note:** all element references in Angular are always wrapped with jQuery or + * jqLite; they are never raw DOM references.
    + * + * ## Angular's jqLite + * jqLite provides only the following jQuery methods: + * + * - [`addClass()`](http://api.jquery.com/addClass/) + * - [`after()`](http://api.jquery.com/after/) + * - [`append()`](http://api.jquery.com/append/) + * - [`attr()`](http://api.jquery.com/attr/) + * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData + * - [`children()`](http://api.jquery.com/children/) - Does not support selectors + * - [`clone()`](http://api.jquery.com/clone/) + * - [`contents()`](http://api.jquery.com/contents/) + * - [`css()`](http://api.jquery.com/css/) + * - [`data()`](http://api.jquery.com/data/) + * - [`empty()`](http://api.jquery.com/empty/) + * - [`eq()`](http://api.jquery.com/eq/) + * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name + * - [`hasClass()`](http://api.jquery.com/hasClass/) + * - [`html()`](http://api.jquery.com/html/) + * - [`next()`](http://api.jquery.com/next/) - Does not support selectors + * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData + * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors + * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors + * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors + * - [`prepend()`](http://api.jquery.com/prepend/) + * - [`prop()`](http://api.jquery.com/prop/) + * - [`ready()`](http://api.jquery.com/ready/) + * - [`remove()`](http://api.jquery.com/remove/) + * - [`removeAttr()`](http://api.jquery.com/removeAttr/) + * - [`removeClass()`](http://api.jquery.com/removeClass/) + * - [`removeData()`](http://api.jquery.com/removeData/) + * - [`replaceWith()`](http://api.jquery.com/replaceWith/) + * - [`text()`](http://api.jquery.com/text/) + * - [`toggleClass()`](http://api.jquery.com/toggleClass/) + * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. + * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces + * - [`val()`](http://api.jquery.com/val/) + * - [`wrap()`](http://api.jquery.com/wrap/) + * + * ## jQuery/jqLite Extras + * Angular also provides the following additional methods and events to both jQuery and jqLite: + * + * ### Events + * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event + * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM + * element before it is removed. + * + * ### Methods * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. - * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current + * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current * element or its parent. + * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the + * current element. This getter should be used only on elements that contain a directive which starts a new isolate + * scope. Calling `scope()` on this element always returns the original non-isolate scope. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * @@ -10911,8 +11993,9 @@ function publishExternalAPI(angular){ * @returns {Object} jQuery object. */ +JQLite.expando = 'ng339'; + var jqCache = JQLite.cache = {}, - jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} @@ -10921,11 +12004,20 @@ var jqCache = JQLite.cache = {}, ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); +/* + * !!! This is an undocumented "private" function !!! + */ +var jqData = JQLite._data = function(node) { + //jQuery always returns an object on cache miss + return this.cache[node[this.expando]] || {}; +}; + function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; +var jqLiteMinErr = minErr('jqLite'); /** * Converts snake_case to camelCase. @@ -10943,37 +12035,39 @@ function camelCase(name) { ///////////////////////////////////////////// // jQuery mutation patch // -// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a +// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// -function JQLitePatchJQueryRemove(name, dispatchThis) { +function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; - function removePatch() { - var list = [this], + function removePatch(param) { + // jshint -W040 + var list = filterElems && param ? [this.filter(param)] : [this], fireEvent = dispatchThis, set, setIndex, setLength, - element, childIndex, childLength, children, - fns, events; - - while(list.length) { - set = list.shift(); - for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { - element = jqLite(set[setIndex]); - if (fireEvent) { - element.triggerHandler('$destroy'); - } else { - fireEvent = !fireEvent; - } - for(childIndex = 0, childLength = (children = element.children()).length; - childIndex < childLength; - childIndex++) { - list.push(jQuery(children[childIndex])); + element, childIndex, childLength, children; + + if (!getterIfNoArguments || param != null) { + while(list.length) { + set = list.shift(); + for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { + element = jqLite(set[setIndex]); + if (fireEvent) { + element.triggerHandler('$destroy'); + } else { + fireEvent = !fireEvent; + } + for(childIndex = 0, childLength = (children = element.children()).length; + childIndex < childLength; + childIndex++) { + list.push(jQuery(children[childIndex])); + } } } } @@ -10981,45 +12075,115 @@ function JQLitePatchJQueryRemove(name, dispatchThis) { } } -///////////////////////////////////////////// -function JQLite(element) { - if (element instanceof JQLite) { - return element; - } - if (!(this instanceof JQLite)) { - if (isString(element) && element.charAt(0) != '<') { - throw Error('selectors not implemented'); - } - return new JQLite(element); - } +var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; +var HTML_REGEXP = /<|&#?\w+;/; +var TAG_NAME_REGEXP = /<([\w:]+)/; +var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; - if (isString(element)) { - var div = document.createElement('div'); - // Read about the NoScope elements here: - // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx - div.innerHTML = '
     
    ' + element; // IE insanity to make NoScope elements work! - div.removeChild(div.firstChild); // remove the superfluous div - JQLiteAddNodes(this, div.childNodes); - this.remove(); // detach the elements from the temporary DOM div. - } else { - JQLiteAddNodes(this, element); - } -} +var wrapMap = { + 'option': [1, ''], -function JQLiteClone(element) { - return element.cloneNode(true); -} + 'thead': [1, '', '
    '], + 'col': [2, '', '
    '], + 'tr': [2, '', '
    '], + 'td': [3, '', '
    '], + '_default': [0, "", ""] +}; -function JQLiteDealoc(element){ - JQLiteRemoveData(element); +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function jqLiteIsTextNode(html) { + return !HTML_REGEXP.test(html); +} + +function jqLiteBuildFragment(html, context) { + var elem, tmp, tag, wrap, + fragment = context.createDocumentFragment(), + nodes = [], i, j, jj; + + if (jqLiteIsTextNode(html)) { + // Convert non-html into a text node + nodes.push(context.createTextNode(html)); + } else { + tmp = fragment.appendChild(context.createElement('div')); + // Convert html into DOM nodes + tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); + wrap = wrapMap[tag] || wrapMap._default; + tmp.innerHTML = '
     
    ' + + wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; + tmp.removeChild(tmp.firstChild); + + // Descend through wrappers to the right content + i = wrap[0]; + while (i--) { + tmp = tmp.lastChild; + } + + for (j=0, jj=tmp.childNodes.length; j -1); } -function JQLiteRemoveClass(element, cssClasses) { - if (cssClasses) { +function jqLiteRemoveClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { forEach(cssClasses.split(' '), function(cssClass) { - element.className = trim( - (" " + element.className + " ") + element.setAttribute('class', trim( + (" " + (element.getAttribute('class') || '') + " ") .replace(/[\n\t]/g, " ") - .replace(" " + trim(cssClass) + " ", " ") + .replace(" " + trim(cssClass) + " ", " ")) ); }); } } -function JQLiteAddClass(element, cssClasses) { - if (cssClasses) { +function jqLiteAddClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { + var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') + .replace(/[\n\t]/g, " "); + forEach(cssClasses.split(' '), function(cssClass) { - if (!JQLiteHasClass(element, cssClass)) { - element.className = trim(element.className + ' ' + trim(cssClass)); + cssClass = trim(cssClass); + if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { + existingClasses += cssClass + ' '; } }); + + element.setAttribute('class', trim(existingClasses)); } } -function JQLiteAddNodes(root, elements) { +function jqLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements @@ -11131,22 +12309,36 @@ function JQLiteAddNodes(root, elements) { } } -function JQLiteController(element, name) { - return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); +function jqLiteController(element, name) { + return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } -function JQLiteInheritedData(element, name, value) { - element = jqLite(element); - +function jqLiteInheritedData(element, name, value) { // if element is the document object work with the html element instead // this makes $(document).scope() possible - if(element[0].nodeType == 9) { - element = element.find('html'); + if(element.nodeType == 9) { + element = element.documentElement; + } + var names = isArray(name) ? name : [name]; + + while (element) { + for (var i = 0, ii = names.length; i < ii; i++) { + if ((value = jqLite.data(element, names[i])) !== undefined) return value; + } + + // If dealing with a document fragment node with a host element, and no parent, use the host + // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM + // to lookup parent controllers. + element = element.parentNode || (element.nodeType === 11 && element.host); } +} - while (element.length) { - if (value = element.data(name)) return value; - element = element.parent(); +function jqLiteEmpty(element) { + for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { + jqLiteDealoc(childNodes[i]); + } + while (element.firstChild) { + element.removeChild(element.firstChild); } } @@ -11163,9 +12355,16 @@ var JQLitePrototype = JQLite.prototype = { fn(); } - this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - JQLite(window).bind('load', trigger); // fallback to window.onload for others + // check if document already is loaded + if (document.readyState === 'complete'){ + setTimeout(trigger); + } else { + this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 + // we can not use jqLite since we are not done loading and jQuery could be loaded later. + // jshint -W064 + JQLite(window).on('load', trigger); // fallback to window.onload for others + // jshint +W064 + } }, toString: function() { var value = []; @@ -11189,11 +12388,11 @@ var JQLitePrototype = JQLite.prototype = { // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; -forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { +forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; -forEach('input,select,option,textarea,button,form'.split(','), function(value) { +forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); @@ -11206,24 +12405,37 @@ function getBooleanAttrName(element, name) { } forEach({ - data: JQLiteData, - inheritedData: JQLiteInheritedData, + data: jqLiteData, + removeData: jqLiteRemoveData +}, function(fn, name) { + JQLite[name] = fn; +}); + +forEach({ + data: jqLiteData, + inheritedData: jqLiteInheritedData, scope: function(element) { - return JQLiteInheritedData(element, '$scope'); + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); + }, + + isolateScope: function(element) { + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); }, - controller: JQLiteController , + controller: jqLiteController, injector: function(element) { - return JQLiteInheritedData(element, '$injector'); + return jqLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, - hasClass: JQLiteHasClass, + hasClass: jqLiteHasClass, css: function(element, name, value) { name = camelCase(name); @@ -11286,27 +12498,38 @@ forEach({ } }, - text: extend((msie < 9) - ? function(element, value) { - if (element.nodeType == 1 /** Element */) { - if (isUndefined(value)) - return element.innerText; - element.innerText = value; - } else { - if (isUndefined(value)) - return element.nodeValue; - element.nodeValue = value; - } + text: (function() { + var NODE_TYPE_TEXT_PROPERTY = []; + if (msie < 9) { + NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ + } else { + NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ + } + getText.$dv = ''; + return getText; + + function getText(element, value) { + var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]; + if (isUndefined(value)) { + return textProp ? element[textProp] : ''; } - : function(element, value) { - if (isUndefined(value)) { - return element.textContent; - } - element.textContent = value; - }, {$dv:''}), + element[textProp] = value; + } + })(), val: function(element, value) { if (isUndefined(value)) { + if (nodeName_(element) === 'SELECT' && element.multiple) { + var result = []; + forEach(element.options, function (option) { + if (option.selected) { + result.push(option.value || option.text); + } + }); + return result.length === 0 ? null : result; + } return element.value; } element.value = value; @@ -11317,25 +12540,30 @@ forEach({ return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - JQLiteDealoc(childNodes[i]); + jqLiteDealoc(childNodes[i]); } element.innerHTML = value; - } + }, + + empty: jqLiteEmpty }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; + var nodeCount = this.length; - // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it + // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. - if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { + // jqLiteEmpty takes no arguments but is a setter. + if (fn !== jqLiteEmpty && + (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values - for(i=0; i < this.length; i++) { - if (fn === JQLiteData) { + for (i = 0; i < nodeCount; i++) { + if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { @@ -11348,18 +12576,24 @@ forEach({ return this; } else { // we are a read, so read the first child. - if (this.length) - return fn(this[0], arg1, arg2); + // TODO: do we still need this? + var value = fn.$dv; + // Only if we have $dv do we iterate over all, otherwise it is just the first element. + var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; + for (var j = 0; j < jj; j++) { + var nodeValue = fn(this[j], arg1, arg2); + value = value ? value + nodeValue : nodeValue; + } + return value; } } else { // we are a write, so apply to all children - for(i=0; i < this.length; i++) { + for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } - return fn.$dv; }; }); @@ -11391,10 +12625,13 @@ function createEventHandler(element, events) { } event.isDefaultPrevented = function() { - return event.defaultPrevented; + return event.defaultPrevented || event.returnValue === false; }; - forEach(events[type || event.type], function(fn) { + // Copy event handlers in case event handlers array is modified during execution. + var eventHandlersCopy = shallowCopy(events[type || event.type] || []); + + forEach(eventHandlersCopy, function(fn) { fn.call(element, event); }); @@ -11422,16 +12659,18 @@ function createEventHandler(element, events) { // selector. ////////////////////////////////////////// forEach({ - removeData: JQLiteRemoveData, + removeData: jqLiteRemoveData, + + dealoc: jqLiteDealoc, - dealoc: JQLiteDealoc, + on: function onFn(element, type, fn, unsupported){ + if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); - bind: function bindFn(element, type, fn){ - var events = JQLiteExpandoStore(element, 'events'), - handle = JQLiteExpandoStore(element, 'handle'); + var events = jqLiteExpandoStore(element, 'events'), + handle = jqLiteExpandoStore(element, 'handle'); - if (!events) JQLiteExpandoStore(element, 'events', events = {}); - if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); + if (!events) jqLiteExpandoStore(element, 'events', events = {}); + if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; @@ -11440,6 +12679,7 @@ forEach({ if (type == 'mouseenter' || type == 'mouseleave') { var contains = document.body.contains || document.body.compareDocumentPosition ? function( a, b ) { + // jshint bitwise: false var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( @@ -11457,39 +12697,52 @@ forEach({ } } return false; - }; + }; events[type] = []; - - // Refer to jQuery's implementation of mouseenter & mouseleave + + // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 - var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"} - bindFn(element, eventmap[type], function(event) { - var ret, target = this, related = event.relatedTarget; + var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; + + onFn(element, eventmap[type], function(event) { + var target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !contains(target, related)) ){ handle(event, type); - } - + } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } - eventFns = events[type] + eventFns = events[type]; } eventFns.push(fn); }); }, - unbind: JQLiteUnbind, + off: jqLiteOff, + + one: function(element, type, fn) { + element = jqLite(element); + + //add the listener twice so that when it is called + //you can remove the original function and still be + //able to call element.off(ev, fn) normally + element.on(type, function onFn() { + element.off(type, fn); + element.off(type, onFn); + }); + element.on(type, fn); + }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; - JQLiteDealoc(element); + jqLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); @@ -11510,13 +12763,14 @@ forEach({ }, contents: function(element) { - return element.childNodes || []; + return element.contentDocument || element.childNodes || []; }, append: function(element, node) { forEach(new JQLite(node), function(child){ - if (element.nodeType === 1) + if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); + } }); }, @@ -11524,12 +12778,7 @@ forEach({ if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ - if (index) { - element.insertBefore(child, index); - } else { - element.appendChild(child); - index = child; - } + element.insertBefore(child, index); }); } }, @@ -11544,7 +12793,7 @@ forEach({ }, remove: function(element) { - JQLiteDealoc(element); + jqLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, @@ -11557,14 +12806,19 @@ forEach({ }); }, - addClass: JQLiteAddClass, - removeClass: JQLiteRemoveClass, + addClass: jqLiteAddClass, + removeClass: jqLiteRemoveClass, toggleClass: function(element, selector, condition) { - if (isUndefined(condition)) { - condition = !JQLiteHasClass(element, selector); + if (selector) { + forEach(selector.split(' '), function(className){ + var classCondition = condition; + if (isUndefined(classCondition)) { + classCondition = !jqLiteHasClass(element, className); + } + (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); + }); } - (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { @@ -11586,37 +12840,70 @@ forEach({ }, find: function(element, selector) { - return element.getElementsByTagName(selector); + if (element.getElementsByTagName) { + return element.getElementsByTagName(selector); + } else { + return []; + } }, - clone: JQLiteClone, + clone: jqLiteClone, - triggerHandler: function(element, eventName) { - var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; + triggerHandler: function(element, event, extraParameters) { - forEach(eventFns, function(fn) { - fn.call(element, null); - }); + var dummyEvent, eventFnsCopy, handlerArgs; + var eventName = event.type || event; + var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; + + if (eventFns) { + + // Create a dummy event to pass to the handlers + dummyEvent = { + preventDefault: function() { this.defaultPrevented = true; }, + isDefaultPrevented: function() { return this.defaultPrevented === true; }, + stopPropagation: noop, + type: eventName, + target: element + }; + + // If a custom event was provided then extend our dummy event with it + if (event.type) { + dummyEvent = extend(dummyEvent, event); + } + + // Copy event handlers in case event handlers array is modified during execution. + eventFnsCopy = shallowCopy(eventFns); + handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; + + forEach(eventFnsCopy, function(fn) { + fn.apply(element, handlerArgs); + }); + + } } }, function(fn, name){ /** * chaining functions */ - JQLite.prototype[name] = function(arg1, arg2) { + JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; for(var i=0; i < this.length; i++) { - if (value == undefined) { - value = fn(this[i], arg1, arg2); - if (value !== undefined) { + if (isUndefined(value)) { + value = fn(this[i], arg1, arg2, arg3); + if (isDefined(value)) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { - JQLiteAddNodes(value, fn(this[i], arg1, arg2)); + jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); } } - return value == undefined ? this : value; + return isDefined(value) ? value : this; }; + + // bind legacy bind/unbind to on/off + JQLite.prototype.bind = JQLite.prototype.on; + JQLite.prototype.unbind = JQLite.prototype.off; }); /** @@ -11631,16 +12918,16 @@ forEach({ * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ -function hashKey(obj) { +function hashKey(obj, nextUidFn) { var objType = typeof obj, key; - if (objType == 'object' && obj !== null) { + if (objType == 'function' || (objType == 'object' && obj !== null)) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { - key = obj.$$hashKey = nextUid(); + key = obj.$$hashKey = (nextUidFn || nextUid)(); } } else { key = obj; @@ -11652,7 +12939,13 @@ function hashKey(obj) { /** * HashMap which can use objects as keys */ -function HashMap(array){ +function HashMap(array, isolatedUid) { + if (isolatedUid) { + var uid = 0; + this.nextUid = function() { + return ++uid; + }; + } forEach(array, this.put, this); } HashMap.prototype = { @@ -11662,15 +12955,15 @@ HashMap.prototype = { * @param value value to store can be any type */ put: function(key, value) { - this[hashKey(key)] = value; + this[hashKey(key, this.nextUid)] = value; }, /** * @param key - * @returns the value for the key + * @returns {Object} the value for the key */ get: function(key) { - return this[hashKey(key)]; + return this[hashKey(key, this.nextUid)]; }, /** @@ -11678,60 +12971,17 @@ HashMap.prototype = { * @param key */ remove: function(key) { - var value = this[key = hashKey(key)]; + var value = this[key = hashKey(key, this.nextUid)]; delete this[key]; return value; } }; -/** - * A map where multiple values can be added to the same key such that they form a queue. - * @returns {HashQueueMap} - */ -function HashQueueMap() {} -HashQueueMap.prototype = { - /** - * Same as array push, but using an array as the value for the hash - */ - push: function(key, value) { - var array = this[key = hashKey(key)]; - if (!array) { - this[key] = [value]; - } else { - array.push(value); - } - }, - - /** - * Same as array shift, but using an array as the value for the hash - */ - shift: function(key) { - var array = this[key = hashKey(key)]; - if (array) { - if (array.length == 1) { - delete this[key]; - return array[0]; - } else { - return array.shift(); - } - } - }, - - /** - * return the first item without deleting it - */ - peek: function(key) { - var array = this[hashKey(key)]; - if (array) { - return array[0]; - } - } -}; - /** * @ngdoc function + * @module ng * @name angular.injector - * @function + * @kind function * * @description * Creates an injector function that can be used for retrieving services as well as for @@ -11740,11 +12990,11 @@ HashQueueMap.prototype = { * @param {Array.} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. - * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. + * @returns {function()} Injector function. See {@link auto.$injector $injector}. * * @example * Typical usage - *
    + * ```js
      *   // create an injector
      *   var $injector = angular.injector(['ng']);
      *
    @@ -11754,38 +13004,63 @@ HashQueueMap.prototype = {
      *     $compile($document)($rootScope);
      *     $rootScope.$digest();
      *   });
    - * 
    + * ``` + * + * Sometimes you want to get access to the injector of a currently running Angular app + * from outside Angular. Perhaps, you want to inject and compile some markup after the + * application has been bootstrapped. You can do this using the extra `injector()` added + * to JQuery/jqLite elements. See {@link angular.element}. + * + * *This is fairly rare but could be the case if a third party library is injecting the + * markup.* + * + * In the following example a new block of HTML containing a `ng-controller` + * directive is added to the end of the document body by JQuery. We then compile and link + * it into the current AngularJS scope. + * + * ```js + * var $div = $('
    {{content.label}}
    '); + * $(document.body).append($div); + * + * angular.element(document).injector().invoke(function($compile) { + * var scope = angular.element($div).scope(); + * $compile($div)(scope); + * }); + * ``` */ /** - * @ngdoc overview - * @name AUTO + * @ngdoc module + * @name auto * @description * - * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. + * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; +var $injectorMinErr = minErr('$injector'); function annotate(fn) { var $inject, fnText, argDecl, last; - if (typeof fn == 'function') { + if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; - fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_ARGS); - forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ - arg.replace(FN_ARG, function(all, underscore, name){ - $inject.push(name); + if (fn.length) { + fnText = fn.toString().replace(STRIP_COMMENTS, ''); + argDecl = fnText.match(FN_ARGS); + forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ + arg.replace(FN_ARG, function(all, underscore, name){ + $inject.push(name); + }); }); - }); + } fn.$inject = $inject; } } else if (isArray(fn)) { @@ -11801,32 +13076,32 @@ function annotate(fn) { /////////////////////////////////////// /** - * @ngdoc object - * @name AUTO.$injector - * @function + * @ngdoc service + * @name $injector + * @kind function * * @description * * `$injector` is used to retrieve object instances as defined by - * {@link AUTO.$provide provider}, instantiate types, invoke methods, + * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * - *
    + * ```js
      *   var $injector = angular.injector();
      *   expect($injector.get('$injector')).toBe($injector);
      *   expect($injector.invoke(function($injector){
      *     return $injector;
      *   }).toBe($injector);
    - * 
    + * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * - *
    + * ```js
      *   // inferred (only works if code not minified/obfuscated)
      *   $injector.invoke(function(serviceA){});
      *
    @@ -11837,16 +13112,16 @@ function annotate(fn) {
      *
      *   // inline
      *   $injector.invoke(['serviceA', function(serviceA){}]);
    - * 
    + * ``` * * ## Inference * - * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be - * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation - * tools since these tools change the argument names. + * In JavaScript calling `toString()` on a function returns the function definition. The definition + * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with + * minification, and obfuscation tools since these tools change the argument names. * * ## `$inject` Annotation - * By adding a `$inject` property onto a function the injection parameters can be specified. + * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. @@ -11854,8 +13129,7 @@ function annotate(fn) { /** * @ngdoc method - * @name AUTO.$injector#get - * @methodOf AUTO.$injector + * @name $injector#get * * @description * Return an instance of the service. @@ -11866,48 +13140,60 @@ function annotate(fn) { /** * @ngdoc method - * @name AUTO.$injector#invoke - * @methodOf AUTO.$injector + * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * - * @param {!function} fn The function to invoke. The function arguments come form the function annotation. + * @param {!Function} fn The function to invoke. Function parameters are injected according to the + * {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. - * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before - * the `$injector` is consulted. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method - * @name AUTO.$injector#instantiate - * @methodOf AUTO.$injector + * @name $injector#has + * + * @description + * Allows the user to query if the particular service exists. + * + * @param {string} Name of the service to query. + * @returns {boolean} returns true if injector has given service. + */ + +/** + * @ngdoc method + * @name $injector#instantiate * @description - * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies - * all of the arguments to the constructor function as specified by the constructor annotation. + * Create a new instance of JS type. The method takes a constructor function, invokes the new + * operator, and supplies all of the arguments to the constructor function as specified by the + * constructor annotation. * - * @param {function} Type Annotated constructor function. - * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before - * the `$injector` is consulted. + * @param {Function} Type Annotated constructor function. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method - * @name AUTO.$injector#annotate - * @methodOf AUTO.$injector + * @name $injector#annotate * * @description - * Returns an array of service names which the function is requesting for injection. This API is used by the injector - * to determine which services need to be injected into the function when the function is invoked. There are three - * ways in which the function can be annotated with the needed dependencies. + * Returns an array of service names which the function is requesting for injection. This API is + * used by the injector to determine which services need to be injected into the function when the + * function is invoked. There are three ways in which the function can be annotated with the needed + * dependencies. * * # Argument names * - * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting - * the function into a string using `toString()` method and extracting the argument names. - *
    + * The simplest form is to extract the dependencies from the arguments of the function. This is done
    + * by converting the function into a string using `toString()` method and extracting the argument
    + * names.
    + * ```js
      *   // Given
      *   function MyController($scope, $route) {
      *     // ...
    @@ -11915,34 +13201,34 @@ function annotate(fn) {
      *
      *   // Then
      *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
    - * 
    + * ``` * - * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies - * are supported. + * This method does not work with code minification / obfuscation. For this reason the following + * annotation strategies are supported. * * # The `$inject` property * - * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of - * services to be injected into the function. - *
    + * If a function has an `$inject` property and its value is an array of strings, then the strings
    + * represent names of services to be injected into the function.
    + * ```js
      *   // Given
      *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
      *     // ...
      *   }
      *   // Define function dependencies
    - *   MyController.$inject = ['$scope', '$route'];
    + *   MyController['$inject'] = ['$scope', '$route'];
      *
      *   // Then
      *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
    - * 
    + * ``` * * # The array notation * - * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very - * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives - * minification is a better choice: + * It is often desirable to inline Injected functions and that's when setting the `$inject` property + * is very inconvenient. In these situations using the array notation to specify the dependencies in + * a way that survives minification is a better choice: * - *
    + * ```js
      *   // We wish to write this (not minification / obfuscation safe)
      *   injector.invoke(function($compile, $rootScope) {
      *     // ...
    @@ -11964,10 +13250,10 @@ function annotate(fn) {
      *   expect(injector.annotate(
      *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
      *    ).toEqual(['$compile', '$rootScope']);
    - * 
    + * ``` * - * @param {function|Array.} fn Function for which dependent service names need to be retrieved as described - * above. + * @param {Function|Array.} fn Function for which dependent service names need to + * be retrieved as described above. * * @returns {Array.} The names of the services which the function requires. */ @@ -11976,148 +13262,305 @@ function annotate(fn) { /** - * @ngdoc object - * @name AUTO.$provide + * @ngdoc service + * @name $provide * * @description * - * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. - * The providers share the same name as the instance they create with `Provider` suffixed to them. - * - * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of - * a service. The Provider can have additional methods which would allow for configuration of the provider. - * - *
    - *   function GreetProvider() {
    - *     var salutation = 'Hello';
    - *
    - *     this.salutation = function(text) {
    - *       salutation = text;
    - *     };
    - *
    - *     this.$get = function() {
    - *       return function (name) {
    - *         return salutation + ' ' + name + '!';
    - *       };
    - *     };
    - *   }
    - *
    - *   describe('Greeter', function(){
    - *
    - *     beforeEach(module(function($provide) {
    - *       $provide.provider('greet', GreetProvider);
    - *     }));
    - *
    - *     it('should greet', inject(function(greet) {
    - *       expect(greet('angular')).toEqual('Hello angular!');
    - *     }));
    - *
    - *     it('should allow configuration of salutation', function() {
    - *       module(function(greetProvider) {
    - *         greetProvider.salutation('Ahoj');
    - *       });
    - *       inject(function(greet) {
    - *         expect(greet('angular')).toEqual('Ahoj angular!');
    - *       });
    - *     });
    - * 
    + * The {@link auto.$provide $provide} service has a number of methods for registering components + * with the {@link auto.$injector $injector}. Many of these functions are also exposed on + * {@link angular.Module}. + * + * An Angular **service** is a singleton object created by a **service factory**. These **service + * factories** are functions which, in turn, are created by a **service provider**. + * The **service providers** are constructor functions. When instantiated they must contain a + * property called `$get`, which holds the **service factory** function. + * + * When you request a service, the {@link auto.$injector $injector} is responsible for finding the + * correct **service provider**, instantiating it and then calling its `$get` **service factory** + * function to get the instance of the **service**. + * + * Often services have no configuration options and there is no need to add methods to the service + * provider. The provider will be no more than a constructor function with a `$get` property. For + * these cases the {@link auto.$provide $provide} service has additional helper methods to register + * services without specifying a provider. + * + * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the + * {@link auto.$injector $injector} + * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by + * providers and services. + * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by + * services, not providers. + * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, + * that will be wrapped in a **service provider** object, whose `$get` property will contain the + * given factory function. + * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` + * that will be wrapped in a **service provider** object, whose `$get` property will instantiate + * a new object using the given constructor function. + * + * See the individual methods for more information and examples. */ /** * @ngdoc method - * @name AUTO.$provide#provider - * @methodOf AUTO.$provide + * @name $provide#provider * @description * - * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. + * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions + * are constructor functions, whose instances are responsible for "providing" a factory for a + * service. + * + * Service provider names start with the name of the service they provide followed by `Provider`. + * For example, the {@link ng.$log $log} service has a provider called + * {@link ng.$logProvider $logProvider}. + * + * Service provider objects can have additional methods which allow configuration of the provider + * and its service. Importantly, you can configure what kind of service is created by the `$get` + * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a + * method {@link ng.$logProvider#debugEnabled debugEnabled} + * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the + * console or not. * - * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. + * @param {string} name The name of the instance. NOTE: the provider will be available under `name + + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using - * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. + * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using - * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. + * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance + + * @example + * + * The following example shows how to create a simple event tracking service and register it using + * {@link auto.$provide#provider $provide.provider()}. + * + * ```js + * // Define the eventTracker provider + * function EventTrackerProvider() { + * var trackingUrl = '/track'; + * + * // A provider method for configuring where the tracked events should been saved + * this.setTrackingUrl = function(url) { + * trackingUrl = url; + * }; + * + * // The service factory function + * this.$get = ['$http', function($http) { + * var trackedEvents = {}; + * return { + * // Call this to track an event + * event: function(event) { + * var count = trackedEvents[event] || 0; + * count += 1; + * trackedEvents[event] = count; + * return count; + * }, + * // Call this to save the tracked events to the trackingUrl + * save: function() { + * $http.post(trackingUrl, trackedEvents); + * } + * }; + * }]; + * } + * + * describe('eventTracker', function() { + * var postSpy; + * + * beforeEach(module(function($provide) { + * // Register the eventTracker provider + * $provide.provider('eventTracker', EventTrackerProvider); + * })); + * + * beforeEach(module(function(eventTrackerProvider) { + * // Configure eventTracker provider + * eventTrackerProvider.setTrackingUrl('/custom-track'); + * })); + * + * it('tracks events', inject(function(eventTracker) { + * expect(eventTracker.event('login')).toEqual(1); + * expect(eventTracker.event('login')).toEqual(2); + * })); + * + * it('saves to the tracking url', inject(function(eventTracker, $http) { + * postSpy = spyOn($http, 'post'); + * eventTracker.event('login'); + * eventTracker.save(); + * expect(postSpy).toHaveBeenCalled(); + * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); + * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); + * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); + * })); + * }); + * ``` */ /** * @ngdoc method - * @name AUTO.$provide#factory - * @methodOf AUTO.$provide + * @name $provide#factory * @description * - * A short hand for configuring services if only `$get` method is required. + * Register a **service factory**, which will be called to return the service instance. + * This is short for registering a service where its provider consists of only a `$get` property, + * which is the given service factory function. + * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to + * configure your service in a provider. * * @param {string} name The name of the instance. - * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for - * `$provide.provider(name, {$get: $getFn})`. + * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand + * for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service + * ```js + * $provide.factory('ping', ['$http', function($http) { + * return function ping() { + * return $http.send('/ping'); + * }; + * }]); + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { + * ping(); + * }]); + * ``` */ /** * @ngdoc method - * @name AUTO.$provide#service - * @methodOf AUTO.$provide + * @name $provide#service * @description * - * A short hand for registering service of given class. + * Register a **service constructor**, which will be invoked with `new` to create the service + * instance. + * This is short for registering a service where its provider's `$get` property is the service + * constructor function that will be used to instantiate the service instance. + * + * You should use {@link auto.$provide#service $provide.service(class)} if you define your service + * as a type/class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service using + * {@link auto.$provide#service $provide.service(class)}. + * ```js + * var Ping = function($http) { + * this.$http = $http; + * }; + * + * Ping.$inject = ['$http']; + * + * Ping.prototype.send = function() { + * return this.$http.get('/ping'); + * }; + * $provide.service('ping', Ping); + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { + * ping.send(); + * }]); + * ``` */ /** * @ngdoc method - * @name AUTO.$provide#value - * @methodOf AUTO.$provide + * @name $provide#value * @description * - * A short hand for configuring services if the `$get` method is a constant. + * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a + * number, an array, an object or a function. This is short for registering a service where its + * provider's `$get` property is a factory function that takes no arguments and returns the **value + * service**. + * + * Value services are similar to constant services, except that they cannot be injected into a + * module configuration function (see {@link angular.Module#config}) but they can be overridden by + * an Angular + * {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance + * + * @example + * Here are some examples of creating value services. + * ```js + * $provide.value('ADMIN_USER', 'admin'); + * + * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); + * + * $provide.value('halfOf', function(value) { + * return value / 2; + * }); + * ``` */ /** * @ngdoc method - * @name AUTO.$provide#constant - * @methodOf AUTO.$provide + * @name $provide#constant * @description * - * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected - * into configuration function (other modules) and it is not interceptable by - * {@link AUTO.$provide#decorator decorator}. + * Register a **constant service**, such as a string, a number, an array, an object or a function, + * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be + * injected into a module configuration function (see {@link angular.Module#config}) and it cannot + * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance + * + * @example + * Here a some examples of creating constants: + * ```js + * $provide.constant('SHARD_HEIGHT', 306); + * + * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); + * + * $provide.constant('double', function(value) { + * return value * 2; + * }); + * ``` */ /** * @ngdoc method - * @name AUTO.$provide#decorator - * @methodOf AUTO.$provide + * @name $provide#decorator * @description * - * Decoration of service, allows the decorator to intercept the service instance creation. The - * returned instance may be the original instance, or a new instance which delegates to the - * original instance. + * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator + * intercepts the creation of a service, allowing it to override or modify the behaviour of the + * service. The object returned by the decorator may be the original service, or a new service + * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be - * instantiated. The function is called using the {@link AUTO.$injector#invoke - * injector.invoke} method and is therefore fully injectable. Local injection arguments: + * instantiated and should return the decorated service instance. The function is called using + * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. + * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. + * + * @example + * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting + * calls to {@link ng.$log#error $log.warn()}. + * ```js + * $provide.decorator('$log', ['$delegate', function($delegate) { + * $delegate.warn = $delegate.error; + * return $delegate; + * }]); + * ``` */ @@ -12125,7 +13568,7 @@ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], - loadedModules = new HashMap(), + loadedModules = new HashMap([], true), providerCache = { $provide: { provider: supportObject(provider), @@ -12136,9 +13579,10 @@ function createInjector(modulesToLoad) { decorator: decorator } }, - providerInjector = createInternalInjector(providerCache, function() { - throw Error("Unknown provider: " + path.join(' <- ')); - }), + providerInjector = (providerCache.$injector = + createInternalInjector(providerCache, function() { + throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { @@ -12162,15 +13606,16 @@ function createInjector(modulesToLoad) { } else { return delegate(key, value); } - } + }; } function provider(name, provider_) { + assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { - throw Error('Provider ' + name + ' must define $get factory method.'); + throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } @@ -12183,9 +13628,10 @@ function createInjector(modulesToLoad) { }]); } - function value(name, value) { return factory(name, valueFn(value)); } + function value(name, val) { return factory(name, valueFn(val)); } function constant(name, value) { + assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } @@ -12204,43 +13650,43 @@ function createInjector(modulesToLoad) { // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ - var runBlocks = []; + var runBlocks = [], moduleFn, invokeQueue, i, ii; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); - if (isString(module)) { - var moduleFn = angularModule(module); - runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - try { - for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { + try { + if (isString(module)) { + moduleFn = angularModule(module); + runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); + + for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], - provider = invokeArgs[0] == '$injector' - ? providerInjector - : providerInjector.get(invokeArgs[0]); + provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } - } catch (e) { - if (e.message) e.message += ' from ' + module; - throw e; + } else if (isFunction(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else if (isArray(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else { + assertArgFn(module, 'module'); } - } else if (isFunction(module)) { - try { - runBlocks.push(providerInjector.invoke(module)); - } catch (e) { - if (e.message) e.message += ' from ' + module; - throw e; + } catch (e) { + if (isArray(module)) { + module = module[module.length - 1]; } - } else if (isArray(module)) { - try { - runBlocks.push(providerInjector.invoke(module)); - } catch (e) { - if (e.message) e.message += ' from ' + String(module[module.length - 1]); - throw e; + if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + // Safari & FF's stack traces don't contain error.message content + // unlike those of Chrome and IE + // So if stack doesn't contain message, we create a new string that contains both. + // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. + /* jshint -W022 */ + e = e.message + '\n' + e.stack; } - } else { - assertArgFn(module, 'module'); + throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", + module, e.stack || e.message || e); } }); return runBlocks; @@ -12253,12 +13699,10 @@ function createInjector(modulesToLoad) { function createInternalInjector(cache, factory) { function getService(serviceName) { - if (typeof serviceName !== 'string') { - throw Error('Service name expected'); - } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { - throw Error('Circular dependency: ' + path.join(' <- ')); + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', + serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { @@ -12266,6 +13710,11 @@ function createInjector(modulesToLoad) { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); + } catch (err) { + if (cache[serviceName] === INSTANTIATING) { + delete cache[serviceName]; + } + throw err; } finally { path.shift(); } @@ -12280,33 +13729,23 @@ function createInjector(modulesToLoad) { for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; + if (typeof key !== 'string') { + throw $injectorMinErr('itkn', + 'Incorrect injection token! Expected service name as string, got {0}', key); + } args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } - if (!fn.$inject) { - // this means that we must be an array. + if (isArray(fn)) { fn = fn[length]; } - - // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke - switch (self ? -1 : args.length) { - case 0: return fn(); - case 1: return fn(args[0]); - case 2: return fn(args[0], args[1]); - case 3: return fn(args[0], args[1], args[2]); - case 4: return fn(args[0], args[1], args[2], args[3]); - case 5: return fn(args[0], args[1], args[2], args[3], args[4]); - case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); - case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); - case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); - default: return fn.apply(self, args); - } + // http://jsperf.com/angularjs-invoke-apply-vs-switch + // #5388 + return fn.apply(self, args); } function instantiate(Type, locals) { @@ -12319,44 +13758,81 @@ function createInjector(modulesToLoad) { instance = new Constructor(); returnedValue = invoke(Type, instance, locals); - return isObject(returnedValue) ? returnedValue : instance; + return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, - annotate: annotate + annotate: annotate, + has: function(name) { + return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); + } }; } } /** - * @ngdoc function - * @name ng.$anchorScroll + * @ngdoc service + * @name $anchorScroll + * @kind function * @requires $window * @requires $location * @requires $rootScope * * @description - * When called, it checks current value of `$location.hash()` and scroll to related element, + * When called, it checks current value of `$location.hash()` and scrolls to the related element, * according to rules specified in - * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. + * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). * - * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. + * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. - */ -function $AnchorScrollProvider() { - - var autoScrollingEnabled = true; - - this.disableAutoScrolling = function() { - autoScrollingEnabled = false; - }; - - this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { - var document = $window.document; - + * + * @example + + +
    + Go to bottom + You're at the bottom! +
    +
    + + function ScrollCtrl($scope, $location, $anchorScroll) { + $scope.gotoBottom = function (){ + // set the location.hash to the id of + // the element you wish to scroll to. + $location.hash('bottom'); + + // call $anchorScroll() + $anchorScroll(); + }; + } + + + #scrollArea { + height: 350px; + overflow: auto; + } + + #bottom { + display: block; + margin-top: 2000px; + } + +
    + */ +function $AnchorScrollProvider() { + + var autoScrollingEnabled = true; + + this.disableAutoScrolling = function() { + autoScrollingEnabled = false; + }; + + this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { + var document = $window.document; + // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice @@ -12398,10 +13874,266 @@ function $AnchorScrollProvider() { }]; } +var $animateMinErr = minErr('$animate'); + +/** + * @ngdoc provider + * @name $animateProvider + * + * @description + * Default implementation of $animate that doesn't perform any animations, instead just + * synchronously performs DOM + * updates and calls done() callbacks. + * + * In order to enable animations the ngAnimate module has to be loaded. + * + * To see the functional implementation check out src/ngAnimate/animate.js + */ +var $AnimateProvider = ['$provide', function($provide) { + + + this.$$selectors = {}; + + + /** + * @ngdoc method + * @name $animateProvider#register + * + * @description + * Registers a new injectable animation factory function. The factory function produces the + * animation object which contains callback functions for each event that is expected to be + * animated. + * + * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` + * must be called once the element animation is complete. If a function is returned then the + * animation service will use this function to cancel the animation whenever a cancel event is + * triggered. + * + * + * ```js + * return { + * eventFn : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction() { + * //code to cancel the animation + * } + * } + * } + * ``` + * + * @param {string} name The name of the animation. + * @param {Function} factory The factory function that will be executed to return the animation + * object. + */ + this.register = function(name, factory) { + var key = name + '-animation'; + if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', + "Expecting class selector starting with '.' got '{0}'.", name); + this.$$selectors[name.substr(1)] = key; + $provide.factory(key, factory); + }; + + /** + * @ngdoc method + * @name $animateProvider#classNameFilter + * + * @description + * Sets and/or returns the CSS class regular expression that is checked when performing + * an animation. Upon bootstrap the classNameFilter value is not set at all and will + * therefore enable $animate to attempt to perform an animation on any element. + * When setting the classNameFilter value, animations will only be performed on elements + * that successfully match the filter expression. This in turn can boost performance + * for low-powered devices as well as applications containing a lot of structural operations. + * @param {RegExp=} expression The className expression which will be checked against all animations + * @return {RegExp} The current CSS className expression value. If null then there is no expression value + */ + this.classNameFilter = function(expression) { + if(arguments.length === 1) { + this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; + } + return this.$$classNameFilter; + }; + + this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) { + + function async(fn) { + fn && $$asyncCallback(fn); + } + + /** + * + * @ngdoc service + * @name $animate + * @description The $animate service provides rudimentary DOM manipulation functions to + * insert, remove and move elements within the DOM, as well as adding and removing classes. + * This service is the core service used by the ngAnimate $animator service which provides + * high-level animation hooks for CSS and JavaScript. + * + * $animate is available in the AngularJS core, however, the ngAnimate module must be included + * to enable full out animation support. Otherwise, $animate will only perform simple DOM + * manipulation operations. + * + * To learn more about enabling animation support, click here to visit the {@link ngAnimate + * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service + * page}. + */ + return { + + /** + * + * @ngdoc method + * @name $animate#enter + * @kind function + * @description Inserts the element into the DOM either after the `after` element or within + * the `parent` element. Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will be inserted into the DOM + * @param {DOMElement} parent the parent element which will append the element as + * a child (if the after element is not present) + * @param {DOMElement} after the sibling element which will append the element + * after itself + * @param {Function=} done callback function that will be called after the element has been + * inserted into the DOM + */ + enter : function(element, parent, after, done) { + if (after) { + after.after(element); + } else { + if (!parent || !parent[0]) { + parent = after.parent(); + } + parent.append(element); + } + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#leave + * @kind function + * @description Removes the element from the DOM. Once complete, the done() callback will be + * fired (if provided). + * @param {DOMElement} element the element which will be removed from the DOM + * @param {Function=} done callback function that will be called after the element has been + * removed from the DOM + */ + leave : function(element, done) { + element.remove(); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#move + * @kind function + * @description Moves the position of the provided element within the DOM to be placed + * either after the `after` element or inside of the `parent` element. Once complete, the + * done() callback will be fired (if provided). + * + * @param {DOMElement} element the element which will be moved around within the + * DOM + * @param {DOMElement} parent the parent element where the element will be + * inserted into (if the after element is not present) + * @param {DOMElement} after the sibling element where the element will be + * positioned next to + * @param {Function=} done the callback function (if provided) that will be fired after the + * element has been moved to its new position + */ + move : function(element, parent, after, done) { + // Do not remove element before insert. Removing will cause data associated with the + // element to be dropped. Insert will implicitly do the remove. + this.enter(element, parent, after, done); + }, + + /** + * + * @ngdoc method + * @name $animate#addClass + * @kind function + * @description Adds the provided className CSS class value to the provided element. Once + * complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have the className value + * added to it + * @param {string} className the CSS class which will be added to the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * className value has been added to the element + */ + addClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + forEach(element, function (element) { + jqLiteAddClass(element, className); + }); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#removeClass + * @kind function + * @description Removes the provided className CSS class value from the provided element. + * Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have the className value + * removed from it + * @param {string} className the CSS class which will be removed from the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * className value has been removed from the element + */ + removeClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + forEach(element, function (element) { + jqLiteRemoveClass(element, className); + }); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#setClass + * @kind function + * @description Adds and/or removes the given CSS classes to and from the element. + * Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have its CSS classes changed + * removed from it + * @param {string} add the CSS classes which will be added to the element + * @param {string} remove the CSS class which will be removed from the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * CSS classes have been set on the element + */ + setClass : function(element, add, remove, done) { + forEach(element, function (element) { + jqLiteAddClass(element, add); + jqLiteRemoveClass(element, remove); + }); + async(done); + }, + + enabled : noop + }; + }]; +}]; + +function $$AsyncCallbackProvider(){ + this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { + return $$rAF.supported + ? function(fn) { return $$rAF(fn); } + : function(fn) { + return $timeout(fn, 0, false); + }; + }]; +} + /** * ! This is a private undocumented service ! * - * @name ng.$browser + * @name $browser * @requires $log * @description * This object has two goals: @@ -12485,8 +14217,7 @@ function Browser(window, document, $log, $sniffer) { pollTimeout; /** - * @name ng.$browser#addPollFn - * @methodOf ng.$browser + * @name $browser#addPollFn * * @param {function()} fn Poll function to add * @@ -12522,11 +14253,11 @@ function Browser(window, document, $log, $sniffer) { ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, - baseElement = document.find('base'); + baseElement = document.find('base'), + newLocation = null; /** - * @name ng.$browser#url - * @methodOf ng.$browser + * @name $browser#url * * @description * GETTER: @@ -12545,6 +14276,10 @@ function Browser(window, document, $log, $sniffer) { * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { + // Android Browser BFCache causes location, history reference to become stale. + if (location !== window.location) location = window.location; + if (history !== window.history) history = window.history; + // setter if (url) { if (lastBrowserUrl == url) return; @@ -12557,14 +14292,20 @@ function Browser(window, document, $log, $sniffer) { baseElement.attr('href', baseElement.attr('href')); } } else { - if (replace) location.replace(url); - else location.href = url; + newLocation = url; + if (replace) { + location.replace(url); + } else { + location.href = url; + } } return self; // getter } else { - // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return location.href.replace(/%27/g,"'"); + // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href + // methods not updating location.href synchronously. + // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 + return newLocation || location.href.replace(/%27/g,"'"); } }; @@ -12572,6 +14313,7 @@ function Browser(window, document, $log, $sniffer) { urlChangeInit = false; function fireUrlChange() { + newLocation = null; if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); @@ -12581,14 +14323,12 @@ function Browser(window, document, $log, $sniffer) { } /** - * @name ng.$browser#onUrlChange - * @methodOf ng.$browser - * @TODO(vojta): refactor to use node's syntax for events + * @name $browser#onUrlChange * * @description * Register callback function that will be called, when url changes. * - * It's only called when the url is changed by outside of angular: + * It's only called when the url is changed from outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link @@ -12604,15 +14344,16 @@ function Browser(window, document, $log, $sniffer) { * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { + // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event - if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); + if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); // hashchange event - if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); + if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); @@ -12628,14 +14369,17 @@ function Browser(window, document, $log, $sniffer) { ////////////////////////////////////////////////////////////// /** + * @name $browser#baseHref + * + * @description * Returns current * (always relative - without domain) * - * @returns {string=} + * @returns {string} The current base href */ self.baseHref = function() { var href = baseElement.attr('href'); - return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; + return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// @@ -12646,41 +14390,45 @@ function Browser(window, document, $log, $sniffer) { var cookiePath = self.baseHref(); /** - * @name ng.$browser#cookies - * @methodOf ng.$browser + * @name $browser#cookies * * @param {string=} name Cookie name - * @param {string=} value Cokkie value + * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: - *
      - *
    • cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it
    • - *
    • cookies(name, value) -> set name to value, if value is undefined delete the cookie
    • - *
    • cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)
    • - *
    + * + * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify + * it + * - cookies(name, value) -> set name to value, if value is undefined delete the cookie + * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that + * way) * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { + /* global escape: false, unescape: false */ var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { - rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; + rawDocument.cookie = escape(name) + "=;path=" + cookiePath + + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { - cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; + cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { - $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ + $log.warn("Cookie '"+ name + + "' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } } @@ -12695,7 +14443,7 @@ function Browser(window, document, $log, $sniffer) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies - var name = unescape(cookie.substring(0, index)); + name = unescape(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. @@ -12711,14 +14459,13 @@ function Browser(window, document, $log, $sniffer) { /** - * @name ng.$browser#defer - * @methodOf ng.$browser - * @param {function()} fn A function, who's execution should be defered. + * @name $browser#defer + * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description - * Executes a fn asynchroniously via `setTimeout(fn, delay)`. + * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed @@ -12738,14 +14485,14 @@ function Browser(window, document, $log, $sniffer) { /** - * @name ng.$browser#defer.cancel - * @methodOf ng.$browser.defer + * @name $browser#defer.cancel * * @description - * Cancels a defered task identified with `deferId`. + * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { @@ -12767,11 +14514,26 @@ function $BrowserProvider(){ } /** - * @ngdoc object - * @name ng.$cacheFactory + * @ngdoc service + * @name $cacheFactory * * @description - * Factory that constructs cache objects. + * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to + * them. + * + * ```js + * + * var cache = $cacheFactory('cacheId'); + * expect($cacheFactory.get('cacheId')).toBe(cache); + * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); + * + * cache.put("key", "value"); + * cache.put("another key", "another value"); + * + * // We've specified no options on creation + * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); + * + * ``` * * * @param {string} cacheId Name or id of the newly created cache. @@ -12782,12 +14544,53 @@ function $BrowserProvider(){ * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. - * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. + * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns + * it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * + * @example + + +
    + + + + +

    Cached Values

    +
    + + : + +
    + +

    Cache Info

    +
    + + : + +
    +
    +
    + + angular.module('cacheExampleApp', []). + controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { + $scope.keys = []; + $scope.cache = $cacheFactory('cacheId'); + $scope.put = function(key, value) { + $scope.cache.put(key, value); + $scope.keys.push(key); + }; + }]); + + + p { + margin: 10px 0 3px; + } + +
    */ function $CacheFactoryProvider() { @@ -12796,7 +14599,7 @@ function $CacheFactoryProvider() { function cacheFactory(cacheId, options) { if (cacheId in caches) { - throw Error('cacheId ' + cacheId + ' taken'); + throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); } var size = 0, @@ -12807,12 +14610,71 @@ function $CacheFactoryProvider() { freshEnd = null, staleEnd = null; + /** + * @ngdoc type + * @name $cacheFactory.Cache + * + * @description + * A cache object used to store and retrieve data, primarily used by + * {@link $http $http} and the {@link ng.directive:script script} directive to cache + * templates and other data. + * + * ```js + * angular.module('superCache') + * .factory('superCache', ['$cacheFactory', function($cacheFactory) { + * return $cacheFactory('super-cache'); + * }]); + * ``` + * + * Example test: + * + * ```js + * it('should behave like a cache', inject(function(superCache) { + * superCache.put('key', 'value'); + * superCache.put('another key', 'another value'); + * + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 2 + * }); + * + * superCache.remove('another key'); + * expect(superCache.get('another key')).toBeUndefined(); + * + * superCache.removeAll(); + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 0 + * }); + * })); + * ``` + */ return caches[cacheId] = { + /** + * @ngdoc method + * @name $cacheFactory.Cache#put + * @kind function + * + * @description + * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be + * retrieved later, and incrementing the size of the cache if the key was not already + * present in the cache. If behaving like an LRU cache, it will also remove stale + * entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param {string} key the key under which the cached data is stored. + * @param {*} value the value to store alongside the key. If it is undefined, the key + * will not be stored. + * @returns {*} the value stored. + */ put: function(key, value) { - var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); - refresh(lruEntry); + refresh(lruEntry); + } if (isUndefined(value)) return; if (!(key in data)) size++; @@ -12821,35 +14683,70 @@ function $CacheFactoryProvider() { if (size > capacity) { this.remove(staleEnd.key); } - }, + return value; + }, + /** + * @ngdoc method + * @name $cacheFactory.Cache#get + * @kind function + * + * @description + * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the data to be retrieved + * @returns {*} the value stored. + */ get: function(key) { - var lruEntry = lruHash[key]; + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; - if (!lruEntry) return; + if (!lruEntry) return; - refresh(lruEntry); + refresh(lruEntry); + } return data[key]; }, + /** + * @ngdoc method + * @name $cacheFactory.Cache#remove + * @kind function + * + * @description + * Removes an entry from the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the entry to be removed + */ remove: function(key) { - var lruEntry = lruHash[key]; + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; - if (!lruEntry) return; + if (!lruEntry) return; - if (lruEntry == freshEnd) freshEnd = lruEntry.p; - if (lruEntry == staleEnd) staleEnd = lruEntry.n; - link(lruEntry.n,lruEntry.p); + if (lruEntry == freshEnd) freshEnd = lruEntry.p; + if (lruEntry == staleEnd) staleEnd = lruEntry.n; + link(lruEntry.n,lruEntry.p); + + delete lruHash[key]; + } - delete lruHash[key]; delete data[key]; size--; }, + /** + * @ngdoc method + * @name $cacheFactory.Cache#removeAll + * @kind function + * + * @description + * Clears the cache object of any entries. + */ removeAll: function() { data = {}; size = 0; @@ -12858,6 +14755,15 @@ function $CacheFactoryProvider() { }, + /** + * @ngdoc method + * @name $cacheFactory.Cache#destroy + * @kind function + * + * @description + * Destroys the {@link $cacheFactory.Cache Cache} object entirely, + * removing it from the {@link $cacheFactory $cacheFactory} set. + */ destroy: function() { data = null; stats = null; @@ -12866,6 +14772,22 @@ function $CacheFactoryProvider() { }, + /** + * @ngdoc method + * @name $cacheFactory.Cache#info + * @kind function + * + * @description + * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. + * + * @returns {object} an object with the following properties: + *
      + *
    • **id**: the id of the cache instance
    • + *
    • **size**: the number of entries kept in the cache instance
    • + *
    • **...**: any additional properties from the options object when creating the + * cache.
    • + *
    + */ info: function() { return extend({}, stats, {size: size}); } @@ -12903,6 +14825,15 @@ function $CacheFactoryProvider() { } + /** + * @ngdoc method + * @name $cacheFactory#info + * + * @description + * Get information about all the caches that have been created + * + * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` + */ cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { @@ -12912,6 +14843,16 @@ function $CacheFactoryProvider() { }; + /** + * @ngdoc method + * @name $cacheFactory#get + * + * @description + * Get access to a cache object by the `cacheId` used when it was created. + * + * @param {string} cacheId Name or id of a cache to access. + * @returns {object} Cache object identified by the cacheId or undefined if no such cache. + */ cacheFactory.get = function(cacheId) { return caches[cacheId]; }; @@ -12922,11 +14863,43 @@ function $CacheFactoryProvider() { } /** - * @ngdoc object - * @name ng.$templateCache + * @ngdoc service + * @name $templateCache * * @description - * Cache used for storing html templates. + * The first time a template is used, it is loaded in the template cache for quick retrieval. You + * can load templates directly into the cache in a `script` tag, or by consuming the + * `$templateCache` service directly. + * + * Adding via the `script` tag: + * + * ```html + * + * ``` + * + * **Note:** the `script` tag containing the template does not need to be included in the `head` of + * the document, but it must be below the `ng-app` definition. + * + * Adding via the $templateCache service: + * + * ```js + * var myApp = angular.module('myApp', []); + * myApp.run(function($templateCache) { + * $templateCache.put('templateId.html', 'This is the content of the template'); + * }); + * ``` + * + * To retrieve the template later, simply use it in your HTML: + * ```html + *
    + * ``` + * + * or get it via Javascript: + * ```js + * $templateCache.get('templateId.html') + * ``` * * See {@link ng.$cacheFactory $cacheFactory}. * @@ -12955,98 +14928,460 @@ function $TemplateCacheProvider() { */ -var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; - - /** - * @ngdoc function - * @name ng.$compile - * @function + * @ngdoc service + * @name $compile + * @kind function * * @description - * Compiles a piece of HTML string or DOM into a template and produces a template function, which - * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. + * Compiles an HTML string or DOM into a template and produces a template function, which + * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. * - * The compilation is a process of walking the DOM tree and trying to match DOM elements to - * {@link ng.$compileProvider#directive directives}. For each match it - * executes corresponding template function and collects the - * instance functions into a single template function which is then returned. + * The compilation is a process of walking the DOM tree and matching DOM elements to + * {@link ng.$compileProvider#directive directives}. * - * The template function can then be used once to produce the view or as it is the case with - * {@link ng.directive:ngRepeat repeater} many-times, in which - * case each call results in a view that is a DOM clone of the original template. + *
    + * **Note:** This document is an in-depth reference of all directive options. + * For a gentle introduction to directives with examples of common use cases, + * see the {@link guide/directive directive guide}. + *
    * - - - -
    -
    -
    -
    -
    -
    - - it('should auto compile', function() { - expect(element('div[compile]').text()).toBe('Hello Angular'); - input('html').enter('{{name}}!'); - expect(element('div[compile]').text()).toBe('Angular!'); - }); - -
    - + * ## Comprehensive Directive API * + * There are many different options for a directive. * - * @param {string|DOMElement} element Element or HTML string to compile into a template function. - * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. - * @param {number} maxPriority only apply directives lower then given priority (Only effects the - * root element(s), not their children) - * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template + * The difference resides in the return value of the factory function. + * You can either return a "Directive Definition Object" (see below) that defines the directive properties, + * or just the `postLink` function (all other properties will have the default values). + * + *
    + * **Best Practice:** It's recommended to use the "directive definition object" form. + *
    + * + * Here's an example directive declared with a Directive Definition Object: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { + * var directiveDefinitionObject = { + * priority: 0, + * template: '
    ', // or // function(tElement, tAttrs) { ... }, + * // or + * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, + * transclude: false, + * restrict: 'A', + * scope: false, + * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, + * controllerAs: 'stringAlias', + * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], + * compile: function compile(tElement, tAttrs, transclude) { + * return { + * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, + * post: function postLink(scope, iElement, iAttrs, controller) { ... } + * } + * // or + * // return function postLink( ... ) { ... } + * }, + * // or + * // link: { + * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, + * // post: function postLink(scope, iElement, iAttrs, controller) { ... } + * // } + * // or + * // link: function postLink( ... ) { ... } + * }; + * return directiveDefinitionObject; + * }); + * ``` + * + *
    + * **Note:** Any unspecified options will use the default value. You can see the default values below. + *
    + * + * Therefore the above can be simplified as: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { + * var directiveDefinitionObject = { + * link: function postLink(scope, iElement, iAttrs) { ... } + * }; + * return directiveDefinitionObject; + * // or + * // return function postLink(scope, iElement, iAttrs) { ... } + * }); + * ``` + * + * + * + * ### Directive Definition Object + * + * The directive definition object provides instructions to the {@link ng.$compile + * compiler}. The attributes are: + * + * #### `priority` + * When there are multiple directives defined on a single DOM element, sometimes it + * is necessary to specify the order in which the directives are applied. The `priority` is used + * to sort the directives before their `compile` functions get called. Priority is defined as a + * number. Directives with greater numerical `priority` are compiled first. Pre-link functions + * are also run in priority order, but post-link functions are run in reverse order. The order + * of directives with the same priority is undefined. The default priority is `0`. + * + * #### `terminal` + * If set to true then the current `priority` will be the last set of directives + * which will execute (any directives at the current priority will still execute + * as the order of execution on same `priority` is undefined). + * + * #### `scope` + * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the + * same element request a new scope, only one new scope is created. The new scope rule does not + * apply for the root of the template since the root of the template always gets a new scope. + * + * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from + * normal scope in that it does not prototypically inherit from the parent scope. This is useful + * when creating reusable components, which should not accidentally read or modify data in the + * parent scope. + * + * The 'isolate' scope takes an object hash which defines a set of local scope properties + * derived from the parent scope. These local properties are useful for aliasing values for + * templates. Locals definition is a hash of local scope property to its source: + * + * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is + * always a string since DOM attributes are strings. If no `attr` name is specified then the + * attribute name is assumed to be the same as the local name. + * Given `` and widget definition + * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect + * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the + * `localName` property on the widget scope. The `name` is read from the parent scope (not + * component scope). + * + * * `=` or `=attr` - set up bi-directional binding between a local scope property and the + * parent scope property of name defined via the value of the `attr` attribute. If no `attr` + * name is specified then the attribute name is assumed to be the same as the local name. + * Given `` and widget definition of + * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected + * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent + * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You + * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. + * + * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. + * If no `attr` name is specified then the attribute name is assumed to be the same as the + * local name. Given `` and widget definition of + * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to + * a function wrapper for the `count = count + value` expression. Often it's desirable to + * pass data from the isolated scope via an expression to the parent scope, this can be + * done by passing a map of local variable names and values into the expression wrapper fn. + * For example, if the expression is `increment(amount)` then we can specify the amount value + * by calling the `localFn` as `localFn({amount: 22})`. + * + * + * + * #### `controller` + * Controller constructor function. The controller is instantiated before the + * pre-linking phase and it is shared with other directives (see + * `require` attribute). This allows the directives to communicate with each other and augment + * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: + * + * * `$scope` - Current scope associated with the element + * * `$element` - Current element + * * `$attrs` - Current attributes object for the element + * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. + * The scope can be overridden by an optional first argument. + * `function([scope], cloneLinkingFn)`. + * + * + * #### `require` + * Require another directive and inject its controller as the fourth argument to the linking function. The + * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the + * injected argument will be an array in corresponding order. If no such directive can be + * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: + * + * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. + * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. + * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found. + * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the + * `link` fn if not found. + * + * + * #### `controllerAs` + * Controller alias at the directive scope. An alias for the controller so it + * can be referenced at the directive template. The directive needs to define a scope for this + * configuration to be used. Useful in the case when directive is used as component. + * + * + * #### `restrict` + * String of subset of `EACM` which restricts the directive to a specific directive + * declaration style. If omitted, the default (attributes only) is used. + * + * * `E` - Element name: `` + * * `A` - Attribute (default): `
    ` + * * `C` - Class: `
    ` + * * `M` - Comment: `` + * + * + * #### `template` + * HTML markup that may: + * * Replace the contents of the directive's element (default). + * * Replace the directive's element itself (if `replace` is true - DEPRECATED). + * * Wrap the contents of the directive's element (if `transclude` is true). + * + * Value may be: + * + * * A string. For example `
    {{delete_str}}
    `. + * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` + * function api below) and returns a string value. + * + * + * #### `templateUrl` + * Same as `template` but the template is loaded from the specified URL. Because + * the template loading is asynchronous the compilation/linking is suspended until the template + * is loaded. + * + * You can specify `templateUrl` as a string representing the URL or as a function which takes two + * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns + * a string value representing the url. In either case, the template URL is passed through {@link + * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. + * + * + * #### `replace` ([*DEPRECATED*!], will be removed in next major release) + * specify what the template should replace. Defaults to `false`. + * + * * `true` - the template will replace the directive's element. + * * `false` - the template will replace the contents of the directive's element. + * + * The replacement process migrates all of the attributes / classes from the old element to the new + * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive + * Directives Guide} for an example. + * + * #### `transclude` + * compile the content of the element and make it available to the directive. + * Typically used with {@link ng.directive:ngTransclude + * ngTransclude}. The advantage of transclusion is that the linking function receives a + * transclusion function which is pre-bound to the correct scope. In a typical setup the widget + * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` + * scope. This makes it possible for the widget to have private state, and the transclusion to + * be bound to the parent (pre-`isolate`) scope. + * + * * `true` - transclude the content of the directive. + * * `'element'` - transclude the whole element including any directives defined at lower priority. + * + *
    + * **Note:** When testing an element transclude directive you must not place the directive at the root of the + * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives + * Testing Transclusion Directives}. + *
    + * + * #### `compile` + * + * ```js + * function compile(tElement, tAttrs, transclude) { ... } + * ``` + * + * The compile function deals with transforming the template DOM. Since most directives do not do + * template transformation, it is not used often. The compile function takes the following arguments: + * + * * `tElement` - template element - The element where the directive has been declared. It is + * safe to do template transformation on the element and child elements only. + * + * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared + * between all directive compile functions. + * + * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` + * + *
    + * **Note:** The template instance and the link instance may be different objects if the template has + * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that + * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration + * should be done in a linking function rather than in a compile function. + *
    + + *
    + * **Note:** The compile function cannot handle directives that recursively use themselves in their + * own templates or compile functions. Compiling these directives results in an infinite loop and a + * stack overflow errors. + * + * This can be avoided by manually using $compile in the postLink function to imperatively compile + * a directive's template instead of relying on automatic template compilation via `template` or + * `templateUrl` declaration or manual compilation inside the compile function. + *
    + * + *
    + * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it + * e.g. does not know about the right outer scope. Please use the transclude function that is passed + * to the link function instead. + *
    + + * A compile function can have a return value which can be either a function or an object. + * + * * returning a (post-link) function - is equivalent to registering the linking function via the + * `link` property of the config object when the compile function is empty. + * + * * returning an object with function(s) registered via `pre` and `post` properties - allows you to + * control when a linking function should be called during the linking phase. See info about + * pre-linking and post-linking functions below. + * + * + * #### `link` + * This property is used only if the `compile` property is not defined. + * + * ```js + * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } + * ``` + * + * The link function is responsible for registering DOM listeners as well as updating the DOM. It is + * executed after the template has been cloned. This is where most of the directive logic will be + * put. + * + * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the + * directive for registering {@link ng.$rootScope.Scope#$watch watches}. + * + * * `iElement` - instance element - The element where the directive is to be used. It is safe to + * manipulate the children of the element only in `postLink` function since the children have + * already been linked. + * + * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared + * between all directive linking functions. + * + * * `controller` - a controller instance - A controller instance if at least one directive on the + * element defines a controller. The controller is shared among all the directives, which allows + * the directives to use the controllers as a communication channel. + * + * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. + * The scope can be overridden by an optional first argument. This is the same as the `$transclude` + * parameter of directive controllers. + * `function([scope], cloneLinkingFn)`. + * + * + * #### Pre-linking function + * + * Executed before the child elements are linked. Not safe to do DOM transformation since the + * compiler linking function will fail to locate the correct elements for linking. + * + * #### Post-linking function + * + * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. + * + * + * ### Attributes + * + * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the + * `link()` or `compile()` functions. It has a variety of uses. + * + * accessing *Normalized attribute names:* + * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. + * the attributes object allows for normalized access to + * the attributes. + * + * * *Directive inter-communication:* All directives share the same instance of the attributes + * object which allows the directives to use the attributes object as inter directive + * communication. + * + * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object + * allowing other directives to read the interpolated value. + * + * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes + * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also + * the only way to easily get the actual value because during the linking phase the interpolation + * hasn't been evaluated yet and so the value is at this time set to `undefined`. + * + * ```js + * function linkingFn(scope, elm, attrs, ctrl) { + * // get the attribute value + * console.log(attrs.ngModel); + * + * // change the attribute + * attrs.$set('ngModel', 'new value'); + * + * // observe changes to interpolated attribute + * attrs.$observe('ngModel', function(value) { + * console.log('ngModel has changed value to ' + value); + * }); + * } + * ``` + * + * Below is an example using `$compileProvider`. + * + *
    + * **Note**: Typically directives are registered with `module.directive`. The example below is + * to illustrate how `$compile` works. + *
    + * + + + +
    +
    +
    +
    +
    +
    + + it('should auto compile', function() { + var textarea = $('textarea'); + var output = $('div[compile]'); + // The initial state reads 'Hello Angular'. + expect(output.getText()).toBe('Hello Angular'); + textarea.clear(); + textarea.sendKeys('{{name}}!'); + expect(output.getText()).toBe('Angular!'); + }); + +
    + + * + * + * @param {string|DOMElement} element Element or HTML string to compile into a template function. + * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. + * @param {number} maxPriority only apply directives lower than given priority (Only effects the + * root element(s), not their children) + * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the - * `template` and call the `cloneAttachFn` function allowing the caller to attach the - * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is - * called as:
    `cloneAttachFn(clonedElement, scope)` where: + * `template` and call the `cloneAttachFn` function allowing the caller to attach the + * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is + * called as:
    `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * - * Calling the linking function returns the element of the template. It is either the original element - * passed in, or the clone of the element if the `cloneAttachFn` is provided. + * Calling the linking function returns the element of the template. It is either the original + * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. @@ -13055,71 +15390,75 @@ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. - *
    + *   ```js
      *     var element = $compile('

    {{total}}

    ')(scope); - *
    + * ``` * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: - *
    - *     var templateHTML = angular.element('

    {{total}}

    '), + * ```js + * var templateElement = angular.element('

    {{total}}

    '), * scope = ....; * - * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { + * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * - * //now we have reference to the cloned DOM via `clone` - *
    + * //now we have reference to the cloned DOM via `clonedElement` + * ``` * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ +var $compileMinErr = minErr('$compile'); /** - * @ngdoc service - * @name ng.$compileProvider - * @function + * @ngdoc provider + * @name $compileProvider + * @kind function * * @description */ -$CompileProvider.$inject = ['$provide']; -function $CompileProvider($provide) { +$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; +function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, - MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ', - urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/; + COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/; + // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes + // The assumption is that future DOM event attribute names will begin with + // 'on' and be composed of only English letters. + var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; /** - * @ngdoc function - * @name ng.$compileProvider#directive - * @methodOf ng.$compileProvider - * @function + * @ngdoc method + * @name $compileProvider#directive + * @kind function * * @description - * Register a new directives with the compiler. + * Register a new directive with the compiler. * - * @param {string} name Name of the directive in camel-case. (ie ngBind which will match as - * ng-bind). - * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more - * info. + * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which + * will match as ng-bind), or an object map of directives where the keys are the + * names and the values are the factories. + * @param {Function|Array} directiveFactory An injectable directive factory function. See + * {@link guide/directive} for more info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { + assertNotHasOwnProperty(name, 'directive'); if (isString(name)) { - assertArg(directiveFactory, 'directive'); + assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; - forEach(hasDirectives[name], function(directiveFactory) { + forEach(hasDirectives[name], function(directiveFactory, index) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { @@ -13128,6 +15467,7 @@ function $CompileProvider($provide) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; + directive.index = index; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; @@ -13148,10 +15488,9 @@ function $CompileProvider($provide) { /** - * @ngdoc function - * @name ng.$compileProvider#urlSanitizationWhitelist - * @methodOf ng.$compileProvider - * @function + * @ngdoc method + * @name $compileProvider#aHrefSanitizationWhitelist + * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe @@ -13159,29 +15498,59 @@ function $CompileProvider($provide) { * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * - * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an - * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular - * expression. If a match is found the original url is written into the dom. Otherwise the - * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ - this.urlSanitizationWhitelist = function(regexp) { + this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { - urlSanitizationWhitelist = regexp; + $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); return this; + } else { + return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); } - return urlSanitizationWhitelist; }; + /** + * @ngdoc method + * @name $compileProvider#imgSrcSanitizationWhitelist + * @kind function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.imgSrcSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); + return this; + } else { + return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); + } + }; + this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', - '$controller', '$rootScope', '$document', + '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, - $controller, $rootScope, $document) { + $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { var Attributes = function(element, attr) { this.$$element = element; @@ -13192,6 +15561,65 @@ function $CompileProvider($provide) { $normalize: directiveNormalize, + /** + * @ngdoc method + * @name $compile.directive.Attributes#$addClass + * @kind function + * + * @description + * Adds the CSS class value specified by the classVal parameter to the element. If animations + * are enabled then an animation will be triggered for the class addition. + * + * @param {string} classVal The className value that will be added to the element + */ + $addClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.addClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$removeClass + * @kind function + * + * @description + * Removes the CSS class value specified by the classVal parameter from the element. If + * animations are enabled then an animation will be triggered for the class removal. + * + * @param {string} classVal The className value that will be removed from the element + */ + $removeClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.removeClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$updateClass + * @kind function + * + * @description + * Adds and removes the appropriate CSS class values to the element based on the difference + * between the new and old CSS class values (specified as newClasses and oldClasses). + * + * @param {string} newClasses The current CSS className value + * @param {string} oldClasses The former CSS className value + */ + $updateClass : function(newClasses, oldClasses) { + var toAdd = tokenDifference(newClasses, oldClasses); + var toRemove = tokenDifference(oldClasses, newClasses); + + if(toAdd.length === 0) { + $animate.removeClass(this.$$element, toRemove); + } else if(toRemove.length === 0) { + $animate.addClass(this.$$element, toAdd); + } else { + $animate.setClass(this.$$element, toAdd, toRemove); + } + }, + /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. @@ -13202,9 +15630,13 @@ function $CompileProvider($provide) { * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { + // TODO: decide whether or not to throw an error if "class" + //is set through this function since it may cause $updateClass to + //become unstable. + var booleanKey = getBooleanAttrName(this.$$element[0], key), - $$observers = this.$$observers, - normalizedVal; + normalizedVal, + nodeName; if (booleanKey) { this.$$element.prop(key, value); @@ -13223,19 +15655,14 @@ function $CompileProvider($provide) { } } + nodeName = nodeName_(this.$$element); - // sanitize a[href] values - if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { - urlSanitizationNode.setAttribute('href', value); - - // href property always returns normalized absolute url, so we can match against that - normalizedVal = urlSanitizationNode.href; - if (!normalizedVal.match(urlSanitizationWhitelist)) { - this[key] = value = 'unsafe:' + normalizedVal; - } + // sanitize a[href] and img[src] values + if ((nodeName === 'A' && key === 'href') || + (nodeName === 'IMG' && key === 'src')) { + this[key] = value = $$sanitizeUri(value, key === 'src'); } - if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); @@ -13245,6 +15672,7 @@ function $CompileProvider($provide) { } // fire observers + var $$observers = this.$$observers; $$observers && forEach($$observers[key], function(fn) { try { fn(value); @@ -13256,12 +15684,22 @@ function $CompileProvider($provide) { /** - * Observe an interpolated attribute. - * The observer will never be called, if given attribute is not interpolated. + * @ngdoc method + * @name $compile.directive.Attributes#$observe + * @kind function + * + * @description + * Observes an interpolated attribute. + * + * The observer function will be invoked once during the next `$digest` following + * compilation. The observer is then invoked whenever the interpolated value + * changes. * * @param {string} key Normalized key. (ie ngAttribute) . - * @param {function(*)} fn Function that will be called whenever the attribute value changes. - * @returns {function(*)} the `fn` Function passed in. + * @param {function(interpolatedValue)} fn Function that will be called whenever + the interpolated value of the attribute changes. + * See the {@link guide/directive#Attributes Directives} guide for more info. + * @returns {function()} the `fn` parameter. */ $observe: function(key, fn) { var attrs = this, @@ -13279,34 +15717,39 @@ function $CompileProvider($provide) { } }; - var urlSanitizationNode = $document[0].createElement('a'), - startSymbol = $interpolate.startSymbol(), + var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); - }; + }, + NG_ATTR_BINDING = /^ngAttr[A-Z]/; return compile; //================================ - function compile($compileNodes, transcludeFn, maxPriority) { + function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, + previousCompileContext) { if (!($compileNodes instanceof jqLite)) { - // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it. + // jquery always rewraps, whereas we need to preserve the original selector so that we can + // modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = jqLite(node).wrap('').parent()[0]; + $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; } }); - var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); - return function publicLinkFn(scope, cloneConnectFn){ + var compositeLinkFn = + compileNodes($compileNodes, transcludeFn, $compileNodes, + maxPriority, ignoreDirective, previousCompileContext); + safeAddClass($compileNodes, 'ng-scope'); + return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. @@ -13314,24 +15757,25 @@ function $CompileProvider($provide) { ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! : $compileNodes; + forEach(transcludeControllers, function(instance, name) { + $linkNode.data('$' + name + 'Controller', instance); + }); + // Attach scope only to non-text nodes. for(var i = 0, ii = $linkNode.length; i addDirective(directives, - directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); + directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); // iterate over the attributes - for (var attr, name, nName, value, nAttrs = node.attributes, + for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { + var attrStartName = false; + var attrEndName = false; + attr = nAttrs[j]; - if (attr.specified) { + if (!msie || msie >= 8 || attr.specified) { name = attr.name; + value = trim(attr.value); + + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { + name = snake_case(ngAttrName.substr(6), '-'); + } + + var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); + if (ngAttrName === directiveNName + 'Start') { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } + nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; - attrs[nName] = value = trim((msie && name == 'href') - ? decodeURIComponent(node.getAttribute(name, 2)) - : attr.value); - if (getBooleanAttrName(node, nName)) { - attrs[nName] = true; // presence means true + if (isNgAttr || !attrs.hasOwnProperty(nName)) { + attrs[nName] = value; + if (getBooleanAttrName(node, nName)) { + attrs[nName] = true; // presence means true + } } addAttrInterpolateDirective(node, directives, value, nName); - addDirective(directives, nName, 'A', maxPriority); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, + attrEndName); } } @@ -13474,7 +15970,7 @@ function $CompileProvider($provide) { if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); - if (addDirective(directives, nName, 'C', maxPriority)) { + if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); @@ -13489,12 +15985,13 @@ function $CompileProvider($provide) { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority)) { + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[2]); } } } catch (e) { - // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. + // turns out that under some circumstances IE9 throws errors when one attempts to read + // comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; @@ -13504,6 +16001,53 @@ function $CompileProvider($provide) { return directives; } + /** + * Given a node with an directive-start it collects all of the siblings until it finds + * directive-end. + * @param node + * @param attrStart + * @param attrEnd + * @returns {*} + */ + function groupScan(node, attrStart, attrEnd) { + var nodes = []; + var depth = 0; + if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { + var startNode = node; + do { + if (!node) { + throw $compileMinErr('uterdir', + "Unterminated attribute, found '{0}' but no matching '{1}' found.", + attrStart, attrEnd); + } + if (node.nodeType == 1 /** Element **/) { + if (node.hasAttribute(attrStart)) depth++; + if (node.hasAttribute(attrEnd)) depth--; + } + nodes.push(node); + node = node.nextSibling; + } while (depth > 0); + } else { + nodes.push(node); + } + + return jqLite(nodes); + } + + /** + * Wrapper for linking function which converts normal linking function into a grouped + * linking function. + * @param linkFn + * @param attrStart + * @param attrEnd + * @returns {Function} + */ + function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { + return function(scope, element, attrs, controllers, transcludeFn) { + element = groupScan(element[0], attrStart, attrEnd); + return linkFn(scope, element, attrs, controllers, transcludeFn); + }; + } /** * Once the directives have been collected, their compile functions are executed. This method @@ -13514,32 +16058,53 @@ function $CompileProvider($provide) { * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function - * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the - * scope argument is auto-generated to the new child of the transcluded parent scope. + * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the + * scope argument is auto-generated to the new + * child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this - * argument has the root jqLite array so that we can replace nodes on it. - * @returns linkFn + * argument has the root jqLite array so that we can replace nodes + * on it. + * @param {Object=} originalReplaceDirective An optional directive that will be ignored when + * compiling the transclusion. + * @param {Array.} preLinkFns + * @param {Array.} postLinkFns + * @param {Object} previousCompileContext Context used for previous compilation of the current + * node + * @returns {Function} linkFn */ - function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) { + function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, + jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, + previousCompileContext) { + previousCompileContext = previousCompileContext || {}; + var terminalPriority = -Number.MAX_VALUE, - preLinkFns = [], - postLinkFns = [], - newScopeDirective = null, - newIsolateScopeDirective = null, - templateDirective = null, + newScopeDirective, + controllerDirectives = previousCompileContext.controllerDirectives, + newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, + templateDirective = previousCompileContext.templateDirective, + nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, + hasTranscludeDirective = false, + hasTemplate = false, + hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, - transcludeDirective, + replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, - controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; + var attrStart = directive.$$start; + var attrEnd = directive.$$end; + + // collect multiblock sections + if (attrStart) { + $compileNode = groupScan(compileNode, attrStart, attrEnd); + } $template = undefined; if (terminalPriority > directive.priority) { @@ -13547,18 +16112,23 @@ function $CompileProvider($provide) { } if (directiveValue = directive.scope) { - assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); - if (isObject(directiveValue)) { - safeAddClass($compileNode, 'ng-isolate-scope'); - newIsolateScopeDirective = directive; - } - safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; + + // skip the check for directives with async templates, we'll check the derived sync + // directive when the template arrives + if (!directive.templateUrl) { + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, + $compileNode); + if (isObject(directiveValue)) { + newIsolateScopeDirective = directive; + } + } } directiveName = directive.name; - if (directiveValue = directive.controller) { + if (!directive.templateUrl && directive.controller) { + directiveValue = directive.controller; controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); @@ -13566,36 +16136,68 @@ function $CompileProvider($provide) { } if (directiveValue = directive.transclude) { - assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); - transcludeDirective = directive; - terminalPriority = directive.priority; + hasTranscludeDirective = true; + + // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. + // This option should only be used by directives that know how to safely handle element transclusion, + // where the transcluded nodes are added or replaced after linking. + if (!directive.$$tlb) { + assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); + nonTlbTranscludeDirective = directive; + } + if (directiveValue == 'element') { - $template = jqLite(compileNode); + hasElementTranscludeDirective = true; + terminalPriority = directive.priority; + $template = $compileNode; $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); + jqLite(document.createComment(' ' + directiveName + ': ' + + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; - replaceWith(jqCollection, jqLite($template[0]), compileNode); - childTranscludeFn = compile($template, transcludeFn, terminalPriority); + replaceWith(jqCollection, sliceArgs($template), compileNode); + + childTranscludeFn = compile($template, transcludeFn, terminalPriority, + replaceDirective && replaceDirective.name, { + // Don't pass in: + // - controllerDirectives - otherwise we'll create duplicates controllers + // - newIsolateScopeDirective or templateDirective - combining templates with + // element transclusion doesn't make sense. + // + // We need only nonTlbTranscludeDirective so that we prevent putting transclusion + // on the same element more than once. + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); } else { - $template = jqLite(JQLiteClone(compileNode)).contents(); - $compileNode.html(''); // clear contents + $template = jqLite(jqLiteClone(compileNode)).contents(); + $compileNode.empty(); // clear contents childTranscludeFn = compile($template, transcludeFn); } } - if ((directiveValue = directive.template)) { + if (directive.template) { + hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; + + directiveValue = (isFunction(directive.template)) + ? directive.template($compileNode, templateAttrs) + : directive.template; + directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { - $template = jqLite('
    ' + - trim(directiveValue) + - '
    ').contents(); + replaceDirective = directive; + if (jqLiteIsTextNode(directiveValue)) { + $template = []; + } else { + $template = jqLite(trim(directiveValue)); + } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { - throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + directiveName, ''); } replaceWith(jqCollection, $compileNode, compileNode); @@ -13604,16 +16206,16 @@ function $CompileProvider($provide) { // combine directives from the original node and from the template: // - take the array of directives for this element - // - split it into two parts, those that were already applied and those that weren't - // - collect directives from the template, add them to the second group and sort them - // - append the second group with new directives to the first group - directives = directives.concat( - collectDirectives( - compileNode, - directives.splice(i + 1, directives.length - (i + 1)), - newTemplateAttrs - ) - ); + // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) + // - collect directives from the template and sort them by priority + // - combine directives as: processed + template + unprocessed + var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); + var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); + + if (newIsolateScopeDirective) { + markDirectivesAsIsolate(templateDirectives); + } + directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; @@ -13623,19 +16225,29 @@ function $CompileProvider($provide) { } if (directive.templateUrl) { + hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; - nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), - nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace, - childTranscludeFn); + + if (directive.replace) { + replaceDirective = directive; + } + + nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, + templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { + controllerDirectives: controllerDirectives, + newIsolateScopeDirective: newIsolateScopeDirective, + templateDirective: templateDirective, + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { - addLinkFns(null, linkFn); + addLinkFns(null, linkFn, attrStart, attrEnd); } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post); + addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); @@ -13649,27 +16261,41 @@ function $CompileProvider($provide) { } - nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; - nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; + nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; + nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; + nodeLinkFn.templateOnThisElement = hasTemplate; + nodeLinkFn.transclude = childTranscludeFn; + + previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// - function addLinkFns(pre, post) { + function addLinkFns(pre, post, attrStart, attrEnd) { if (pre) { + if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; + pre.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + pre = cloneAndAnnotateFn(pre, {isolateScope: true}); + } preLinkFns.push(pre); } if (post) { + if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; + post.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + post = cloneAndAnnotateFn(post, {isolateScope: true}); + } postLinkFns.push(post); } } - function getControllers(require, $element) { + function getControllers(directiveName, require, $element, elementControllers) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { @@ -13679,15 +16305,23 @@ function $CompileProvider($provide) { } optional = optional || value == '?'; } - value = $element[retrievalMethod]('$' + require + 'Controller'); + value = null; + + if (elementControllers && retrievalMethod === 'data') { + value = elementControllers[require]; + } + value = value || $element[retrievalMethod]('$' + require + 'Controller'); + if (!value && !optional) { - throw Error("No controller: " + require); + throw $compileMinErr('ctreq', + "Controller '{0}', required by directive '{1}', can't be found!", + require, directiveName); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { - value.push(getControllers(require, $element)); + value.push(getControllers(directiveName, require, $element, elementControllers)); }); } return value; @@ -13695,99 +16329,131 @@ function $CompileProvider($provide) { function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var attrs, $element, i, ii, linkFn, controller; + var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; - if (compileNode === linkNode) { - attrs = templateAttrs; - } else { - attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); - } + attrs = (compileNode === linkNode) + ? templateAttrs + : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); $element = attrs.$$element; if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/; + var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; + + isolateScope = scope.$new(true); + + if (templateDirective && (templateDirective === newIsolateScopeDirective || + templateDirective === newIsolateScopeDirective.$$originalDirective)) { + $element.data('$isolateScope', isolateScope); + } else { + $element.data('$isolateScopeNoTemplate', isolateScope); + } + + - var parentScope = scope.$parent || scope; + safeAddClass($element, 'ng-isolate-scope'); - forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) { - var match = definiton.match(LOCAL_REGEXP) || [], - attrName = match[2]|| scopeName, + forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { + var match = definition.match(LOCAL_REGEXP) || [], + attrName = match[3] || scopeName, + optional = (match[2] == '?'), mode = match[1], // @, =, or & lastValue, - parentGet, parentSet; + parentGet, parentSet, compare; - scope.$$isolateBindings[scopeName] = mode + attrName; + isolateScope.$$isolateBindings[scopeName] = mode + attrName; switch (mode) { - case '@': { + case '@': attrs.$observe(attrName, function(value) { - scope[scopeName] = value; + isolateScope[scopeName] = value; }); - attrs.$$observers[attrName].$$scope = parentScope; + attrs.$$observers[attrName].$$scope = scope; + if( attrs[attrName] ) { + // If the attribute has been provided then we trigger an interpolation to ensure + // the value is there for use in the link fn + isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); + } break; - } - case '=': { + case '=': + if (optional && !attrs[attrName]) { + return; + } parentGet = $parse(attrs[attrName]); + if (parentGet.literal) { + compare = equals; + } else { + compare = function(a,b) { return a === b || (a !== a && b !== b); }; + } parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest - lastValue = scope[scopeName] = parentGet(parentScope); - throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + - ' (directive: ' + newIsolateScopeDirective.name + ')'); + lastValue = isolateScope[scopeName] = parentGet(scope); + throw $compileMinErr('nonassign', + "Expression '{0}' used with directive '{1}' is non-assignable!", + attrs[attrName], newIsolateScopeDirective.name); }; - lastValue = scope[scopeName] = parentGet(parentScope); - scope.$watch(function parentValueWatch() { - var parentValue = parentGet(parentScope); - - if (parentValue !== scope[scopeName]) { + lastValue = isolateScope[scopeName] = parentGet(scope); + isolateScope.$watch(function parentValueWatch() { + var parentValue = parentGet(scope); + if (!compare(parentValue, isolateScope[scopeName])) { // we are out of sync and need to copy - if (parentValue !== lastValue) { + if (!compare(parentValue, lastValue)) { // parent changed and it has precedence - lastValue = scope[scopeName] = parentValue; + isolateScope[scopeName] = parentValue; } else { // if the parent can be assigned then do so - parentSet(parentScope, parentValue = lastValue = scope[scopeName]); + parentSet(scope, parentValue = isolateScope[scopeName]); } } - return parentValue; - }); + return lastValue = parentValue; + }, null, parentGet.literal); break; - } - case '&': { + case '&': parentGet = $parse(attrs[attrName]); - scope[scopeName] = function(locals) { - return parentGet(parentScope, locals); + isolateScope[scopeName] = function(locals) { + return parentGet(scope, locals); }; break; - } - default: { - throw Error('Invalid isolate scope definition for directive ' + - newIsolateScopeDirective.name + ': ' + definiton); - } + default: + throw $compileMinErr('iscp', + "Invalid isolate scope definition for directive '{0}'." + + " Definition: {... {1}: '{2}' ...}", + newIsolateScopeDirective.name, scopeName, definition); } }); } - + transcludeFn = boundTranscludeFn && controllersBoundTransclude; if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { - $scope: scope, + $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, $element: $element, $attrs: attrs, - $transclude: boundTranscludeFn - }; + $transclude: transcludeFn + }, controllerInstance; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } - $element.data( - '$' + directive.name + 'Controller', - $controller(controller, locals)); + controllerInstance = $controller(controller, locals); + // For directives with element transclusion the element is a comment, + // but jQuery .data doesn't support attaching data to comment nodes as it's hard to + // clean up (http://bugs.jquery.com/ticket/8335). + // Instead, we save the controllers for the element in a local hash and attach to .data + // later, once we have the actual element. + elementControllers[directive.name] = controllerInstance; + if (!hasElementTranscludeDirective) { + $element.data('$' + directive.name + 'Controller', controllerInstance); + } + + if (directive.controllerAs) { + locals.$scope[directive.controllerAs] = controllerInstance; + } }); } @@ -13795,29 +16461,58 @@ function $CompileProvider($provide) { for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; - linkFn(scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element)); + linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION - childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); + // We only pass the isolate scope, if the isolate directive has a template, + // otherwise the child elements do not belong to the isolate directive. + var scopeToChild = scope; + if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { + scopeToChild = isolateScope; + } + childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING - for(i = 0, ii = postLinkFns.length; i < ii; i++) { + for(i = postLinkFns.length - 1; i >= 0; i--) { try { linkFn = postLinkFns[i]; - linkFn(scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element)); + linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } + + // This is the function that is injected as `$transclude`. + function controllersBoundTransclude(scope, cloneAttachFn) { + var transcludeControllers; + + // no scope passed + if (arguments.length < 2) { + cloneAttachFn = scope; + scope = undefined; + } + + if (hasElementTranscludeDirective) { + transcludeControllers = elementControllers; + } + + return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); + } } } + function markDirectivesAsIsolate(directives) { + // mark all directives as needing isolate scope. + for (var j = 0, jj = directives.length; j < jj; j++) { + directives[j] = inherit(directives[j], {$$isolateScope: true}); + } + } /** * looks up the directive and decorates it with exception handling and proper parameters. We @@ -13831,10 +16526,12 @@ function $CompileProvider($provide) { * * `A': attribute * * `C`: class * * `M`: comment - * @returns true if directive was added. + * @returns {boolean} true if directive was added. */ - function addDirective(tDirectives, name, location, maxPriority) { - var match = false; + function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, + endAttrName) { + if (name === ignoreDirective) return null; + var match = null; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i directive.priority) && directive.restrict.indexOf(location) != -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } tDirectives.push(directive); - match = true; + match = directive; } } catch(e) { $exceptionHandler(e); } } @@ -13868,7 +16568,7 @@ function $CompileProvider($provide) { // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { - if (src[key]) { + if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); @@ -13882,6 +16582,10 @@ function $CompileProvider($provide) { dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); + dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; + // `dst` will never contain hasOwnProperty as DOM parser won't let it. + // You will get an "InvalidCharacterError: DOM Exception 5" error if you + // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; @@ -13890,8 +16594,8 @@ function $CompileProvider($provide) { } - function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, - $rootElement, replace, childTranscludeFn) { + function compileTemplateUrl(directives, $compileNode, tAttrs, + $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, @@ -13899,28 +16603,42 @@ function $CompileProvider($provide) { origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { - controller: null, templateUrl: null, transclude: null, scope: null - }); + templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective + }), + templateUrl = (isFunction(origAsyncDirective.templateUrl)) + ? origAsyncDirective.templateUrl($compileNode, tAttrs) + : origAsyncDirective.templateUrl; - $compileNode.html(''); + $compileNode.empty(); - $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). + $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). success(function(content) { - var compileNode, tempTemplateAttrs, $template; + var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); - if (replace) { - $template = jqLite('
    ' + trim(content) + '
    ').contents(); + if (origAsyncDirective.replace) { + if (jqLiteIsTextNode(content)) { + $template = []; + } else { + $template = jqLite(trim(content)); + } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { - throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + origAsyncDirective.name, templateUrl); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); - collectDirectives(compileNode, directives, tempTemplateAttrs); + var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); + + if (isObject(origAsyncDirective.scope)) { + markDirectivesAsIsolate(templateDirectives); + } + directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; @@ -13928,43 +16646,64 @@ function $CompileProvider($provide) { } directives.unshift(derivedSyncDirective); - afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn); - afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); + afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, + childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, + previousCompileContext); + forEach($rootElement, function(node, i) { + if (node == compileNode) { + $rootElement[i] = $compileNode[0]; + } + }); + afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while(linkQueue.length) { - var controller = linkQueue.pop(), - linkRootElement = linkQueue.pop(), - beforeTemplateLinkNode = linkQueue.pop(), - scope = linkQueue.pop(), - linkNode = compileNode; + var scope = linkQueue.shift(), + beforeTemplateLinkNode = linkQueue.shift(), + linkRootElement = linkQueue.shift(), + boundTranscludeFn = linkQueue.shift(), + linkNode = $compileNode[0]; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { - // it was cloned therefore we have to clone as well. - linkNode = JQLiteClone(compileNode); + var oldClasses = beforeTemplateLinkNode.className; + + if (!(previousCompileContext.hasElementTranscludeDirective && + origAsyncDirective.replace)) { + // it was cloned therefore we have to clone as well. + linkNode = jqLiteClone(compileNode); + } + replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); - } - afterTemplateNodeLinkFn(function() { - beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); - }, scope, linkNode, $rootElement, controller); + // Copy in CSS classes from original node + safeAddClass(jqLite(linkNode), oldClasses); + } + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } else { + childBoundTranscludeFn = boundTranscludeFn; + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, + childBoundTranscludeFn); } linkQueue = null; }). error(function(response, code, headers, config) { - throw Error('Failed to load template: ' + config.url); + throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); }); - return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { + return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { + var childBoundTranscludeFn = boundTranscludeFn; if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); - linkQueue.push(controller); + linkQueue.push(childBoundTranscludeFn); } else { - afterTemplateNodeLinkFn(function() { - beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); - }, scope, node, rootElement, controller); + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } @@ -13974,33 +16713,59 @@ function $CompileProvider($provide) { * Sorting function for bound directives. */ function byPriority(a, b) { - return b.priority - a.priority; + var diff = b.priority - a.priority; + if (diff !== 0) return diff; + if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; + return a.index - b.index; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { - throw Error('Multiple directives [' + previousDirective.name + ', ' + - directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); + throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', + previousDirective.name, directive.name, what, startingTag(element)); } } - function addTextInterpolateDirective(directives, text) { - var interpolateFn = $interpolate(text, true); - if (interpolateFn) { - directives.push({ - priority: 0, - compile: valueFn(function textInterpolateLinkFn(scope, node) { - var parent = node.parent(), - bindings = parent.data('$binding') || []; - bindings.push(interpolateFn); - safeAddClass(parent.data('$binding', bindings), 'ng-binding'); - scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { - node[0].nodeValue = value; - }); - }) - }); + function addTextInterpolateDirective(directives, text) { + var interpolateFn = $interpolate(text, true); + if (interpolateFn) { + directives.push({ + priority: 0, + compile: function textInterpolateCompileFn(templateNode) { + // when transcluding a template that has bindings in the root + // then we don't have a parent and should do this in the linkFn + var parent = templateNode.parent(), hasCompileParent = parent.length; + if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding'); + + return function textInterpolateLinkFn(scope, node) { + var parent = node.parent(), + bindings = parent.data('$binding') || []; + bindings.push(interpolateFn); + parent.data('$binding', bindings); + if (!hasCompileParent) safeAddClass(parent, 'ng-binding'); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }; + } + }); + } + } + + + function getTrustedContext(node, attrNormalizedName) { + if (attrNormalizedName == "srcdoc") { + return $sce.HTML; + } + var tag = nodeName_(node); + // maction[xlink:href] can source SVG. It's not limited to . + if (attrNormalizedName == "xlinkHref" || + (tag == "FORM" && attrNormalizedName == "action") || + (tag != "IMG" && (attrNormalizedName == "src" || + attrNormalizedName == "ngSrc"))) { + return $sce.RESOURCE_URL; } } @@ -14012,24 +16777,54 @@ function $CompileProvider($provide) { if (!interpolateFn) return; + if (name === "multiple" && nodeName_(node) === "SELECT") { + throw $compileMinErr("selmulti", + "Binding to the 'multiple' attribute is not supported. Element: {0}", + startingTag(node)); + } + directives.push({ priority: 100, - compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { - var $$observers = (attr.$$observers || (attr.$$observers = {})); + compile: function() { + return { + pre: function attrInterpolatePreLinkFn(scope, element, attr) { + var $$observers = (attr.$$observers || (attr.$$observers = {})); + + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', + "Interpolations for HTML DOM event attributes are disallowed. Please use the " + + "ng- versions (such as ng-click instead of onclick) instead."); + } - if (name === 'class') { - // we need to interpolate classes again, in the case the element was replaced - // and therefore the two class attrs got merged - we want to interpolate the result - interpolateFn = $interpolate(attr[name], true); + // we need to interpolate again, in case the attribute value has been updated + // (e.g. by another directive's compile function) + interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); + + // if attribute was updated so that there is no interpolation going on we don't want to + // register any observers + if (!interpolateFn) return; + + // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the + // actual attr value + attr[name] = interpolateFn(scope); + ($$observers[name] || ($$observers[name] = [])).$$inter = true; + (attr.$$observers && attr.$$observers[name].$$scope || scope). + $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service. Be sure to + //skip animations when the first digest occurs (when + //both the new and the old values are the same) since + //the CSS classes are the non-interpolated values + if(name === 'class' && newValue != oldValue) { + attr.$updateClass(newValue, oldValue); + } else { + attr.$set(name, newValue); + } + }); + } + }; } - - attr[name] = undefined; - ($$observers[name] || ($$observers[name] = [])).$$inter = true; - (attr.$$observers && attr.$$observers[name].$$scope || scope). - $watch(interpolateFn, function interpolateFnWatchAction(value) { - attr.$set(name, value); - }); - }) }); } @@ -14039,31 +16834,56 @@ function $CompileProvider($provide) { * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes - * in the root of the tree. - * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, - * but replace its DOM node reference. + * in the root of the tree. + * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep + * the shell, but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ - function replaceWith($rootElement, $element, newNode) { - var oldNode = $element[0], - parent = oldNode.parentNode, + function replaceWith($rootElement, elementsToRemove, newNode) { + var firstElementToRemove = elementsToRemove[0], + removeCount = elementsToRemove.length, + parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == oldNode) { - $rootElement[i] = newNode; + if ($rootElement[i] == firstElementToRemove) { + $rootElement[i++] = newNode; + for (var j = i, j2 = j + removeCount - 1, + jj = $rootElement.length; + j < jj; j++, j2++) { + if (j2 < jj) { + $rootElement[j] = $rootElement[j2]; + } else { + delete $rootElement[j]; + } + } + $rootElement.length -= removeCount - 1; break; } } } if (parent) { - parent.replaceChild(newNode, oldNode); + parent.replaceChild(newNode, firstElementToRemove); + } + var fragment = document.createDocumentFragment(); + fragment.appendChild(firstElementToRemove); + newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; + for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { + var element = elementsToRemove[k]; + jqLite(element).remove(); // must do this way to clean up expando + fragment.appendChild(element); + delete elementsToRemove[k]; } - newNode[jqLite.expando] = oldNode[jqLite.expando]; - $element[0] = newNode; + elementsToRemove[0] = newNode; + elementsToRemove.length = 1; + } + + + function cloneAndAnnotateFn(fn, annotation) { + return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } }]; } @@ -14072,7 +16892,7 @@ var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': - * my:DiRective + * my:Directive * my-directive * x-my-directive * data-my:directive @@ -14085,40 +16905,40 @@ function directiveNormalize(name) { } /** - * @ngdoc object - * @name ng.$compile.directive.Attributes - * @description + * @ngdoc type + * @name $compile.directive.Attributes * - * A shared object between directive compile / linking functions which contains normalized DOM element - * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed - * since all of these are treated as equivalent in Angular: + * @description + * A shared object between directive compile / linking functions which contains normalized DOM + * element attributes. The values reflect current binding state `{{ }}`. The normalization is + * needed since all of these are treated as equivalent in Angular: * - * + * ``` + * + * ``` */ /** * @ngdoc property - * @name ng.$compile.directive.Attributes#$attr - * @propertyOf ng.$compile.directive.Attributes + * @name $compile.directive.Attributes#$attr * @returns {object} A map of DOM element attribute names to the normalized name. This is - * needed to do reverse lookup from normalized name back to actual name. + * needed to do reverse lookup from normalized name back to actual name. */ /** - * @ngdoc function - * @name ng.$compile.directive.Attributes#$set - * @methodOf ng.$compile.directive.Attributes - * @function + * @ngdoc method + * @name $compile.directive.Attributes#$set + * @kind function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is - * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} + * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. - * @param {string} value Value to set the attribute to. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ @@ -14142,9 +16962,25 @@ function directiveLinkingFn( /* function(Function) */ boundTranscludeFn ){} +function tokenDifference(str1, str2) { + var values = '', + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); + + outer: + for(var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for(var j = 0; j < tokens2.length; j++) { + if(token == tokens2[j]) continue outer; + } + values += (values.length > 0 ? ' ' : '') + token; + } + return values; +} + /** - * @ngdoc object - * @name ng.$controllerProvider + * @ngdoc provider + * @name $controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. @@ -14153,20 +16989,22 @@ function directiveLinkingFn( * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { - var controllers = {}; + var controllers = {}, + CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** - * @ngdoc function - * @name ng.$controllerProvider#register - * @methodOf ng.$controllerProvider - * @param {string} name Controller name + * @ngdoc method + * @name $controllerProvider#register + * @param {string|Object} name Controller name, or an object map of controllers where the keys are + * the names and the values are the constructors. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { + assertNotHasOwnProperty(name, 'controller'); if (isObject(name)) { - extend(controllers, name) + extend(controllers, name); } else { controllers[name] = constructor; } @@ -14176,8 +17014,8 @@ function $ControllerProvider() { this.$get = ['$injector', '$window', function($injector, $window) { /** - * @ngdoc function - * @name ng.$controller + * @ngdoc service + * @name $controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the @@ -14194,33 +17032,64 @@ function $ControllerProvider() { * @description * `$controller` service is responsible for instantiating controllers. * - * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into - * a service, so that one can override this service with {@link https://gist.github.com/1649788 - * BC version}. + * It's just a simple call to {@link auto.$injector $injector}, but extracted into + * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ - return function(constructor, locals) { - if(isString(constructor)) { - var name = constructor; - constructor = controllers.hasOwnProperty(name) - ? controllers[name] - : getter(locals.$scope, name, true) || getter($window, name, true); - - assertArgFn(constructor, name, true); + return function(expression, locals) { + var instance, match, constructor, identifier; + + if(isString(expression)) { + match = expression.match(CNTRL_REG), + constructor = match[1], + identifier = match[3]; + expression = controllers.hasOwnProperty(constructor) + ? controllers[constructor] + : getter(locals.$scope, constructor, true) || getter($window, constructor, true); + + assertArgFn(expression, constructor, true); } - return $injector.instantiate(constructor, locals); + instance = $injector.instantiate(expression, locals); + + if (identifier) { + if (!(locals && typeof locals.$scope === 'object')) { + throw minErr('$controller')('noscp', + "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", + constructor || expression.name, identifier); + } + + locals.$scope[identifier] = instance; + } + + return instance; }; }]; } /** - * @ngdoc object - * @name ng.$document + * @ngdoc service + * @name $document * @requires $window * * @description - * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` - * element. + * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. + * + * @example + + +
    +

    $document title:

    +

    window.document title:

    +
    +
    + + angular.module('documentExample', []) + .controller('ExampleController', ['$scope', '$document', function($scope, $document) { + $scope.title = $document[0].title; + $scope.windowTitle = angular.element(window.document)[0].title; + }]); + +
    */ function $DocumentProvider(){ this.$get = ['$window', function(window){ @@ -14229,9 +17098,9 @@ function $DocumentProvider(){ } /** - * @ngdoc function - * @name ng.$exceptionHandler - * @requires $log + * @ngdoc service + * @name $exceptionHandler + * @requires ng.$log * * @description * Any uncaught exception in angular expressions is delegated to this service. @@ -14241,6 +17110,20 @@ function $DocumentProvider(){ * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * + * ## Example: + * + * ```js + * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { + * return function (exception, cause) { + * exception.message += ' (caused by "' + cause + '")'; + * throw exception; + * }; + * }); + * ``` + * + * This example will override the normal action of `$exceptionHandler`, to make angular + * exceptions fail hard when they happen, instead of just logging to the console. + * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. @@ -14255,67 +17138,1372 @@ function $ExceptionHandlerProvider() { } /** - * @ngdoc object - * @name ng.$interpolateProvider - * @function + * Parse headers into key value object * - * @description + * @param {string} headers Raw headers as a string + * @returns {Object} Parsed headers as key value object + */ +function parseHeaders(headers) { + var parsed = {}, key, val, i; + + if (!headers) return parsed; + + forEach(headers.split('\n'), function(line) { + i = line.indexOf(':'); + key = lowercase(trim(line.substr(0, i))); + val = trim(line.substr(i + 1)); + + if (key) { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +} + + +/** + * Returns a function that provides access to parsed headers. * - * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * Headers are lazy parsed when first requested. + * @see parseHeaders + * + * @param {(string|Object)} headers Headers to provide access to. + * @returns {function(string=)} Returns a getter function which if called with: + * + * - if called with single an argument returns a single header value or null + * - if called with no arguments returns an object containing all headers. */ -function $InterpolateProvider() { - var startSymbol = '{{'; - var endSymbol = '}}'; +function headersGetter(headers) { + var headersObj = isObject(headers) ? headers : undefined; - /** - * @ngdoc method - * @name ng.$interpolateProvider#startSymbol - * @methodOf ng.$interpolateProvider - * @description - * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. - * - * @param {string=} value new value to set the starting symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.startSymbol = function(value){ - if (value) { - startSymbol = value; - return this; - } else { - return startSymbol; + return function(name) { + if (!headersObj) headersObj = parseHeaders(headers); + + if (name) { + return headersObj[lowercase(name)] || null; } + + return headersObj; }; +} + + +/** + * Chain all given functions + * + * This function is used for both request and response transforming + * + * @param {*} data Data to transform. + * @param {function(string=)} headers Http headers getter fn. + * @param {(Function|Array.)} fns Function or an array of functions. + * @returns {*} Transformed data. + */ +function transformData(data, headers, fns) { + if (isFunction(fns)) + return fns(data, headers); + + forEach(fns, function(fn) { + data = fn(data, headers); + }); + + return data; +} + + +function isSuccess(status) { + return 200 <= status && status < 300; +} + + +/** + * @ngdoc provider + * @name $httpProvider + * @description + * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. + * */ +function $HttpProvider() { + var JSON_START = /^\s*(\[|\{[^\{])/, + JSON_END = /[\}\]]\s*$/, + PROTECTION_PREFIX = /^\)\]\}',?\n/, + CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; /** - * @ngdoc method - * @name ng.$interpolateProvider#endSymbol - * @methodOf ng.$interpolateProvider + * @ngdoc property + * @name $httpProvider#defaults * @description - * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * - * @param {string=} value new value to set the ending symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.endSymbol = function(value){ - if (value) { - endSymbol = value; - return this; - } else { - return endSymbol; - } + * Object containing default values for all {@link ng.$http $http} requests. + * + * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. + * Defaults value is `'XSRF-TOKEN'`. + * + * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the + * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. + * + * - **`defaults.headers`** - {Object} - Default headers for all $http requests. + * Refer to {@link ng.$http#setting-http-headers $http} for documentation on + * setting default headers. + * - **`defaults.headers.common`** + * - **`defaults.headers.post`** + * - **`defaults.headers.put`** + * - **`defaults.headers.patch`** + **/ + var defaults = this.defaults = { + // transform incoming response data + transformResponse: [function(data) { + if (isString(data)) { + // strip json vulnerability protection prefix + data = data.replace(PROTECTION_PREFIX, ''); + if (JSON_START.test(data) && JSON_END.test(data)) + data = fromJson(data); + } + return data; + }], + + // transform outgoing request data + transformRequest: [function(d) { + return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; + }], + + // default headers + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + }, + post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) + }, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN' }; + /** + * Are ordered by request, i.e. they are applied in the same order as the + * array, on request, but reverse order, on response. + */ + var interceptorFactories = this.interceptors = []; - this.$get = ['$parse', function($parse) { - var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length; + /** + * For historical reasons, response interceptors are ordered by the order in which + * they are applied to the response. (This is the opposite of interceptorFactories) + */ + var responseInterceptorFactories = this.responseInterceptors = []; + + this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', + function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { + + var defaultCache = $cacheFactory('$http'); /** - * @ngdoc function - * @name ng.$interpolate - * @function + * Interceptors stored in reverse order. Inner interceptors before outer interceptors. + * The reversal is needed so that we can build up the interception chain around the + * server request. + */ + var reversedInterceptors = []; + + forEach(interceptorFactories, function(interceptorFactory) { + reversedInterceptors.unshift(isString(interceptorFactory) + ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); + }); + + forEach(responseInterceptorFactories, function(interceptorFactory, index) { + var responseFn = isString(interceptorFactory) + ? $injector.get(interceptorFactory) + : $injector.invoke(interceptorFactory); + + /** + * Response interceptors go before "around" interceptors (no real reason, just + * had to pick one.) But they are already reversed, so we can't use unshift, hence + * the splice. + */ + reversedInterceptors.splice(index, 0, { + response: function(response) { + return responseFn($q.when(response)); + }, + responseError: function(response) { + return responseFn($q.reject(response)); + } + }); + }); + + + /** + * @ngdoc service + * @kind function + * @name $http + * @requires ng.$httpBackend + * @requires $cacheFactory + * @requires $rootScope + * @requires $q + * @requires $injector * - * @requires $parse + * @description + * The `$http` service is a core Angular service that facilitates communication with the remote + * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) + * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). + * + * For unit testing applications that use `$http` service, see + * {@link ngMock.$httpBackend $httpBackend mock}. + * + * For a higher level of abstraction, please check out the {@link ngResource.$resource + * $resource} service. + * + * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by + * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage + * it is important to familiarize yourself with these APIs and the guarantees they provide. + * + * + * # General usage + * The `$http` service is a function which takes a single argument — a configuration object — + * that is used to generate an HTTP request and returns a {@link ng.$q promise} + * with two $http specific methods: `success` and `error`. + * + * ```js + * $http({method: 'GET', url: '/someUrl'}). + * success(function(data, status, headers, config) { + * // this callback will be called asynchronously + * // when the response is available + * }). + * error(function(data, status, headers, config) { + * // called asynchronously if an error occurs + * // or server returns response with an error status. + * }); + * ``` + * + * Since the returned value of calling the $http function is a `promise`, you can also use + * the `then` method to register callbacks, and these callbacks will receive a single argument – + * an object representing the response. See the API signature and type info below for more + * details. + * + * A response status code between 200 and 299 is considered a success status and + * will result in the success callback being called. Note that if the response is a redirect, + * XMLHttpRequest will transparently follow it, meaning that the error callback will not be + * called for such responses. + * + * # Writing Unit Tests that use $http + * When unit testing (using {@link ngMock ngMock}), it is necessary to call + * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending + * request using trained responses. + * + * ``` + * $httpBackend.expectGET(...); + * $http.get(...); + * $httpBackend.flush(); + * ``` + * + * # Shortcut methods + * + * Shortcut methods are also available. All shortcut methods require passing in the URL, and + * request data must be passed in for POST/PUT requests. + * + * ```js + * $http.get('/someUrl').success(successCallback); + * $http.post('/someUrl', data).success(successCallback); + * ``` + * + * Complete list of shortcut methods: + * + * - {@link ng.$http#get $http.get} + * - {@link ng.$http#head $http.head} + * - {@link ng.$http#post $http.post} + * - {@link ng.$http#put $http.put} + * - {@link ng.$http#delete $http.delete} + * - {@link ng.$http#jsonp $http.jsonp} + * - {@link ng.$http#patch $http.patch} + * + * + * # Setting HTTP Headers + * + * The $http service will automatically add certain HTTP headers to all requests. These defaults + * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration + * object, which currently contains this default configuration: + * + * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): + * - `Accept: application/json, text/plain, * / *` + * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) + * - `Content-Type: application/json` + * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) + * - `Content-Type: application/json` + * + * To add or overwrite these defaults, simply add or remove a property from these configuration + * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object + * with the lowercased HTTP method name as the key, e.g. + * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. + * + * The defaults can also be set at runtime via the `$http.defaults` object in the same + * fashion. For example: + * + * ``` + * module.run(function($http) { + * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' + * }); + * ``` + * + * In addition, you can supply a `headers` property in the config object passed when + * calling `$http(config)`, which overrides the defaults without changing them globally. + * + * + * # Transforming Requests and Responses + * + * Both requests and responses can be transformed using transform functions. By default, Angular + * applies these transformations: + * + * Request transformations: + * + * - If the `data` property of the request configuration object contains an object, serialize it + * into JSON format. + * + * Response transformations: + * + * - If XSRF prefix is detected, strip it (see Security Considerations section below). + * - If JSON response is detected, deserialize it using a JSON parser. + * + * To globally augment or override the default transforms, modify the + * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` + * properties. These properties are by default an array of transform functions, which allows you + * to `push` or `unshift` a new transformation function into the transformation chain. You can + * also decide to completely override any default transformations by assigning your + * transformation functions to these properties directly without the array wrapper. These defaults + * are again available on the $http factory at run-time, which may be useful if you have run-time + * services you wish to be involved in your transformations. + * + * Similarly, to locally override the request/response transforms, augment the + * `transformRequest` and/or `transformResponse` properties of the configuration object passed + * into `$http`. + * + * + * # Caching + * + * To enable caching, set the request configuration `cache` property to `true` (to use default + * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). + * When the cache is enabled, `$http` stores the response from the server in the specified + * cache. The next time the same request is made, the response is served from the cache without + * sending a request to the server. + * + * Note that even if the response is served from cache, delivery of the data is asynchronous in + * the same way that real requests are. + * + * If there are multiple GET requests for the same URL that should be cached using the same + * cache, but the cache is not populated yet, only one request to the server will be made and + * the remaining requests will be fulfilled using the response from the first request. + * + * You can change the default cache to a new object (built with + * {@link ng.$cacheFactory `$cacheFactory`}) by updating the + * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set + * their `cache` property to `true` will now use this cache object. + * + * If you set the default cache to `false` then only requests that specify their own custom + * cache object will be cached. + * + * # Interceptors + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication, or any kind of synchronous or + * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be + * able to intercept requests before they are handed to the server and + * responses before they are handed over to the application code that + * initiated these requests. The interceptors leverage the {@link ng.$q + * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. + * + * The interceptors are service factories that are registered with the `$httpProvider` by + * adding them to the `$httpProvider.interceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor. + * + * There are two kinds of interceptors (and two kinds of rejection interceptors): + * + * * `request`: interceptors get called with a http `config` object. The function is free to + * modify the `config` object or create a new one. The function needs to return the `config` + * object directly, or a promise containing the `config` or a new `config` object. + * * `requestError`: interceptor gets called when a previous interceptor threw an error or + * resolved with a rejection. + * * `response`: interceptors get called with http `response` object. The function is free to + * modify the `response` object or create a new one. The function needs to return the `response` + * object directly, or as a promise containing the `response` or a new `response` object. + * * `responseError`: interceptor gets called when a previous interceptor threw an error or + * resolved with a rejection. + * + * + * ```js + * // register the interceptor as a service + * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { + * return { + * // optional method + * 'request': function(config) { + * // do something on success + * return config; + * }, + * + * // optional method + * 'requestError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * }, + * + * + * + * // optional method + * 'response': function(response) { + * // do something on success + * return response; + * }, + * + * // optional method + * 'responseError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * } + * }; + * }); + * + * $httpProvider.interceptors.push('myHttpInterceptor'); + * + * + * // alternatively, register the interceptor via an anonymous factory + * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { + * return { + * 'request': function(config) { + * // same as above + * }, + * + * 'response': function(response) { + * // same as above + * } + * }; + * }); + * ``` + * + * # Response interceptors (DEPRECATED) + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication or any kind of synchronous or + * asynchronous preprocessing of received responses, it is desirable to be able to intercept + * responses for http requests before they are handed over to the application code that + * initiated these requests. The response interceptors leverage the {@link ng.$q + * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. + * + * The interceptors are service factories that are registered with the $httpProvider by + * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor — a function that + * takes a {@link ng.$q promise} and returns the original or a new promise. + * + * ```js + * // register the interceptor as a service + * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { + * return function(promise) { + * return promise.then(function(response) { + * // do something on success + * return response; + * }, function(response) { + * // do something on error + * if (canRecover(response)) { + * return responseOrNewPromise + * } + * return $q.reject(response); + * }); + * } + * }); + * + * $httpProvider.responseInterceptors.push('myHttpInterceptor'); + * + * + * // register the interceptor via an anonymous factory + * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { + * return function(promise) { + * // same as above + * } + * }); + * ``` + * + * + * # Security Considerations + * + * When designing web applications, consider security threats from: + * + * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) + * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) + * + * Both server and the client must cooperate in order to eliminate these threats. Angular comes + * pre-configured with strategies that address these issues, but for this to work backend server + * cooperation is required. + * + * ## JSON Vulnerability Protection + * + * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) + * allows third party website to turn your JSON resource URL into + * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To + * counter this your server can prefix all JSON requests with following string `")]}',\n"`. + * Angular will automatically strip the prefix before processing it as JSON. + * + * For example if your server needs to return: + * ```js + * ['one','two'] + * ``` + * + * which is vulnerable to attack, your server can return: + * ```js + * )]}', + * ['one','two'] + * ``` + * + * Angular will strip the prefix, before processing the JSON. + * + * + * ## Cross Site Request Forgery (XSRF) Protection + * + * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which + * an unauthorized site can gain your user's private data. Angular provides a mechanism + * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie + * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only + * JavaScript that runs on your domain could read the cookie, your server can be assured that + * the XHR came from JavaScript running on your domain. The header will not be set for + * cross-domain requests. + * + * To take advantage of this, your server needs to set a token in a JavaScript readable session + * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the + * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure + * that only JavaScript running on your domain could have sent the request. The token must be + * unique for each user and must be verifiable by the server (to prevent the JavaScript from + * making up its own tokens). We recommend that the token is a digest of your site's + * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) + * for added security. + * + * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName + * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, + * or the per-request config object. + * + * + * @param {object} config Object describing the request to be made and how it should be + * processed. The object has following properties: + * + * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) + * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. + * - **params** – `{Object.}` – Map of strings or objects which will be turned + * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be + * JSONified. + * - **data** – `{string|Object}` – Data to be sent as the request message data. + * - **headers** – `{Object}` – Map of strings or functions which return strings representing + * HTTP headers to send to the server. If the return value of a function is null, the + * header will not be sent. + * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. + * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. + * - **transformRequest** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * - **transformResponse** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} + * that should abort the request when resolved. + * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) + * for more information. + * - **responseType** - `{string}` - see + * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * + * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the + * standard `then` method and two http specific methods: `success` and `error`. The `then` + * method takes two arguments a success and an error callback which will be called with a + * response object. The `success` and `error` methods take a single argument - a function that + * will be called when the request succeeds or fails respectively. The arguments passed into + * these functions are destructured representation of the response object passed into the + * `then` method. The response object has these properties: + * + * - **data** – `{string|Object}` – The response body transformed with the transform + * functions. + * - **status** – `{number}` – HTTP status code of the response. + * - **headers** – `{function([headerName])}` – Header getter function. + * - **config** – `{Object}` – The configuration object that was used to generate the request. + * - **statusText** – `{string}` – HTTP status text of the response. + * + * @property {Array.} pendingRequests Array of config objects for currently pending + * requests. This is primarily meant to be used for debugging purposes. + * + * + * @example + + +
    + + +
    + + + +
    http status code: {{status}}
    +
    http response data: {{data}}
    +
    +
    + + angular.module('httpExample', []) + .controller('FetchController', ['$scope', '$http', '$templateCache', + function($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; + + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; + + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + success(function(data, status) { + $scope.status = status; + $scope.data = data; + }). + error(function(data, status) { + $scope.data = data || "Request failed"; + $scope.status = status; + }); + }; + + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + }]); + + + Hello, $http! + + + var status = element(by.binding('status')); + var data = element(by.binding('data')); + var fetchBtn = element(by.id('fetchbtn')); + var sampleGetBtn = element(by.id('samplegetbtn')); + var sampleJsonpBtn = element(by.id('samplejsonpbtn')); + var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); + + it('should make an xhr GET request', function() { + sampleGetBtn.click(); + fetchBtn.click(); + expect(status.getText()).toMatch('200'); + expect(data.getText()).toMatch(/Hello, \$http!/); + }); + + it('should make a JSONP request to angularjs.org', function() { + sampleJsonpBtn.click(); + fetchBtn.click(); + expect(status.getText()).toMatch('200'); + expect(data.getText()).toMatch(/Super Hero!/); + }); + + it('should make JSONP request to invalid URL and invoke the error handler', + function() { + invalidJsonpBtn.click(); + fetchBtn.click(); + expect(status.getText()).toMatch('0'); + expect(data.getText()).toMatch('Request failed'); + }); + +
    + */ + function $http(requestConfig) { + var config = { + method: 'get', + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse + }; + var headers = mergeHeaders(requestConfig); + + extend(config, requestConfig); + config.headers = headers; + config.method = uppercase(config.method); + + var serverRequest = function(config) { + headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); + + // strip content-type if data is undefined + if (isUndefined(reqData)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; + } + }); + } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData, headers).then(transformResponse, transformResponse); + }; + + var chain = [serverRequest, undefined]; + var promise = $q.when(config); + + // apply interceptors + forEach(reversedInterceptors, function(interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift(interceptor.request, interceptor.requestError); + } + if (interceptor.response || interceptor.responseError) { + chain.push(interceptor.response, interceptor.responseError); + } + }); + + while(chain.length) { + var thenFn = chain.shift(); + var rejectFn = chain.shift(); + + promise = promise.then(thenFn, rejectFn); + } + + promise.success = function(fn) { + promise.then(function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + promise.error = function(fn) { + promise.then(null, function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + return promise; + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response, { + data: transformData(response.data, response.headers, config.transformResponse) + }); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); + } + + function mergeHeaders(config) { + var defHeaders = defaults.headers, + reqHeaders = extend({}, config.headers), + defHeaderName, lowercaseDefHeaderName, reqHeaderName; + + defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); + + // using for-in instead of forEach to avoid unecessary iteration after header has been found + defaultHeadersIteration: + for (defHeaderName in defHeaders) { + lowercaseDefHeaderName = lowercase(defHeaderName); + + for (reqHeaderName in reqHeaders) { + if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { + continue defaultHeadersIteration; + } + } + + reqHeaders[defHeaderName] = defHeaders[defHeaderName]; + } + + // execute if header value is a function for merged headers + execHeaders(reqHeaders); + return reqHeaders; + + function execHeaders(headers) { + var headerContent; + + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(); + if (headerContent != null) { + headers[header] = headerContent; + } else { + delete headers[header]; + } + } + }); + } + } + } + + $http.pendingRequests = []; + + /** + * @ngdoc method + * @name $http#get + * + * @description + * Shortcut method to perform `GET` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#delete + * + * @description + * Shortcut method to perform `DELETE` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#head + * + * @description + * Shortcut method to perform `HEAD` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#jsonp + * + * @description + * Shortcut method to perform `JSONP` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request. + * The name of the callback should be the string `JSON_CALLBACK`. + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethods('get', 'delete', 'head', 'jsonp'); + + /** + * @ngdoc method + * @name $http#post + * + * @description + * Shortcut method to perform `POST` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#put + * + * @description + * Shortcut method to perform `PUT` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethodsWithData('post', 'put'); + + /** + * @ngdoc property + * @name $http#defaults + * + * @description + * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of + * default headers, withCredentials as well as request and response transformations. + * + * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. + */ + $http.defaults = defaults; + + + return $http; + + + function createShortMethods(names) { + forEach(arguments, function(name) { + $http[name] = function(url, config) { + return $http(extend(config || {}, { + method: name, + url: url + })); + }; + }); + } + + + function createShortMethodsWithData(name) { + forEach(arguments, function(name) { + $http[name] = function(url, data, config) { + return $http(extend(config || {}, { + method: name, + url: url, + data: data + })); + }; + }); + } + + + /** + * Makes the request. + * + * !!! ACCESSES CLOSURE VARS: + * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests + */ + function sendReq(config, reqData, reqHeaders) { + var deferred = $q.defer(), + promise = deferred.promise, + cache, + cachedResp, + url = buildUrl(config.url, config.params); + + $http.pendingRequests.push(config); + promise.then(removePendingReq, removePendingReq); + + + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { + cache = isObject(config.cache) ? config.cache + : isObject(defaults.cache) ? defaults.cache + : defaultCache; + } + + if (cache) { + cachedResp = cache.get(url); + if (isDefined(cachedResp)) { + if (isPromiseLike(cachedResp)) { + // cached request has already been sent, but there is no response yet + cachedResp.then(removePendingReq, removePendingReq); + return cachedResp; + } else { + // serving from cache + if (isArray(cachedResp)) { + resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); + } else { + resolvePromise(cachedResp, 200, {}, 'OK'); + } + } + } else { + // put the promise for the non-transformed response into cache as a placeholder + cache.put(url, promise); + } + } + + + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend + if (isUndefined(cachedResp)) { + var xsrfValue = urlIsSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, + config.withCredentials, config.responseType); + } + + return promise; + + + /** + * Callback registered to $httpBackend(): + * - caches the response if desired + * - resolves the raw $http promise + * - calls $apply + */ + function done(status, response, headersString, statusText) { + if (cache) { + if (isSuccess(status)) { + cache.put(url, [status, response, parseHeaders(headersString), statusText]); + } else { + // remove promise from the cache + cache.remove(url); + } + } + + resolvePromise(response, status, headersString, statusText); + if (!$rootScope.$$phase) $rootScope.$apply(); + } + + + /** + * Resolves the raw $http promise. + */ + function resolvePromise(response, status, headers, statusText) { + // normalize internal statuses to 0 + status = Math.max(status, 0); + + (isSuccess(status) ? deferred.resolve : deferred.reject)({ + data: response, + status: status, + headers: headersGetter(headers), + config: config, + statusText : statusText + }); + } + + + function removePendingReq() { + var idx = indexOf($http.pendingRequests, config); + if (idx !== -1) $http.pendingRequests.splice(idx, 1); + } + } + + + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || isUndefined(value)) return; + if (!isArray(value)) value = [value]; + + forEach(value, function(v) { + if (isObject(v)) { + if (isDate(v)){ + v = v.toISOString(); + } else if (isObject(v)) { + v = toJson(v); + } + } + parts.push(encodeUriQuery(key) + '=' + + encodeUriQuery(v)); + }); + }); + if(parts.length > 0) { + url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } + return url; + } + }]; +} + +function createXhr(method) { + //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest + //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest + //if it is available + if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) || + !window.XMLHttpRequest)) { + return new window.ActiveXObject("Microsoft.XMLHTTP"); + } else if (window.XMLHttpRequest) { + return new window.XMLHttpRequest(); + } + + throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); +} + +/** + * @ngdoc service + * @name $httpBackend + * @requires $window + * @requires $document + * + * @description + * HTTP backend used by the {@link ng.$http service} that delegates to + * XMLHttpRequest object or JSONP and deals with browser incompatibilities. + * + * You should never need to use this service directly, instead use the higher-level abstractions: + * {@link ng.$http $http} or {@link ngResource.$resource $resource}. + * + * During testing this implementation is swapped with {@link ngMock.$httpBackend mock + * $httpBackend} which can be trained with responses. + */ +function $HttpBackendProvider() { + this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { + return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); + }]; +} + +function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { + var ABORTED = -1; + + // TODO(vojta): fix the signature + return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { + var status; + $browser.$$incOutstandingRequestCount(); + url = url || $browser.url(); + + if (lowercase(method) == 'jsonp') { + var callbackId = '_' + (callbacks.counter++).toString(36); + callbacks[callbackId] = function(data) { + callbacks[callbackId].data = data; + callbacks[callbackId].called = true; + }; + + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + callbackId, function(status, text) { + completeRequest(callback, status, callbacks[callbackId].data, "", text); + callbacks[callbackId] = noop; + }); + } else { + + var xhr = createXhr(method); + + xhr.open(method, url, true); + forEach(headers, function(value, key) { + if (isDefined(value)) { + xhr.setRequestHeader(key, value); + } + }); + + // In IE6 and 7, this might be called synchronously when xhr.send below is called and the + // response is in the cache. the promise api will ensure that to the app code the api is + // always async + xhr.onreadystatechange = function() { + // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by + // xhrs that are resolved while the app is in the background (see #5426). + // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before + // continuing + // + // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and + // Safari respectively. + if (xhr && xhr.readyState == 4) { + var responseHeaders = null, + response = null, + statusText = ''; + + if(status !== ABORTED) { + responseHeaders = xhr.getAllResponseHeaders(); + + // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) + response = ('response' in xhr) ? xhr.response : xhr.responseText; + } + + // Accessing statusText on an aborted xhr object will + // throw an 'c00c023f error' in IE9 and lower, don't touch it. + if (!(status === ABORTED && msie < 10)) { + statusText = xhr.statusText; + } + + completeRequest(callback, + status || xhr.status, + response, + responseHeaders, + statusText); + } + }; + + if (withCredentials) { + xhr.withCredentials = true; + } + + if (responseType) { + try { + xhr.responseType = responseType; + } catch (e) { + // WebKit added support for the json responseType value on 09/03/2013 + // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are + // known to throw when setting the value "json" as the response type. Other older + // browsers implementing the responseType + // + // The json response type can be ignored if not supported, because JSON payloads are + // parsed on the client-side regardless. + if (responseType !== 'json') { + throw e; + } + } + } + + xhr.send(post || null); + } + + if (timeout > 0) { + var timeoutId = $browserDefer(timeoutRequest, timeout); + } else if (isPromiseLike(timeout)) { + timeout.then(timeoutRequest); + } + + + function timeoutRequest() { + status = ABORTED; + jsonpDone && jsonpDone(); + xhr && xhr.abort(); + } + + function completeRequest(callback, status, response, headersString, statusText) { + // cancel timeout and subsequent timeout promise resolution + timeoutId && $browserDefer.cancel(timeoutId); + jsonpDone = xhr = null; + + // fix status code when it is 0 (0 status is undocumented). + // Occurs when accessing file resources or on Android 4.1 stock browser + // while retrieving files from application cache. + if (status === 0) { + status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; + } + + // normalize IE bug (http://bugs.jquery.com/ticket/1450) + status = status === 1223 ? 204 : status; + statusText = statusText || ''; + + callback(status, response, headersString, statusText); + $browser.$$completeOutstandingRequest(noop); + } + }; + + function jsonpReq(url, callbackId, done) { + // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + // - fetches local scripts via XHR and evals them + // - adds and immediately removes script elements from the document + var script = rawDocument.createElement('script'), callback = null; + script.type = "text/javascript"; + script.src = url; + script.async = true; + + callback = function(event) { + removeEventListenerFn(script, "load", callback); + removeEventListenerFn(script, "error", callback); + rawDocument.body.removeChild(script); + script = null; + var status = -1; + var text = "unknown"; + + if (event) { + if (event.type === "load" && !callbacks[callbackId].called) { + event = { type: "error" }; + } + text = event.type; + status = event.type === "error" ? 404 : 200; + } + + if (done) { + done(status, text); + } + }; + + addEventListenerFn(script, "load", callback); + addEventListenerFn(script, "error", callback); + + if (msie <= 8) { + script.onreadystatechange = function() { + if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) { + script.onreadystatechange = null; + callback({ + type: 'load' + }); + } + }; + } + + rawDocument.body.appendChild(script); + return callback; + } +} + +var $interpolateMinErr = minErr('$interpolate'); + +/** + * @ngdoc provider + * @name $interpolateProvider + * @kind function + * + * @description + * + * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * + * @example + + + +
    + //demo.label// +
    +
    + + it('should interpolate binding with custom symbols', function() { + expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); + }); + +
    + */ +function $InterpolateProvider() { + var startSymbol = '{{'; + var endSymbol = '}}'; + + /** + * @ngdoc method + * @name $interpolateProvider#startSymbol + * @description + * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. + * + * @param {string=} value new value to set the starting symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.startSymbol = function(value){ + if (value) { + startSymbol = value; + return this; + } else { + return startSymbol; + } + }; + + /** + * @ngdoc method + * @name $interpolateProvider#endSymbol + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * @param {string=} value new value to set the ending symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.endSymbol = function(value){ + if (value) { + endSymbol = value; + return this; + } else { + return endSymbol; + } + }; + + + this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { + var startSymbolLength = startSymbol.length, + endSymbolLength = endSymbol.length; + + /** + * @ngdoc service + * @name $interpolate + * @kind function + * + * @requires $parse + * @requires $sce * * @description * @@ -14325,25 +18513,29 @@ function $InterpolateProvider() { * interpolation markup. * * -
    -         var $interpolate = ...; // injected
    -         var exp = $interpolate('Hello {{name}}!');
    -         expect(exp({name:'Angular'}).toEqual('Hello Angular!');
    -       
    + * ```js + * var $interpolate = ...; // injected + * var exp = $interpolate('Hello {{name | uppercase}}!'); + * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); + * ``` * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. - * @returns {function(context)} an interpolation function which is used to compute the interpolated - * string. The function has these parameters: + * @param {string=} trustedContext when provided, the returned function passes the interpolated + * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, + * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that + * provides Strict Contextual Escaping for details. + * @returns {function(context)} an interpolation function which is used to compute the + * interpolated string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ - function $interpolate(text, mustHaveExpression) { + function $interpolate(text, mustHaveExpression, trustedContext) { var startIndex, endIndex, index = 0, @@ -14375,21 +18567,60 @@ function $InterpolateProvider() { length = 1; } + // Concatenating expressions makes it hard to reason about whether some combination of + // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a + // single expression be used for iframe[src], object[src], etc., we ensure that the value + // that's used is assigned or constructed by some JS code somewhere that is more testable or + // make it obvious that you bound the value to some user controlled value. This helps reduce + // the load when auditing for XSS issues. + if (trustedContext && parts.length > 1) { + throw $interpolateMinErr('noconcat', + "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + + "interpolations that concatenate multiple expressions when a trusted value is " + + "required. See http://docs.angularjs.org/api/ng.$sce", text); + } + if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { - for(var i = 0, ii = length, part; i + * **Note**: Intervals created by this service must be explicitly destroyed when you are finished + * with them. In particular they are not automatically destroyed when a controller's scope or a + * directive's element are destroyed. + * You should take this into consideration and make sure to always cancel the interval at the + * appropriate moment. See the example below for more details on how and when to do this. + * + * + * @param {function()} fn A function that should be called repeatedly. + * @param {number} delay Number of milliseconds between each function call. + * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat + * indefinitely. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @returns {promise} A promise which will be notified on each iteration. + * + * @example + * + * + * + * + *
    + *
    + * Date format:
    + * Current time is: + *
    + * Blood 1 : {{blood_1}} + * Blood 2 : {{blood_2}} + * + * + * + *
    + *
    + * + *
    + *
    + */ + function interval(fn, delay, count, invokeApply) { + var setInterval = $window.setInterval, + clearInterval = $window.clearInterval, + deferred = $q.defer(), + promise = deferred.promise, + iteration = 0, + skipApply = (isDefined(invokeApply) && !invokeApply); + + count = isDefined(count) ? count : 0; + + promise.then(null, null, fn); + + promise.$$intervalId = setInterval(function tick() { + deferred.notify(iteration++); + + if (count > 0 && iteration >= count) { + deferred.resolve(iteration); + clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + } + + if (!skipApply) $rootScope.$apply(); + + }, delay); + + intervals[promise.$$intervalId] = deferred; + + return promise; + } + + + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {promise} promise returned by the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully canceled. + */ + interval.cancel = function(promise) { + if (promise && promise.$$intervalId in intervals) { + intervals[promise.$$intervalId].reject('canceled'); + $window.clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + return true; + } + return false; + }; + + return interval; + }]; +} + +/** + * @ngdoc service + * @name $locale + * + * @description + * $locale service provides localization rules for various Angular components. As of right now the + * only public api is: + * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + */ +function $LocaleProvider(){ + this.$get = function() { + return { + id: 'en-us', + + NUMBER_FORMATS: { + DECIMAL_SEP: '.', + GROUP_SEP: ',', + PATTERNS: [ + { // Decimal Pattern + minInt: 1, + minFrac: 0, + maxFrac: 3, + posPre: '', + posSuf: '', + negPre: '-', + negSuf: '', + gSize: 3, + lgSize: 3 + },{ //Currency Pattern + minInt: 1, + minFrac: 2, + maxFrac: 2, + posPre: '\u00A4', + posSuf: '', + negPre: '(\u00A4', + negSuf: ')', + gSize: 3, + lgSize: 3 + } + ], + CURRENCY_SYM: '$' + }, + + DATETIME_FORMATS: { + MONTH: + 'January,February,March,April,May,June,July,August,September,October,November,December' + .split(','), + SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), + AMPMS: ['AM','PM'], + medium: 'MMM d, y h:mm:ss a', + short: 'M/d/yy h:mm a', + fullDate: 'EEEE, MMMM d, y', + longDate: 'MMMM d, y', + mediumDate: 'MMM d, y', + shortDate: 'M/d/yy', + mediumTime: 'h:mm:ss a', + shortTime: 'h:mm a' + }, + + pluralCat: function(num) { + if (num === 1) { + return 'one'; + } + return 'other'; + } + }; + }; +} + +var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; +var $locationMinErr = minErr('$location'); /** @@ -14458,114 +18943,205 @@ function encodePath(path) { return segments.join('/'); } -function stripHash(url) { - return url.split('#')[0]; +function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { + var parsedUrl = urlResolve(absoluteUrl, appBase); + + locationObj.$$protocol = parsedUrl.protocol; + locationObj.$$host = parsedUrl.hostname; + locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } -function matchUrl(url, obj) { - var match = URL_MATCH.exec(url); +function parseAppUrl(relativeUrl, locationObj, appBase) { + var prefixed = (relativeUrl.charAt(0) !== '/'); + if (prefixed) { + relativeUrl = '/' + relativeUrl; + } + var match = urlResolve(relativeUrl, appBase); + locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? + match.pathname.substring(1) : match.pathname); + locationObj.$$search = parseKeyValue(match.search); + locationObj.$$hash = decodeURIComponent(match.hash); + + // make sure path starts with '/'; + if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { + locationObj.$$path = '/' + locationObj.$$path; + } +} - match = { - protocol: match[1], - host: match[3], - port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, - path: match[6] || '/', - search: match[8], - hash: match[10] - }; - if (obj) { - obj.$$protocol = match.protocol; - obj.$$host = match.host; - obj.$$port = match.port; +/** + * + * @param {string} begin + * @param {string} whole + * @returns {string} returns text from whole after begin or undefined if it does not begin with + * expected string. + */ +function beginsWith(begin, whole) { + if (whole.indexOf(begin) === 0) { + return whole.substr(begin.length); } - - return match; } -function composeProtocolHostPort(protocol, host, port) { - return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); +function stripHash(url) { + var index = url.indexOf('#'); + return index == -1 ? url : url.substr(0, index); } -function pathPrefixFromBase(basePath) { - return basePath.substr(0, basePath.lastIndexOf('/')); +function stripFile(url) { + return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } +/* return the server only (scheme://host:port) */ +function serverBase(url) { + return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); +} -function convertToHtml5Url(url, basePath, hashPrefix) { - var match = matchUrl(url); - // already html5 url - if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || - match.hash.indexOf(hashPrefix) !== 0) { - return url; - // convert hashbang url -> html5 url - } else { - return composeProtocolHostPort(match.protocol, match.host, match.port) + - pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); - } -} +/** + * LocationHtml5Url represents an url + * This object is exposed as $location service when HTML5 mode is enabled and supported + * + * @constructor + * @param {string} appBase application base URL + * @param {string} basePrefix url path prefix + */ +function LocationHtml5Url(appBase, basePrefix) { + this.$$html5 = true; + basePrefix = basePrefix || ''; + var appBaseNoFile = stripFile(appBase); + parseAbsoluteUrl(appBase, this, appBase); -function convertToHashbangUrl(url, basePath, hashPrefix) { - var match = matchUrl(url); + /** + * Parse given html5 (regular) url string into properties + * @param {string} newAbsoluteUrl HTML5 url + * @private + */ + this.$$parse = function(url) { + var pathUrl = beginsWith(appBaseNoFile, url); + if (!isString(pathUrl)) { + throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, + appBaseNoFile); + } - // already hashbang url - if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) && - match.hash.indexOf(hashPrefix) === 0) { - return url; - // convert html5 url -> hashbang url - } else { - var search = match.search && '?' + match.search || '', - hash = match.hash && '#' + match.hash || '', - pathPrefix = pathPrefixFromBase(basePath), - path = match.path.substr(pathPrefix.length); + parseAppUrl(pathUrl, this, appBase); - if (match.path.indexOf(pathPrefix) !== 0) { - throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'); + if (!this.$$path) { + this.$$path = '/'; } - return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + - '#' + hashPrefix + path + search + hash; - } + this.$$compose(); + }; + + /** + * Compose url and update `absUrl` property + * @private + */ + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; + + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' + }; + + this.$$rewrite = function(url) { + var appUrl, prevAppUrl; + + if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { + prevAppUrl = appUrl; + if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { + return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + } else { + return appBase + prevAppUrl; + } + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { + return appBaseNoFile + appUrl; + } else if (appBaseNoFile == url + '/') { + return appBaseNoFile; + } + }; } /** - * LocationUrl represents an url - * This object is exposed as $location service when HTML5 mode is enabled and supported + * LocationHashbangUrl represents url + * This object is exposed as $location service when developer doesn't opt into html5 mode. + * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor - * @param {string} url HTML5 url - * @param {string} pathPrefix + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix */ -function LocationUrl(url, pathPrefix, appBaseUrl) { - pathPrefix = pathPrefix || ''; +function LocationHashbangUrl(appBase, hashPrefix) { + var appBaseNoFile = stripFile(appBase); + + parseAbsoluteUrl(appBase, this, appBase); + /** - * Parse given html5 (regular) url string into properties - * @param {string} newAbsoluteUrl HTML5 url + * Parse given hashbang url into properties + * @param {string} url Hashbang url * @private */ - this.$$parse = function(newAbsoluteUrl) { - var match = matchUrl(newAbsoluteUrl, this); + this.$$parse = function(url) { + var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); + var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' + ? beginsWith(hashPrefix, withoutBaseUrl) + : (this.$$html5) + ? withoutBaseUrl + : ''; + + if (!isString(withoutHashUrl)) { + throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, + hashPrefix); + } + parseAppUrl(withoutHashUrl, this, appBase); + + this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); + + this.$$compose(); + + /* + * In Windows, on an anchor node on documents loaded from + * the filesystem, the browser will return a pathname + * prefixed with the drive name ('/C:/path') when a + * pathname without a drive is set: + * * a.setAttribute('href', '/foo') + * * a.pathname === '/C:/foo' //true + * + * Inside of Angular, we're always using pathnames that + * do not include drive names for routing. + */ + function removeWindowsDriveName (path, url, base) { + /* + Matches paths for file protocol on windows, + such as /C:/foo/bar, and captures only /foo/bar. + */ + var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; - if (match.path.indexOf(pathPrefix) !== 0) { - throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !'); - } + var firstPathSegmentMatch; - this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); - this.$$search = parseKeyValue(match.search); - this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; + //Get the relative path from the input URL. + if (url.indexOf(base) === 0) { + url = url.replace(base, ''); + } - this.$$compose(); + // The input URL intentionally contains a first path segment that ends with a colon. + if (windowsFilePathExp.exec(url)) { + return path; + } + + firstPathSegmentMatch = windowsFilePathExp.exec(path); + return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; + } }; /** - * Compose url and update `absUrl` property + * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { @@ -14573,85 +19149,65 @@ function LocationUrl(url, pathPrefix, appBaseUrl) { hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + - pathPrefix + this.$$url; + this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; - - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return absoluteLinkUrl; + this.$$rewrite = function(url) { + if(stripHash(appBase) == stripHash(url)) { + return url; } - } - - - this.$$parse(url); + }; } /** * LocationHashbangUrl represents url - * This object is exposed as $location service when html5 history api is disabled or not supported + * This object is exposed as $location service when html5 history api is enabled but the browser + * does not support it. * * @constructor - * @param {string} url Legacy url - * @param {string} hashPrefix Prefix for hash part (containing path and search) + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix */ -function LocationHashbangUrl(url, hashPrefix, appBaseUrl) { - var basePath; - - /** - * Parse given hashbang url into properties - * @param {string} url Hashbang url - * @private - */ - this.$$parse = function(url) { - var match = matchUrl(url, this); +function LocationHashbangInHtml5Url(appBase, hashPrefix) { + this.$$html5 = true; + LocationHashbangUrl.apply(this, arguments); + var appBaseNoFile = stripFile(appBase); - if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { - throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'); - } + this.$$rewrite = function(url) { + var appUrl; - basePath = match.path + (match.search ? '?' + match.search : ''); - match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); - if (match[1]) { - this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); - } else { - this.$$path = ''; + if ( appBase == stripHash(url) ) { + return url; + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { + return appBase + hashPrefix + appUrl; + } else if ( appBaseNoFile === url + '/') { + return appBaseNoFile; } - - this.$$search = parseKeyValue(match[3]); - this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; - - this.$$compose(); }; - /** - * Compose hashbang url and update `absUrl` property - * @private - */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + - basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); + // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' + this.$$absUrl = appBase + hashPrefix + this.$$url; }; - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return absoluteLinkUrl; - } - } - - - this.$$parse(url); } -LocationUrl.prototype = { +LocationHashbangInHtml5Url.prototype = + LocationHashbangUrl.prototype = + LocationHtml5Url.prototype = { + + /** + * Are we in html5 mode? + * @private + */ + $$html5: false, /** * Has any change been replacing ? @@ -14661,14 +19217,13 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#absUrl - * @methodOf ng.$location + * @name $location#absUrl * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in - * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. + * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). * * @return {string} full url */ @@ -14676,8 +19231,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#url - * @methodOf ng.$location + * @name $location#url * * @description * This method is getter / setter. @@ -14687,6 +19241,7 @@ LocationUrl.prototype = { * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) + * @param {string=} replace The path that will be changed * @return {string} url */ url: function(url, replace) { @@ -14703,8 +19258,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#protocol - * @methodOf ng.$location + * @name $location#protocol * * @description * This method is getter only. @@ -14717,8 +19271,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#host - * @methodOf ng.$location + * @name $location#host * * @description * This method is getter only. @@ -14731,8 +19284,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#port - * @methodOf ng.$location + * @name $location#port * * @description * This method is getter only. @@ -14745,8 +19297,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#path - * @methodOf ng.$location + * @name $location#path * * @description * This method is getter / setter. @@ -14767,8 +19318,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#search - * @methodOf ng.$location + * @name $location#search * * @description * This method is getter / setter. @@ -14777,24 +19327,66 @@ LocationUrl.prototype = { * * Change search part when called with parameter and return `$location`. * - * @param {string|object=} search New search params - string or hash object - * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a - * single search parameter. If the value is `null`, the parameter will be deleted. * - * @return {string} search + * ```js + * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * var searchObject = $location.search(); + * // => {foo: 'bar', baz: 'xoxo'} + * + * + * // set foo to 'yipee' + * $location.search('foo', 'yipee'); + * // => $location + * ``` + * + * @param {string|Object.|Object.>} search New search params - string or + * hash object. + * + * When called with a single argument the method acts as a setter, setting the `search` component + * of `$location` to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded + * as duplicate search parameters in the url. + * + * @param {(string|Array|boolean)=} paramValue If `search` is a string, then `paramValue` + * will override only a single search property. + * + * If `paramValue` is an array, it will override the property of the `search` component of + * `$location` specified via the first argument. + * + * If `paramValue` is `null`, the property specified via the first argument will be deleted. + * + * If `paramValue` is `true`, the property specified via the first argument will be added with no + * value nor trailing equal sign. + * + * @return {Object} If called with no arguments returns the parsed `search` object. If called with + * one or more arguments returns `$location` object itself. */ search: function(search, paramValue) { - if (isUndefined(search)) - return this.$$search; + switch (arguments.length) { + case 0: + return this.$$search; + case 1: + if (isString(search)) { + this.$$search = parseKeyValue(search); + } else if (isObject(search)) { + // remove object undefined or null properties + forEach(search, function(value, key) { + if (value == null) delete search[key]; + }); - if (isDefined(paramValue)) { - if (paramValue === null) { - delete this.$$search[search]; - } else { - this.$$search[search] = paramValue; - } - } else { - this.$$search = isString(search) ? parseKeyValue(search) : search; + this.$$search = search; + } else { + throw $locationMinErr('isrcharg', + 'The first argument of the `$location#search()` call must be a string or an object.'); + } + break; + default: + if (isUndefined(paramValue) || paramValue === null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } } this.$$compose(); @@ -14803,8 +19395,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#hash - * @methodOf ng.$location + * @name $location#hash * * @description * This method is getter / setter. @@ -14820,8 +19411,7 @@ LocationUrl.prototype = { /** * @ngdoc method - * @name ng.$location#replace - * @methodOf ng.$location + * @name $location#replace * * @description * If called, all changes to $location during current `$digest` will be replacing current history @@ -14833,21 +19423,6 @@ LocationUrl.prototype = { } }; -LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); - -function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) { - LocationHashbangUrl.apply(this, arguments); - - - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length); - } - } -} - -LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype); - function locationGetter(property) { return function() { return this[property]; @@ -14869,16 +19444,14 @@ function locationGetterSetter(property, preprocess) { /** - * @ngdoc object - * @name ng.$location + * @ngdoc service + * @name $location * - * @requires $browser - * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the - * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL + * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * @@ -14893,13 +19466,12 @@ function locationGetterSetter(property, preprocess) { * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * - * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular - * Services: Using $location} + * For more information see {@link guide/$location Developer Guide: Using $location} */ /** - * @ngdoc object - * @name ng.$locationProvider + * @ngdoc provider + * @name $locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ @@ -14908,9 +19480,8 @@ function $LocationProvider(){ html5Mode = false; /** - * @ngdoc property - * @name ng.$locationProvider#hashPrefix - * @methodOf ng.$locationProvider + * @ngdoc method + * @name $locationProvider#hashPrefix * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter @@ -14925,11 +19496,10 @@ function $LocationProvider(){ }; /** - * @ngdoc property - * @name ng.$locationProvider#html5Mode - * @methodOf ng.$locationProvider + * @ngdoc method + * @name $locationProvider#html5Mode * @description - * @param {string=} mode Use HTML5 strategy if available. + * @param {boolean=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { @@ -14941,42 +19511,54 @@ function $LocationProvider(){ } }; + /** + * @ngdoc event + * @name $location#$locationChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a URL will change. This change can be prevented by calling + * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more + * details about event object. Upon successful change + * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + */ + + /** + * @ngdoc event + * @name $location#$locationChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a URL was changed. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + */ + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, - basePath, - pathPrefix, - initUrl = $browser.url(), - initUrlParts = matchUrl(initUrl), - appBaseUrl; + LocationMode, + baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' + initialUrl = $browser.url(), + appBase; if (html5Mode) { - basePath = $browser.baseHref() || '/'; - pathPrefix = pathPrefixFromBase(basePath); - appBaseUrl = - composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + - pathPrefix + '/'; - - if ($sniffer.history) { - $location = new LocationUrl( - convertToHtml5Url(initUrl, basePath, hashPrefix), - pathPrefix, appBaseUrl); - } else { - $location = new LocationHashbangInHtml5Url( - convertToHashbangUrl(initUrl, basePath, hashPrefix), - hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1)); - } + appBase = serverBase(initialUrl) + (baseHref || '/'); + LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { - appBaseUrl = - composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + - (initUrlParts.path || '') + - (initUrlParts.search ? ('?' + initUrlParts.search) : '') + - '#' + hashPrefix + '/'; - - $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl); + appBase = stripHash(initialUrl); + LocationMode = LocationHashbangUrl; } + $location = new LocationMode(appBase, '#' + hashPrefix); + $location.$$parse($location.$$rewrite(initialUrl)); - $rootElement.bind('click', function(event) { + var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + + $rootElement.on('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then @@ -14990,37 +19572,84 @@ function $LocationProvider(){ if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } - var absHref = elm.prop('href'), - rewrittenUrl = $location.$$rewriteAppUrl(absHref); + var absHref = elm.prop('href'); + + if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { + // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during + // an animation. + absHref = urlResolve(absHref.animVal).href; + } + + // Ignore when url is started with javascript: or mailto: + if (IGNORE_URI_REGEXP.test(absHref)) return; + + // Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9) + // The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or + // somewhere#anchor or http://example.com/somewhere + if (LocationMode === LocationHashbangInHtml5Url) { + // get the actual href attribute - see + // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx + var href = elm.attr('href') || elm.attr('xlink:href'); + + if (href.indexOf('://') < 0) { // Ignore absolute URLs + var prefix = '#' + hashPrefix; + if (href[0] == '/') { + // absolute path - replace old path + absHref = appBase + prefix + href; + } else if (href[0] == '#') { + // local anchor + absHref = appBase + prefix + ($location.path() || '/') + href; + } else { + // relative path - join with current path + var stack = $location.path().split("/"), + parts = href.split("/"); + for (var i=0; i html5 url - if ($location.absUrl() != initUrl) { + if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { - if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { - $browser.url($location.absUrl()); - return; - } $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); - afterLocationChange(oldUrl); + if ($rootScope.$broadcast('$locationChangeStart', newUrl, + oldUrl).defaultPrevented) { + $location.$$parse(oldUrl); + $browser.url(oldUrl); + } else { + afterLocationChange(oldUrl); + } }); if (!$rootScope.$$phase) $rootScope.$digest(); } @@ -15058,26 +19687,30 @@ function $LocationProvider(){ } /** - * @ngdoc object - * @name ng.$log + * @ngdoc service + * @name $log * @requires $window * * @description - * Simple service for logging. Default implementation writes the message + * Simple service for logging. Default implementation safely writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * + * The default is to log `debug` messages. You can use + * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. + * * @example - + - function LogCtrl($scope, $log) { - $scope.$log = $log; - $scope.message = 'Hello World!'; - } + angular.module('logExample', []) + .controller('LogController', ['$scope', '$log', function($scope, $log) { + $scope.$log = $log; + $scope.message = 'Hello World!'; + }]); -
    +

    Reload this page with open console, enter text and hit the log button...

    Message: @@ -15090,13 +19723,37 @@ function $LocationProvider(){ */ +/** + * @ngdoc provider + * @name $logProvider + * @description + * Use the `$logProvider` to configure how the application logs messages + */ function $LogProvider(){ + var debug = true, + self = this; + + /** + * @ngdoc method + * @name $logProvider#debugEnabled + * @description + * @param {boolean=} flag enable or disable debug level messages + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.debugEnabled = function(flag) { + if (isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; + this.$get = ['$window', function($window){ return { /** * @ngdoc method - * @name ng.$log#log - * @methodOf ng.$log + * @name $log#log * * @description * Write a log message @@ -15105,8 +19762,16 @@ function $LogProvider(){ /** * @ngdoc method - * @name ng.$log#warn - * @methodOf ng.$log + * @name $log#info + * + * @description + * Write an information message + */ + info: consoleLog('info'), + + /** + * @ngdoc method + * @name $log#warn * * @description * Write a warning message @@ -15115,23 +19780,29 @@ function $LogProvider(){ /** * @ngdoc method - * @name ng.$log#info - * @methodOf ng.$log + * @name $log#error * * @description - * Write an information message + * Write an error message */ - info: consoleLog('info'), + error: consoleLog('error'), /** * @ngdoc method - * @name ng.$log#error - * @methodOf ng.$log + * @name $log#debug * * @description - * Write an error message + * Write a debug message */ - error: consoleLog('error') + debug: (function () { + var fn = consoleLog('debug'); + + return function() { + if (debug) { + fn.apply(self, arguments); + } + }; + }()) }; function formatError(arg) { @@ -15149,9 +19820,16 @@ function $LogProvider(){ function consoleLog(type) { var console = $window.console || {}, - logFn = console[type] || console.log || noop; + logFn = console[type] || console.log || noop, + hasApply = false; - if (logFn.apply) { + // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. + // The reason behind this is that console.log has type "object" in IE8... + try { + hasApply = !!logFn.apply; + } catch (e) {} + + if (hasApply) { return function() { var args = []; forEach(arguments, function(arg) { @@ -15164,13 +19842,96 @@ function $LogProvider(){ // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { - logFn(arg1, arg2); - } + logFn(arg1, arg2 == null ? '' : arg2); + }; } }]; } +var $parseMinErr = minErr('$parse'); +var promiseWarningCache = {}; +var promiseWarning; + +// Sandboxing Angular Expressions +// ------------------------------ +// Angular expressions are generally considered safe because these expressions only have direct +// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by +// obtaining a reference to native JS functions such as the Function constructor. +// +// As an example, consider the following Angular expression: +// +// {}.toString.constructor('alert("evil JS code")') +// +// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits +// against the expression language, but not to prevent exploits that were enabled by exposing +// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good +// practice and therefore we are not even trying to protect against interaction with an object +// explicitly exposed in this way. +// +// In general, it is not possible to access a Window object from an angular expression unless a +// window or some DOM object that has a reference to window is published onto a Scope. +// Similarly we prevent invocations of function known to be dangerous, as well as assignments to +// native objects. + + +function ensureSafeMemberName(name, fullExpression) { + if (name === "__defineGetter__" || name === "__defineSetter__" + || name === "__lookupGetter__" || name === "__lookupSetter__" + || name === "__proto__") { + throw $parseMinErr('isecfld', + 'Attempting to access a disallowed field in Angular expressions! ' + +'Expression: {0}', fullExpression); + } + return name; +} + +function ensureSafeObject(obj, fullExpression) { + // nifty check if obj is Function that is fast and works across iframes and other contexts + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isWindow(obj) + obj.document && obj.location && obj.alert && obj.setInterval) { + throw $parseMinErr('isecwindow', + 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isElement(obj) + obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { + throw $parseMinErr('isecdom', + 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// block Object so that we can't get hold of dangerous Object.* methods + obj === Object) { + throw $parseMinErr('isecobj', + 'Referencing Object in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } + return obj; +} + +var CALL = Function.prototype.call; +var APPLY = Function.prototype.apply; +var BIND = Function.prototype.bind; + +function ensureSafeFunction(obj, fullExpression) { + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) { + throw $parseMinErr('isecff', + 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } +} + var OPERATORS = { + /* jshint bitwise : false */ 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, @@ -15184,12 +19945,17 @@ var OPERATORS = { return a; } return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, + '-':function(self, locals, a,b){ + a=a(self, locals); b=b(self, locals); + return (isDefined(a)?a:0)-(isDefined(b)?b:0); + }, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, + '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, + '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals) 0) { - var token = tokens[0]; + peek: function(e1, e2, e3, e4) { + if (this.tokens.length > 0) { + var token = this.tokens[0]; var t = token.text; - if (t==e1 || t==e2 || t==e3 || t==e4 || + if (t === e1 || t === e2 || t === e3 || t === e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; - } + }, - function expect(e1, e2, e3, e4){ - var token = peek(e1, e2, e3, e4); + expect: function(e1, e2, e3, e4){ + var token = this.peek(e1, e2, e3, e4); if (token) { - if (json && !token.json) { - throwError("is not valid json", token); - } - tokens.shift(); + this.tokens.shift(); return token; } return false; - } + }, - function consume(e1){ - if (!expect(e1)) { - throwError("is unexpected, expecting [" + e1 + "]", peek()); + consume: function(e1){ + if (!this.expect(e1)) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); } - } + }, - function unaryFn(fn, right) { - return function(self, locals) { + unaryFn: function(fn, right) { + return extend(function(self, locals) { return fn(self, locals, right); - }; - } + }, { + constant:right.constant + }); + }, + + ternaryFn: function(left, middle, right){ + return extend(function(self, locals){ + return left(self, locals) ? middle(self, locals) : right(self, locals); + }, { + constant: left.constant && middle.constant && right.constant + }); + }, - function binaryFn(left, fn, right) { - return function(self, locals) { + binaryFn: function(left, fn, right) { + return extend(function(self, locals) { return fn(self, locals, left, right); - }; - } + }, { + constant:left.constant && right.constant + }); + }, - function statements() { + statements: function() { var statements = []; - while(true) { - if (tokens.length > 0 && !peek('}', ')', ';', ']')) - statements.push(filterChain()); - if (!expect(';')) { + while (true) { + if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) + statements.push(this.filterChain()); + if (!this.expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? - return statements.length == 1 - ? statements[0] - : function(self, locals){ - var value; - for ( var i = 0; i < statements.length; i++) { - var statement = statements[i]; - if (statement) - value = statement(self, locals); - } - return value; - }; + return (statements.length === 1) + ? statements[0] + : function(self, locals) { + var value; + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (statement) { + value = statement(self, locals); + } + } + return value; + }; } } - } + }, - function _filterChain() { - var left = expression(); + filterChain: function() { + var left = this.expression(); var token; - while(true) { - if ((token = expect('|'))) { - left = binaryFn(left, token.fn, filter()); + while (true) { + if ((token = this.expect('|'))) { + left = this.binaryFn(left, token.fn, this.filter()); } else { return left; } } - } + }, - function filter() { - var token = expect(); - var fn = $filter(token.text); + filter: function() { + var token = this.expect(); + var fn = this.$filter(token.text); var argsFn = []; - while(true) { - if ((token = expect(':'))) { - argsFn.push(expression()); + while (true) { + if ((token = this.expect(':'))) { + argsFn.push(this.expression()); } else { - var fnInvoke = function(self, locals, input){ + var fnInvoke = function(self, locals, input) { var args = [input]; - for ( var i = 0; i < argsFn.length; i++) { + for (var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); @@ -15578,286 +20426,299 @@ function parser(text, json, $filter, csp){ }; } } - } + }, - function expression() { - return assignment(); - } + expression: function() { + return this.assignment(); + }, - function _assignment() { - var left = logicalOR(); + assignment: function() { + var left = this.ternary(); var right; var token; - if ((token = expect('='))) { + if ((token = this.expect('='))) { if (!left.assign) { - throwError("implies assignment but [" + - text.substring(0, token.index) + "] can not be assigned to", token); + this.throwError('implies assignment but [' + + this.text.substring(0, token.index) + '] can not be assigned to', token); } - right = logicalOR(); - return function(scope, locals){ + right = this.ternary(); + return function(scope, locals) { return left.assign(scope, right(scope, locals), locals); }; + } + return left; + }, + + ternary: function() { + var left = this.logicalOR(); + var middle; + var token; + if ((token = this.expect('?'))) { + middle = this.assignment(); + if ((token = this.expect(':'))) { + return this.ternaryFn(left, middle, this.assignment()); + } else { + this.throwError('expected :', token); + } } else { return left; } - } + }, - function logicalOR() { - var left = logicalAND(); + logicalOR: function() { + var left = this.logicalAND(); var token; - while(true) { - if ((token = expect('||'))) { - left = binaryFn(left, token.fn, logicalAND()); + while (true) { + if ((token = this.expect('||'))) { + left = this.binaryFn(left, token.fn, this.logicalAND()); } else { return left; } } - } + }, - function logicalAND() { - var left = equality(); + logicalAND: function() { + var left = this.equality(); var token; - if ((token = expect('&&'))) { - left = binaryFn(left, token.fn, logicalAND()); + if ((token = this.expect('&&'))) { + left = this.binaryFn(left, token.fn, this.logicalAND()); } return left; - } + }, - function equality() { - var left = relational(); + equality: function() { + var left = this.relational(); var token; - if ((token = expect('==','!='))) { - left = binaryFn(left, token.fn, equality()); + if ((token = this.expect('==','!=','===','!=='))) { + left = this.binaryFn(left, token.fn, this.equality()); } return left; - } + }, - function relational() { - var left = additive(); + relational: function() { + var left = this.additive(); var token; - if ((token = expect('<', '>', '<=', '>='))) { - left = binaryFn(left, token.fn, relational()); + if ((token = this.expect('<', '>', '<=', '>='))) { + left = this.binaryFn(left, token.fn, this.relational()); } return left; - } + }, - function additive() { - var left = multiplicative(); + additive: function() { + var left = this.multiplicative(); var token; - while ((token = expect('+','-'))) { - left = binaryFn(left, token.fn, multiplicative()); + while ((token = this.expect('+','-'))) { + left = this.binaryFn(left, token.fn, this.multiplicative()); } return left; - } + }, - function multiplicative() { - var left = unary(); + multiplicative: function() { + var left = this.unary(); var token; - while ((token = expect('*','/','%'))) { - left = binaryFn(left, token.fn, unary()); + while ((token = this.expect('*','/','%'))) { + left = this.binaryFn(left, token.fn, this.unary()); } return left; - } + }, - function unary() { + unary: function() { var token; - if (expect('+')) { - return primary(); - } else if ((token = expect('-'))) { - return binaryFn(ZERO, token.fn, unary()); - } else if ((token = expect('!'))) { - return unaryFn(token.fn, unary()); - } else { - return primary(); - } - } - - - function primary() { - var primary; - if (expect('(')) { - primary = filterChain(); - consume(')'); - } else if (expect('[')) { - primary = arrayDeclaration(); - } else if (expect('{')) { - primary = object(); + if (this.expect('+')) { + return this.primary(); + } else if ((token = this.expect('-'))) { + return this.binaryFn(Parser.ZERO, token.fn, this.unary()); + } else if ((token = this.expect('!'))) { + return this.unaryFn(token.fn, this.unary()); } else { - var token = expect(); - primary = token.fn; - if (!primary) { - throwError("not a primary expression", token); - } + return this.primary(); } + }, - var next, context; - while ((next = expect('(', '[', '.'))) { - if (next.text === '(') { - primary = functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = fieldAccess(primary); - } else { - throwError("IMPOSSIBLE"); + fieldAccess: function(object) { + var parser = this; + var field = this.expect().text; + var getter = getterFn(field, this.options, this.text); + + return extend(function(scope, locals, self) { + return getter(self || object(scope, locals)); + }, { + assign: function(scope, value, locals) { + var o = object(scope, locals); + if (!o) object.assign(scope, o = {}); + return setter(o, field, value, parser.text, parser.options); } - } - return primary; - } - - function _fieldAccess(object) { - var field = expect().text; - var getter = getterFn(field, csp); - return extend( - function(scope, locals, self) { - return getter(self || object(scope, locals), locals); - }, - { - assign:function(scope, value, locals) { - return setter(object(scope, locals), field, value); - } - } - ); - } + }); + }, - function _objectIndex(obj) { - var indexFn = expression(); - consume(']'); - return extend( - function(self, locals){ - var o = obj(self, locals), - i = indexFn(self, locals), - v, p; - - if (!o) return undefined; - v = o[i]; - if (v && v.then) { - p = v; - if (!('$$v' in v)) { - p.$$v = undefined; - p.then(function(val) { p.$$v = val; }); - } - v = v.$$v; - } - return v; - }, { - assign:function(self, value, locals){ - return obj(self, locals)[indexFn(self, locals)] = value; + objectIndex: function(obj) { + var parser = this; + + var indexFn = this.expression(); + this.consume(']'); + + return extend(function(self, locals) { + var o = obj(self, locals), + i = indexFn(self, locals), + v, p; + + ensureSafeMemberName(i, parser.text); + if (!o) return undefined; + v = ensureSafeObject(o[i], parser.text); + if (v && v.then && parser.options.unwrapPromises) { + p = v; + if (!('$$v' in v)) { + p.$$v = undefined; + p.then(function(val) { p.$$v = val; }); } - }); - } + v = v.$$v; + } + return v; + }, { + assign: function(self, value, locals) { + var key = ensureSafeMemberName(indexFn(self, locals), parser.text); + // prevent overwriting of Function.constructor which would break ensureSafeObject check + var o = ensureSafeObject(obj(self, locals), parser.text); + if (!o) obj.assign(self, o = {}); + return o[key] = value; + } + }); + }, - function _functionCall(fn, contextGetter) { + functionCall: function(fn, contextGetter) { var argsFn = []; - if (peekToken().text != ')') { + if (this.peekToken().text !== ')') { do { - argsFn.push(expression()); - } while (expect(',')); + argsFn.push(this.expression()); + } while (this.expect(',')); } - consume(')'); - return function(scope, locals){ - var args = [], - context = contextGetter ? contextGetter(scope, locals) : scope; + this.consume(')'); + + var parser = this; + + return function(scope, locals) { + var args = []; + var context = contextGetter ? contextGetter(scope, locals) : scope; - for ( var i = 0; i < argsFn.length; i++) { + for (var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](scope, locals)); } var fnPtr = fn(scope, locals, context) || noop; - // IE stupidity! - return fnPtr.apply - ? fnPtr.apply(context, args) - : fnPtr(args[0], args[1], args[2], args[3], args[4]); + + ensureSafeObject(context, parser.text); + ensureSafeFunction(fnPtr, parser.text); + + // IE stupidity! (IE doesn't have apply for some native functions) + var v = fnPtr.apply + ? fnPtr.apply(context, args) + : fnPtr(args[0], args[1], args[2], args[3], args[4]); + + return ensureSafeObject(v, parser.text); }; - } + }, // This is used with json array declaration - function arrayDeclaration () { + arrayDeclaration: function () { var elementFns = []; - if (peekToken().text != ']') { + var allConstant = true; + if (this.peekToken().text !== ']') { do { - elementFns.push(expression()); - } while (expect(',')); + if (this.peek(']')) { + // Support trailing commas per ES5.1. + break; + } + var elementFn = this.expression(); + elementFns.push(elementFn); + if (!elementFn.constant) { + allConstant = false; + } + } while (this.expect(',')); } - consume(']'); - return function(self, locals){ + this.consume(']'); + + return extend(function(self, locals) { var array = []; - for ( var i = 0; i < elementFns.length; i++) { + for (var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; - }; - } + }, { + literal: true, + constant: allConstant + }); + }, - function object () { + object: function () { var keyValues = []; - if (peekToken().text != '}') { + var allConstant = true; + if (this.peekToken().text !== '}') { do { - var token = expect(), + if (this.peek('}')) { + // Support trailing commas per ES5.1. + break; + } + var token = this.expect(), key = token.string || token.text; - consume(":"); - var value = expression(); - keyValues.push({key:key, value:value}); - } while (expect(',')); + this.consume(':'); + var value = this.expression(); + keyValues.push({key: key, value: value}); + if (!value.constant) { + allConstant = false; + } + } while (this.expect(',')); } - consume('}'); - return function(self, locals){ + this.consume('}'); + + return extend(function(self, locals) { var object = {}; - for ( var i = 0; i < keyValues.length; i++) { + for (var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; object[keyValue.key] = keyValue.value(self, locals); } return object; - }; + }, { + literal: true, + constant: allConstant + }); } -} +}; + ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// -function setter(obj, path, setValue) { - var element = path.split('.'); +function setter(obj, path, setValue, fullExp, options) { + //needed? + options = options || {}; + + var element = path.split('.'), key; for (var i = 0; element.length > 1; i++) { - var key = element.shift(); + key = ensureSafeMemberName(element.shift(), fullExp); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; - } - obj[element.shift()] = setValue; - return setValue; -} - -/** - * Return the value accesible from the object by path. Any undefined traversals are ignored - * @param {Object} obj starting object - * @param {string} path path to traverse - * @param {boolean=true} bindFnToScope - * @returns value as accesbile by path - */ -//TODO(misko): this function needs to be removed -function getter(obj, path, bindFnToScope) { - if (!path) return obj; - var keys = path.split('.'); - var key; - var lastInstance = obj; - var len = keys.length; - - for (var i = 0; i < len; i++) { - key = keys[i]; - if (obj) { - obj = (lastInstance = obj)[key]; + if (obj.then && options.unwrapPromises) { + promiseWarning(fullExp); + if (!("$$v" in obj)) { + (function(promise) { + promise.then(function(val) { promise.$$v = val; }); } + )(obj); + } + if (obj.$$v === undefined) { + obj.$$v = {}; + } + obj = obj.$$v; } } - if (!bindFnToScope && isFunction(obj)) { - return bind(lastInstance, obj); - } - return obj; + key = ensureSafeMemberName(element.shift(), fullExp); + ensureSafeObject(obj, fullExp); + ensureSafeObject(obj[key], fullExp); + obj[key] = setValue; + return setValue; } var getterFnCache = {}; @@ -15867,71 +20728,114 @@ var getterFnCache = {}; * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ -function cspSafeGetterFn(key0, key1, key2, key3, key4) { - return function(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, - promise; +function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { + ensureSafeMemberName(key0, fullExp); + ensureSafeMemberName(key1, fullExp); + ensureSafeMemberName(key2, fullExp); + ensureSafeMemberName(key3, fullExp); + ensureSafeMemberName(key4, fullExp); - if (pathVal === null || pathVal === undefined) return pathVal; + return !options.unwrapPromises + ? function cspSafeGetter(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; - pathVal = pathVal[key0]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key1 || pathVal === null || pathVal === undefined) return pathVal; + if (pathVal == null) return pathVal; + pathVal = pathVal[key0]; - pathVal = pathVal[key1]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key2 || pathVal === null || pathVal === undefined) return pathVal; + if (!key1) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key1]; - pathVal = pathVal[key2]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key3 || pathVal === null || pathVal === undefined) return pathVal; + if (!key2) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key2]; - pathVal = pathVal[key3]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key4 || pathVal === null || pathVal === undefined) return pathVal; + if (!key3) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key3]; - pathVal = pathVal[key4]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - return pathVal; - }; + if (!key4) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key4]; + + return pathVal; + } + : function cspSafePromiseEnabledGetter(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, + promise; + + if (pathVal == null) return pathVal; + + pathVal = pathVal[key0]; + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + + if (!key1) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key1]; + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + + if (!key2) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key2]; + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + + if (!key3) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key3]; + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + + if (!key4) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key4]; + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + return pathVal; + }; } -function getterFn(path, csp) { +function getterFn(path, options, fullExp) { + // Check whether the cache has this getter already. + // We can use hasOwnProperty directly on the cache because we ensure, + // see below, that the cache never stores a path called 'hasOwnProperty' if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } @@ -15940,60 +20844,77 @@ function getterFn(path, csp) { pathKeysLength = pathKeys.length, fn; - if (csp) { - fn = (pathKeysLength < 6) - ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) - : function(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn( - pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] - )(scope, locals); - - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - } + // http://jsperf.com/angularjs-parse-getter/6 + if (options.csp) { + if (pathKeysLength < 6) { + fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, + options); + } else { + fn = function(scope, locals) { + var i = 0, val; + do { + val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], + pathKeys[i++], fullExp, options)(scope, locals); + + locals = undefined; // clear after first iteration + scope = val; + } while (i < pathKeysLength); + return val; + }; + } } else { - var code = 'var l, fn, p;\n'; + var code = 'var p;\n'; forEach(pathKeys, function(key, index) { - code += 'if(s === null || s === undefined) return s;\n' + - 'l=s;\n' + + ensureSafeMemberName(key, fullExp); + code += 'if(s == null) return undefined;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + - 'if (s && s.then) {\n' + - ' if (!("$$v" in s)) {\n' + - ' p=s;\n' + - ' p.$$v = undefined;\n' + - ' p.then(function(v) {p.$$v=v;});\n' + - '}\n' + - ' s=s.$$v\n' + - '}\n'; + (options.unwrapPromises + ? 'if (s && s.then) {\n' + + ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' + + ' if (!("$$v" in s)) {\n' + + ' p=s;\n' + + ' p.$$v = undefined;\n' + + ' p.then(function(v) {p.$$v=v;});\n' + + '}\n' + + ' s=s.$$v\n' + + '}\n' + : ''); }); code += 'return s;'; - fn = Function('s', 'k', code); // s=scope, k=locals - fn.toString = function() { return code; }; + + /* jshint -W054 */ + var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning + /* jshint +W054 */ + evaledFnGetter.toString = valueFn(code); + fn = options.unwrapPromises ? function(scope, locals) { + return evaledFnGetter(scope, locals, promiseWarning); + } : evaledFnGetter; } - return getterFnCache[path] = fn; + // Only cache the value if it's not going to mess up the cache object + // This is more performant that using Object.prototype.hasOwnProperty.call + if (path !== 'hasOwnProperty') { + getterFnCache[path] = fn; + } + return fn; } /////////////////////////////////// /** - * @ngdoc function - * @name ng.$parse - * @function + * @ngdoc service + * @name $parse + * @kind function * * @description * * Converts Angular {@link guide/expression expression} into a function. * - *
    + * ```js
      *   var getter = $parse('user.name');
      *   var setter = getter.assign;
      *   var context = {user:{name:'angular'}};
    @@ -16003,32 +20924,163 @@ function getterFn(path, csp) {
      *   setter(context, 'newValue');
      *   expect(context.user.name).toEqual('newValue');
      *   expect(getter(context, locals)).toEqual('local');
    - * 
    + * ``` * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (tipically a scope object). + * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * - * The return function also has an `assign` property, if the expression is assignable, which - * allows one to set values to expressions. + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. + * + */ + + +/** + * @ngdoc provider + * @name $parseProvider + * @kind function * + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. */ function $ParseProvider() { var cache = {}; - this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { + + var $parseOptions = { + csp: false, + unwrapPromises: false, + logPromiseWarnings: true + }; + + + /** + * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. + * + * @ngdoc method + * @name $parseProvider#unwrapPromises + * @description + * + * **This feature is deprecated, see deprecation notes below for more info** + * + * If set to true (default is false), $parse will unwrap promises automatically when a promise is + * found at any part of the expression. In other words, if set to true, the expression will always + * result in a non-promise value. + * + * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled, + * the fulfillment value is used in place of the promise while evaluating the expression. + * + * **Deprecation notice** + * + * This is a feature that didn't prove to be wildly useful or popular, primarily because of the + * dichotomy between data access in templates (accessed as raw values) and controller code + * (accessed as promises). + * + * In most code we ended up resolving promises manually in controllers anyway and thus unifying + * the model access there. + * + * Other downsides of automatic promise unwrapping: + * + * - when building components it's often desirable to receive the raw promises + * - adds complexity and slows down expression evaluation + * - makes expression code pre-generation unattractive due to the amount of code that needs to be + * generated + * - makes IDE auto-completion and tool support hard + * + * **Warning Logs** + * + * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a + * promise (to reduce the noise, each expression is logged only once). To disable this logging use + * `$parseProvider.logPromiseWarnings(false)` api. + * + * + * @param {boolean=} value New value. + * @returns {boolean|self} Returns the current setting when used as getter and self if used as + * setter. + */ + this.unwrapPromises = function(value) { + if (isDefined(value)) { + $parseOptions.unwrapPromises = !!value; + return this; + } else { + return $parseOptions.unwrapPromises; + } + }; + + + /** + * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. + * + * @ngdoc method + * @name $parseProvider#logPromiseWarnings + * @description + * + * Controls whether Angular should log a warning on any encounter of a promise in an expression. + * + * The default is set to `true`. + * + * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well. + * + * @param {boolean=} value New value. + * @returns {boolean|self} Returns the current setting when used as getter and self if used as + * setter. + */ + this.logPromiseWarnings = function(value) { + if (isDefined(value)) { + $parseOptions.logPromiseWarnings = value; + return this; + } else { + return $parseOptions.logPromiseWarnings; + } + }; + + + this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { + $parseOptions.csp = $sniffer.csp; + + promiseWarning = function promiseWarningFn(fullExp) { + if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return; + promiseWarningCache[fullExp] = true; + $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' + + 'Automatic unwrapping of promises in Angular expressions is deprecated.'); + }; + return function(exp) { - switch(typeof exp) { + var parsedExpression; + + switch (typeof exp) { case 'string': - return cache.hasOwnProperty(exp) - ? cache[exp] - : cache[exp] = parser(exp, false, $filter, $sniffer.csp); + + if (cache.hasOwnProperty(exp)) { + return cache[exp]; + } + + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + parsedExpression = parser.parse(exp); + + if (exp !== 'hasOwnProperty') { + // Only cache the value if it's not going to mess up the cache object + // This is more performant that using Object.prototype.hasOwnProperty.call + cache[exp] = parsedExpression; + } + + return parsedExpression; + case 'function': return exp; + default: return noop; } @@ -16038,7 +21090,7 @@ function $ParseProvider() { /** * @ngdoc service - * @name ng.$q + * @name $q * @requires $rootScope * * @description @@ -16051,23 +21103,21 @@ function $ParseProvider() { * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * - *
    - *   // for the purpose of this example let's assume that variables `$q` and `scope` are
    - *   // available in the current lexical scope (they could have been injected or passed in).
    + * ```js
    + *   // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
    + *   // are available in the current lexical scope (they could have been injected or passed in).
      *
      *   function asyncGreet(name) {
      *     var deferred = $q.defer();
      *
      *     setTimeout(function() {
    - *       // since this fn executes async in a future turn of the event loop, we need to wrap
    - *       // our code into an $apply call so that the model changes are properly observed.
    - *       scope.$apply(function() {
    - *         if (okToGreet(name)) {
    - *           deferred.resolve('Hello, ' + name + '!');
    - *         } else {
    - *           deferred.reject('Greeting ' + name + ' is not allowed.');
    - *         }
    - *       });
    + *       deferred.notify('About to greet ' + name + '.');
    + *
    + *       if (okToGreet(name)) {
    + *         deferred.resolve('Hello, ' + name + '!');
    + *       } else {
    + *         deferred.reject('Greeting ' + name + ' is not allowed.');
    + *       }
      *     }, 1000);
      *
      *     return deferred.promise;
    @@ -16078,12 +21128,14 @@ function $ParseProvider() {
      *     alert('Success: ' + greeting);
      *   }, function(reason) {
      *     alert('Failed: ' + reason);
    + *   }, function(update) {
    + *     alert('Got notification: ' + update);
      *   });
    - * 
    + * ``` * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of - * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). + * comes in the way of guarantees that promise and deferred APIs make, see + * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. @@ -16096,7 +21148,8 @@ function $ParseProvider() { * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion of the task. + * that can be used for signaling the successful or unsuccessful completion, as well as the status + * of the task. * * **Methods** * @@ -16104,6 +21157,8 @@ function $ParseProvider() { * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. + * - `notify(value)` - provides updates on the status of the promise's execution. This may be called + * multiple times before the promise is either resolved or rejected. * * **Properties** * @@ -16120,69 +21175,82 @@ function $ParseProvider() { * * **Methods** * - * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved - * or rejected calls one of the success or error callbacks asynchronously as soon as the result - * is available. The callbacks are called with a single argument the result or rejection reason. + * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or + * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously + * as soon as the result is available. The callbacks are called with a single argument: the result + * or rejection reason. Additionally, the notify callback may be called zero or more times to + * provide a progress indication, before the promise is resolved or rejected. * * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback` or `errorCallback`. + * `successCallback`, `errorCallback`. It also notifies via the return value of the + * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback + * method. + * + * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` * + * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. This is useful to release resources or do some + * clean-up that needs to be done whether the promise was rejected or resolved. See the [full + * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for + * more information. + * + * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as + * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to + * make your code IE8 and Android 2.x compatible. * * # Chaining promises * - * Because calling `then` api of a promise returns a new derived promise, it is easily possible - * to create a chain of promises: + * Because calling the `then` method of a promise returns a new derived promise, it is easily + * possible to create a chain of promises: * - *
    + * ```js
      *   promiseB = promiseA.then(function(result) {
      *     return result + 1;
      *   });
      *
    - *   // promiseB will be resolved immediately after promiseA is resolved and its value will be
    - *   // the result of promiseA incremented by 1
    - * 
    + * // promiseB will be resolved immediately after promiseA is resolved and its value + * // will be the result of promiseA incremented by 1 + * ``` * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful apis like + * the promises at any point in the chain. This makes it possible to implement powerful APIs like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * - * There are three main differences: + * There are two main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. - * - $q promises are recognized by the templating engine in angular, which means that in templates - * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. - * + * * # Testing - * - *
    + *
    + *  ```js
      *    it('should simulate promise', inject(function($q, $rootScope) {
      *      var deferred = $q.defer();
      *      var promise = deferred.promise;
      *      var resolvedValue;
    - * 
    + *
      *      promise.then(function(value) { resolvedValue = value; });
      *      expect(resolvedValue).toBeUndefined();
    - * 
    + *
      *      // Simulate resolving of promise
      *      deferred.resolve(123);
      *      // Note that the 'then' function does not get called synchronously.
      *      // This is because we want the promise API to always be async, whether or not
      *      // it got called synchronously or asynchronously.
      *      expect(resolvedValue).toBeUndefined();
    - * 
    + *
      *      // Propagate promise resolution to 'then' functions using $apply().
      *      $rootScope.$apply();
      *      expect(resolvedValue).toEqual(123);
    - *    });
    - *  
    + * })); + * ``` */ function $QProvider() { @@ -16197,7 +21265,7 @@ function $QProvider() { /** * Constructs a promise manager. * - * @param {function(function)} nextTick Function for executing functions in the next turn. + * @param {function(Function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. @@ -16205,9 +21273,10 @@ function $QProvider() { function qFactory(nextTick, exceptionHandler) { /** - * @ngdoc - * @name ng.$q#defer - * @methodOf ng.$q + * @ngdoc method + * @name $q#defer + * @kind function + * * @description * Creates a `Deferred` object which represents a task which will finish in the future. * @@ -16230,7 +21299,7 @@ function qFactory(nextTick, exceptionHandler) { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; - value.then(callback[0], callback[1]); + value.then(callback[0], callback[1], callback[2]); } }); } @@ -16239,39 +21308,105 @@ function qFactory(nextTick, exceptionHandler) { reject: function(reason) { - deferred.resolve(reject(reason)); + deferred.resolve(createInternalRejectedPromise(reason)); + }, + + + notify: function(progress) { + if (pending) { + var callbacks = pending; + + if (pending.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + callback[2](progress); + } + }); + } + } }, promise: { - then: function(callback, errback) { + then: function(callback, errback, progressback) { var result = defer(); var wrappedCallback = function(value) { try { - result.resolve((callback || defaultCallback)(value)); + result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); } catch(e) { - exceptionHandler(e); result.reject(e); + exceptionHandler(e); } }; var wrappedErrback = function(reason) { try { - result.resolve((errback || defaultErrback)(reason)); + result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); } catch(e) { - exceptionHandler(e); result.reject(e); + exceptionHandler(e); + } + }; + + var wrappedProgressback = function(progress) { + try { + result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); + } catch(e) { + exceptionHandler(e); } }; if (pending) { - pending.push([wrappedCallback, wrappedErrback]); + pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); } else { - value.then(wrappedCallback, wrappedErrback); + value.then(wrappedCallback, wrappedErrback, wrappedProgressback); } return result.promise; + }, + + "catch": function(callback) { + return this.then(null, callback); + }, + + "finally": function(callback) { + + function makePromise(value, resolved) { + var result = defer(); + if (resolved) { + result.resolve(value); + } else { + result.reject(value); + } + return result.promise; + } + + function handleCallback(value, isResolved) { + var callbackOutput = null; + try { + callbackOutput = (callback ||defaultCallback)(); + } catch(e) { + return makePromise(e, false); + } + if (isPromiseLike(callbackOutput)) { + return callbackOutput.then(function() { + return makePromise(value, isResolved); + }, function(error) { + return makePromise(error, false); + }); + } else { + return makePromise(value, isResolved); + } + } + + return this.then(function(value) { + return handleCallback(value, true); + }, function(error) { + return handleCallback(error, false); + }); } } }; @@ -16281,7 +21416,7 @@ function qFactory(nextTick, exceptionHandler) { var ref = function(value) { - if (value && value.then) return value; + if (isPromiseLike(value)) return value; return { then: function(callback) { var result = defer(); @@ -16295,9 +21430,10 @@ function qFactory(nextTick, exceptionHandler) { /** - * @ngdoc - * @name ng.$q#reject - * @methodOf ng.$q + * @ngdoc method + * @name $q#reject + * @kind function + * * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in @@ -16309,7 +21445,7 @@ function qFactory(nextTick, exceptionHandler) { * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * - *
    +   * ```js
        *   promiseB = promiseA.then(function(result) {
        *     // success: do something and resolve promiseB
        *     //          with the old or a new result
    @@ -16324,625 +21460,184 @@ function qFactory(nextTick, exceptionHandler) {
        *     }
        *     return $q.reject(reason);
        *   });
    -   * 
    + * ``` * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { - return { - then: function(callback, errback) { - var result = defer(); - nextTick(function() { - result.resolve((errback || defaultErrback)(reason)); - }); - return result.promise; - } - }; - }; - - - /** - * @ngdoc - * @name ng.$q#when - * @methodOf ng.$q - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise - */ - var when = function(value, callback, errback) { - var result = defer(), - done; - - var wrappedCallback = function(value) { - try { - return (callback || defaultCallback)(value); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedErrback = function(reason) { - try { - return (errback || defaultErrback)(reason); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - nextTick(function() { - ref(value).then(function(value) { - if (done) return; - done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); - }, function(reason) { - if (done) return; - done = true; - result.resolve(wrappedErrback(reason)); - }); - }); - + var result = defer(); + result.reject(reason); return result.promise; - }; - - - function defaultCallback(value) { - return value; - } - - - function defaultErrback(reason) { - return reject(reason); - } - - - /** - * @ngdoc - * @name ng.$q#all - * @methodOf ng.$q - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.} promises An array of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array of values, - * each value corresponding to the promise at the same index in the `promises` array. If any of - * the promises is resolved with a rejection, this resulting promise will be resolved with the - * same rejection. - */ - function all(promises) { - var deferred = defer(), - counter = promises.length, - results = []; - - if (counter) { - forEach(promises, function(promise, index) { - ref(promise).then(function(value) { - if (index in results) return; - results[index] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (index in results) return; - deferred.reject(reason); - }); - }); - } else { - deferred.resolve(results); - } - - return deferred.promise; - } - - return { - defer: defer, - reject: reject, - when: when, - all: all - }; -} - -/** - * @ngdoc object - * @name ng.$routeProvider - * @function - * - * @description - * - * Used for configuring routes. See {@link ng.$route $route} for an example. - */ -function $RouteProvider(){ - var routes = {}; - - /** - * @ngdoc method - * @name ng.$routeProvider#when - * @methodOf ng.$routeProvider - * - * @param {string} path Route path (matched against `$location.path`). If `$location.path` - * contains redundant trailing slash or is missing one, the route will still match and the - * `$location.path` will be updated to add or drop the trailing slash to exactly match the - * route definition. - * - * `path` can contain named groups starting with a colon (`:name`). All characters up to the - * next slash are matched and stored in `$routeParams` under the given `name` when the route - * matches. - * - * @param {Object} route Mapping information to be assigned to `$route.current` on route - * match. - * - * Object properties: - * - * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly - * created scope or the name of a {@link angular.Module#controller registered controller} - * if passed as a string. - * - `template` – `{string=}` – html template as a string that should be used by - * {@link ng.directive:ngView ngView} or - * {@link ng.directive:ngInclude ngInclude} directives. - * this property takes precedence over `templateUrl`. - * - `templateUrl` – `{string=}` – path to an html template that should be used by - * {@link ng.directive:ngView ngView}. - * - `resolve` - `{Object.=}` - An optional map of dependencies which should - * be injected into the controller. If any of these dependencies are promises, they will be - * resolved and converted to a value before the controller is instantiated and the - * `$routeChangeSuccess` event is fired. The map object is: - * - * - `key` – `{string}`: a name of a dependency to be injected into the controller. - * - `factory` - `{string|function}`: If `string` then it is an alias for a service. - * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} - * and the return value is treated as the dependency. If the result is a promise, it is resolved - * before its value is injected into the controller. - * - * - `redirectTo` – {(string|function())=} – value to update - * {@link ng.$location $location} path with and trigger route redirection. - * - * If `redirectTo` is a function, it will be called with the following parameters: - * - * - `{Object.}` - route parameters extracted from the current - * `$location.path()` by applying the current route templateUrl. - * - `{string}` - current `$location.path()` - * - `{Object}` - current `$location.search()` - * - * The custom `redirectTo` function is expected to return a string which will be used - * to update `$location.path()` and `$location.search()`. - * - * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() - * changes. - * - * If the option is set to `false` and url in the browser changes, then - * `$routeUpdate` event is broadcasted on the root scope. - * - * @returns {Object} self - * - * @description - * Adds a new route definition to the `$route` service. - */ - this.when = function(path, route) { - routes[path] = extend({reloadOnSearch: true}, route); - - // create redirection for trailing slashes - if (path) { - var redirectPath = (path[path.length-1] == '/') - ? path.substr(0, path.length-1) - : path +'/'; - - routes[redirectPath] = {redirectTo: path}; - } - - return this; - }; - - /** - * @ngdoc method - * @name ng.$routeProvider#otherwise - * @methodOf ng.$routeProvider - * - * @description - * Sets route definition that will be used on route change when no other route definition - * is matched. - * - * @param {Object} params Mapping information to be assigned to `$route.current`. - * @returns {Object} self - */ - this.otherwise = function(params) { - this.when(null, params); - return this; - }; - - - this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', - function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { - - /** - * @ngdoc object - * @name ng.$route - * @requires $location - * @requires $routeParams - * - * @property {Object} current Reference to the current route definition. - * The route definition contains: - * - * - `controller`: The controller constructor as define in route definition. - * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for - * controller instantiation. The `locals` contain - * the resolved values of the `resolve` map. Additionally the `locals` also contain: - * - * - `$scope` - The current route scope. - * - `$template` - The current route template HTML. - * - * @property {Array.} routes Array of all configured routes. - * - * @description - * Is used for deep-linking URLs to controllers and views (HTML partials). - * It watches `$location.url()` and tries to map the path to an existing route definition. - * - * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. - * - * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} - * directive and the {@link ng.$routeParams $routeParams} service. - * - * @example - This example shows how changing the URL hash causes the `$route` to match a route against the - URL, and the `ngView` pulls in the partial. - - Note that this example is using {@link ng.directive:script inlined templates} - to get it working on jsfiddle as well. - - - -
    - Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
    - -
    -
    - -
    $location.path() = {{$location.path()}}
    -
    $route.current.templateUrl = {{$route.current.templateUrl}}
    -
    $route.current.params = {{$route.current.params}}
    -
    $route.current.scope.name = {{$route.current.scope.name}}
    -
    $routeParams = {{$routeParams}}
    -
    -
    - - - controller: {{name}}
    - Book Id: {{params.bookId}}
    -
    - - - controller: {{name}}
    - Book Id: {{params.bookId}}
    - Chapter Id: {{params.chapterId}} -
    - - - angular.module('ngView', [], function($routeProvider, $locationProvider) { - $routeProvider.when('/Book/:bookId', { - templateUrl: 'book.html', - controller: BookCntl, - resolve: { - // I will cause a 1 second delay - delay: function($q, $timeout) { - var delay = $q.defer(); - $timeout(delay.resolve, 1000); - return delay.promise; - } - } - }); - $routeProvider.when('/Book/:bookId/ch/:chapterId', { - templateUrl: 'chapter.html', - controller: ChapterCntl - }); - - // configure html5 to get links working on jsfiddle - $locationProvider.html5Mode(true); - }); - - function MainCntl($scope, $route, $routeParams, $location) { - $scope.$route = $route; - $scope.$location = $location; - $scope.$routeParams = $routeParams; - } - - function BookCntl($scope, $routeParams) { - $scope.name = "BookCntl"; - $scope.params = $routeParams; - } + }; - function ChapterCntl($scope, $routeParams) { - $scope.name = "ChapterCntl"; - $scope.params = $routeParams; - } - + var createInternalRejectedPromise = function(reason) { + return { + then: function(callback, errback) { + var result = defer(); + nextTick(function() { + try { + result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }); + return result.promise; + } + }; + }; - - it('should load and compile correct template', function() { - element('a:contains("Moby: Ch1")').click(); - var content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: ChapterCntl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); - - element('a:contains("Scarlet")').click(); - sleep(2); // promises are not part of scenario waiting - content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: BookCntl/); - expect(content).toMatch(/Book Id\: Scarlet/); - }); - -
    - */ - /** - * @ngdoc event - * @name ng.$route#$routeChangeStart - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted before a route change. At this point the route services starts - * resolving all of the dependencies needed for the route change to occurs. - * Typically this involves fetching the view template as well as any dependencies - * defined in `resolve` route property. Once all of the dependencies are resolved - * `$routeChangeSuccess` is fired. - * - * @param {Route} next Future route information. - * @param {Route} current Current route information. - */ + /** + * @ngdoc method + * @name $q#when + * @kind function + * + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @returns {Promise} Returns a promise of the passed value or promise + */ + var when = function(value, callback, errback, progressback) { + var result = defer(), + done; - /** - * @ngdoc event - * @name ng.$route#$routeChangeSuccess - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted after a route dependencies are resolved. - * {@link ng.directive:ngView ngView} listens for the directive - * to instantiate the controller and render the view. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} current Current route information. - * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered. - */ + var wrappedCallback = function(value) { + try { + return (isFunction(callback) ? callback : defaultCallback)(value); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; - /** - * @ngdoc event - * @name ng.$route#$routeChangeError - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted if any of the resolve promises are rejected. - * - * @param {Route} current Current route information. - * @param {Route} previous Previous route information. - * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. - */ + var wrappedErrback = function(reason) { + try { + return (isFunction(errback) ? errback : defaultErrback)(reason); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; - /** - * @ngdoc event - * @name ng.$route#$routeUpdate - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * - * The `reloadOnSearch` property has been set to false, and we are reusing the same - * instance of the Controller. - */ + var wrappedProgressback = function(progress) { + try { + return (isFunction(progressback) ? progressback : defaultCallback)(progress); + } catch (e) { + exceptionHandler(e); + } + }; - var forceReload = false, - $route = { - routes: routes, + nextTick(function() { + ref(value).then(function(value) { + if (done) return; + done = true; + result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); + }, function(reason) { + if (done) return; + done = true; + result.resolve(wrappedErrback(reason)); + }, function(progress) { + if (done) return; + result.notify(wrappedProgressback(progress)); + }); + }); - /** - * @ngdoc method - * @name ng.$route#reload - * @methodOf ng.$route - * - * @description - * Causes `$route` service to reload the current route even if - * {@link ng.$location $location} hasn't changed. - * - * As a result of that, {@link ng.directive:ngView ngView} - * creates new scope, reinstantiates the controller. - */ - reload: function() { - forceReload = true; - $rootScope.$evalAsync(updateRoute); - } - }; + return result.promise; + }; - $rootScope.$on('$locationChangeSuccess', updateRoute); - return $route; + function defaultCallback(value) { + return value; + } - ///////////////////////////////////////////////////// - /** - * @param on {string} current url - * @param when {string} route when template to match the url against - * @return {?Object} - */ - function switchRouteMatcher(on, when) { - // TODO(i): this code is convoluted and inefficient, we should construct the route matching - // regex only once and then reuse it - - // Escape regexp special characters. - when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + '$'; - var regex = '', - params = [], - dst = {}; - - var re = /:(\w+)/g, - paramMatch, - lastMatchedIndex = 0; - - while ((paramMatch = re.exec(when)) !== null) { - // Find each :param in `when` and replace it with a capturing group. - // Append all other sections of when unchanged. - regex += when.slice(lastMatchedIndex, paramMatch.index); - regex += '([^\\/]*)'; - params.push(paramMatch[1]); - lastMatchedIndex = re.lastIndex; - } - // Append trailing path part. - regex += when.substr(lastMatchedIndex); + function defaultErrback(reason) { + return reject(reason); + } - var match = on.match(new RegExp(regex)); - if (match) { - forEach(params, function(name, index) { - dst[name] = match[index + 1]; - }); - } - return match ? dst : null; - } - - function updateRoute() { - var next = parseRoute(), - last = $route.current; - - if (next && last && next.$$route === last.$$route - && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { - last.params = next.params; - copy(last.params, $routeParams); - $rootScope.$broadcast('$routeUpdate', last); - } else if (next || last) { - forceReload = false; - $rootScope.$broadcast('$routeChangeStart', next, last); - $route.current = next; - if (next) { - if (next.redirectTo) { - if (isString(next.redirectTo)) { - $location.path(interpolate(next.redirectTo, next.params)).search(next.params) - .replace(); - } else { - $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) - .replace(); - } - } - } - $q.when(next). - then(function() { - if (next) { - var keys = [], - values = [], - template; + /** + * @ngdoc method + * @name $q#all + * @kind function + * + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. + * If any of the promises is resolved with a rejection, this resulting promise will be rejected + * with the same rejection value. + */ + function all(promises) { + var deferred = defer(), + counter = 0, + results = isArray(promises) ? [] : {}; + + forEach(promises, function(promise, key) { + counter++; + ref(promise).then(function(value) { + if (results.hasOwnProperty(key)) return; + results[key] = value; + if (!(--counter)) deferred.resolve(results); + }, function(reason) { + if (results.hasOwnProperty(key)) return; + deferred.reject(reason); + }); + }); - forEach(next.resolve || {}, function(value, key) { - keys.push(key); - values.push(isString(value) ? $injector.get(value) : $injector.invoke(value)); - }); - if (isDefined(template = next.template)) { - } else if (isDefined(template = next.templateUrl)) { - template = $http.get(template, {cache: $templateCache}). - then(function(response) { return response.data; }); - } - if (isDefined(template)) { - keys.push('$template'); - values.push(template); - } - return $q.all(values).then(function(values) { - var locals = {}; - forEach(values, function(value, index) { - locals[keys[index]] = value; - }); - return locals; - }); - } - }). - // after route change - then(function(locals) { - if (next == $route.current) { - if (next) { - next.locals = locals; - copy(next.params, $routeParams); - } - $rootScope.$broadcast('$routeChangeSuccess', next, last); - } - }, function(error) { - if (next == $route.current) { - $rootScope.$broadcast('$routeChangeError', next, last, error); - } - }); - } + if (counter === 0) { + deferred.resolve(results); } + return deferred.promise; + } - /** - * @returns the current active route, by matching it against the URL - */ - function parseRoute() { - // Match a route - var params, match; - forEach(routes, function(route, path) { - if (!match && (params = switchRouteMatcher($location.path(), path))) { - match = inherit(route, { - params: extend({}, $location.search(), params), - pathParams: params}); - match.$$route = route; - } - }); - // No route matched; fallback to "otherwise" route - return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); - } + return { + defer: defer, + reject: reject, + when: when, + all: all + }; +} - /** - * @returns interpolation of the redirect path with the parametrs - */ - function interpolate(string, params) { - var result = []; - forEach((string||'').split(':'), function(segment, i) { - if (i == 0) { - result.push(segment); - } else { - var segmentMatch = segment.match(/(\w+)(.*)/); - var key = segmentMatch[1]; - result.push(params[key]); - result.push(segmentMatch[2] || ''); - delete params[key]; +function $$RAFProvider(){ //rAF + this.$get = ['$window', '$timeout', function($window, $timeout) { + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame || + $window.mozRequestAnimationFrame; + + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.mozCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; + + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported + ? function(fn) { + var id = requestAnimationFrame(fn); + return function() { + cancelAnimationFrame(id); + }; } - }); - return result.join(''); - } - }]; -} + : function(fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function() { + $timeout.cancel(timer); + }; + }; -/** - * @ngdoc object - * @name ng.$routeParams - * @requires $route - * - * @description - * Current set of route parameters. The route parameters are a combination of the - * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters - * are extracted when the {@link ng.$route $route} path is matched. - * - * In case of parameter name collision, `path` params take precedence over `search` params. - * - * The service guarantees that the identity of the `$routeParams` object will remain unchanged - * (but its properties will likely change) even when a route change occurs. - * - * @example - *
    - *  // Given:
    - *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
    - *  // Route: /Chapter/:chapterId/Section/:sectionId
    - *  //
    - *  // Then
    - *  $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
    - * 
    - */ -function $RouteParamsProvider() { - this.$get = valueFn({}); + raf.supported = rafSupported; + + return raf; + }]; } /** @@ -16960,7 +21655,7 @@ function $RouteParamsProvider() { * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (shift) instead of at the end (push) + * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list @@ -16972,39 +21667,50 @@ function $RouteParamsProvider() { /** - * @ngdoc object - * @name ng.$rootScopeProvider + * @ngdoc provider + * @name $rootScopeProvider * @description * * Provider for the $rootScope service. */ /** - * @ngdoc function - * @name ng.$rootScopeProvider#digestTtl - * @methodOf ng.$rootScopeProvider + * @ngdoc method + * @name $rootScopeProvider#digestTtl * @description * - * Sets the number of digest iterations the scope should attempt to execute before giving up and + * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * + * In complex applications it's possible that the dependencies between `$watch`s will result in + * several digest iterations. However if an application needs more than the default 10 digest + * iterations for its model to stabilize then you should investigate what is causing the model to + * continuously change during the digest. + * + * Increasing the TTL could have performance implications, so you should not change it without + * proper justification. + * * @param {number} limit The number of digest iterations. */ /** - * @ngdoc object - * @name ng.$rootScope + * @ngdoc service + * @name $rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. - * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide - * event processing life-cycle. See {@link guide/scope developer guide on scopes}. + * All other scopes are descendant scopes of the root scope. Scopes provide separation + * between the model and the view, via a mechanism for watching the model for changes. + * They also provide an event emission/broadcast and subscription facility. See the + * {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + var lastDirtyWatch = null; this.digestTtl = function(value) { if (arguments.length) { @@ -17013,45 +21719,27 @@ function $RootScopeProvider(){ return TTL; }; - this.$get = ['$injector', '$exceptionHandler', '$parse', - function( $injector, $exceptionHandler, $parse) { + this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', + function( $injector, $exceptionHandler, $parse, $browser) { /** - * @ngdoc function - * @name ng.$rootScope.Scope + * @ngdoc type + * @name $rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the - * {@link AUTO.$injector $injector}. Child scopes are created using the + * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. - *
    -        angular.injector(['ng']).invoke(function($rootScope) {
    -           var scope = $rootScope.$new();
    -           scope.salutation = 'Hello';
    -           scope.name = 'World';
    -
    -           expect(scope.greeting).toEqual(undefined);
    -
    -           scope.$watch('name', function() {
    -             scope.greeting = scope.salutation + ' ' + scope.name + '!';
    -           }); // initialize the watch
    -
    -           expect(scope.greeting).toEqual(undefined);
    -           scope.name = 'Misko';
    -           // still old value, since watches have not been called yet
    -           expect(scope.greeting).toEqual(undefined);
    -
    -           scope.$digest(); // fire all  the watches
    -           expect(scope.greeting).toEqual('Hello Misko!');
    -        });
    -     * 
    + * ```html + * + * ``` * * # Inheritance * A scope can inherit from a parent scope, as in this example: - *
    +     * ```js
              var parent = $rootScope;
              var child = parent.$new();
     
    @@ -17062,14 +21750,15 @@ function $RootScopeProvider(){
              child.salutation = "Welcome";
              expect(child.salutation).toEqual('Welcome');
              expect(parent.salutation).toEqual('Hello');
    -     * 
    + * ``` * * - * @param {Object.=} providers Map of service factory which need to be provided - * for the current scope. Defaults to {@link ng}. + * @param {Object.=} providers Map of service factory which need to be + * provided for the current scope. Defaults to {@link ng}. * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy when unit-testing and having - * the need to override a default service. + * append/override services provided by `providers`. This is handy + * when unit-testing and having the need to override a default + * service. * @returns {Object} Newly created scope. * */ @@ -17081,69 +21770,74 @@ function $RootScopeProvider(){ this['this'] = this.$root = this; this.$$destroyed = false; this.$$asyncQueue = []; + this.$$postDigestQueue = []; this.$$listeners = {}; + this.$$listenerCount = {}; this.$$isolateBindings = {}; } /** * @ngdoc property - * @name ng.$rootScope.Scope#$id - * @propertyOf ng.$rootScope.Scope + * @name $rootScope.Scope#$id * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { + constructor: Scope, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$new - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$new + * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and - * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope - * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. + * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the + * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * - * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for - * the scope and its child scopes to be permanently detached from the parent and thus stop - * participating in model change detection and listener notification by invoking. + * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is + * desired for the scope and its child scopes to be permanently detached from the parent and + * thus stop participating in model change detection and listener notification by invoking. * - * @param {boolean} isolate if true then the scope does not prototypically inherit from the + * @param {boolean} isolate If true, then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. - * When creating widgets it is useful for the widget to not accidentally read parent + * When creating widgets, it is useful for the widget to not accidentally read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { - var Child, + var ChildScope, child; - if (isFunction(isolate)) { - // TODO: remove at some point - throw Error('API-CHANGE: Use $controller to instantiate controllers.'); - } if (isolate) { child = new Scope(); child.$root = this.$root; + // ensure that there is just one async queue per $rootScope and its children + child.$$asyncQueue = this.$$asyncQueue; + child.$$postDigestQueue = this.$$postDigestQueue; } else { - Child = function() {}; // should be anonymous; This is so that when the minifier munges - // the name it does not become random set of chars. These will then show up as class - // name in the debugger. - Child.prototype = this; - child = new Child(); - child.$id = nextUid(); + // Only create a child scope class if somebody asks for one, + // but cache it to allow the VM to optimize lookups. + if (!this.$$childScopeClass) { + this.$$childScopeClass = function() { + this.$$watchers = this.$$nextSibling = + this.$$childHead = this.$$childTail = null; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$id = nextUid(); + this.$$childScopeClass = null; + }; + this.$$childScopeClass.prototype = this; + } + child = new this.$$childScopeClass(); } child['this'] = child; - child.$$listeners = {}; child.$parent = this; - child.$$asyncQueue = []; - child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; @@ -17155,33 +21849,37 @@ function $RootScopeProvider(){ }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$watch - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$watch + * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * - * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and - * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} - * reruns when it detects changes the `watchExpression` can execute multiple times per + * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest + * $digest()} and should return the value that will be watched. (Since + * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the + * `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). The inequality is determined according to - * {@link angular.equals} function. To save the value of the object for later comparison, the - * {@link angular.copy} function is used. It also means that watching complex options will - * have adverse memory and performance implications. - * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This - * is achieved by rerunning the watchers until no changes are detected. The rerun iteration - * limit is 10 to prevent an infinite loop deadlock. + * see below). Inequality is determined according to reference inequality, + * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) + * via the `!==` Javascript operator, unless `objectEquality == true` + * (see next point) + * - When `objectEquality == true`, inequality of the `watchExpression` is determined + * according to the {@link angular.equals} function. To save the value of the object for + * later comparison, the {@link angular.copy} function is used. This therefore means that + * watching complex objects will have adverse memory and performance implications. + * - The watch `listener` may change the model, which may trigger other `listener`s to fire. + * This is achieved by rerunning the watchers until no changes are detected. The rerun + * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is - * detected, be prepared for multiple calls to your listener.) + * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a + * change is detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the @@ -17190,102 +21888,331 @@ function $RootScopeProvider(){ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * + * The example below contains an illustration of using a function as your $watch listener + * * * # Example - *
    +       * ```js
                // let's assume that scope was dependency injected as the $rootScope
                var scope = $rootScope;
                scope.name = 'misko';
                scope.counter = 0;
     
                expect(scope.counter).toEqual(0);
    -           scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
    +           scope.$watch('name', function(newValue, oldValue) {
    +             scope.counter = scope.counter + 1;
    +           });
                expect(scope.counter).toEqual(0);
     
                scope.$digest();
    -           // no variable change
    -           expect(scope.counter).toEqual(0);
    +           // the listener is always called during the first $digest loop after it was registered
    +           expect(scope.counter).toEqual(1);
     
    -           scope.name = 'adam';
                scope.$digest();
    +           // but now it will not be called unless the value changes
                expect(scope.counter).toEqual(1);
    -       * 
    + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + + + + // Using a listener function + var food; + scope.foodCounter = 0; + expect(scope.foodCounter).toEqual(0); + scope.$watch( + // This is the listener function + function() { return food; }, + // This is the change handler + function(newValue, oldValue) { + if ( newValue !== oldValue ) { + // Only increment the counter if the value changed + scope.foodCounter = scope.foodCounter + 1; + } + } + ); + // No digest has been run so the counter will be zero + expect(scope.foodCounter).toEqual(0); + + // Run the digest but since food has not changed count will still be zero + scope.$digest(); + expect(scope.foodCounter).toEqual(0); + + // Update food and run digest. Now the counter will increment + food = 'cheeseburger'; + scope.$digest(); + expect(scope.foodCounter).toEqual(1); + + * ``` * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a - * call to the `listener`. + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers + * a call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(newValue, oldValue, scope)`: called with current and previous values as + * parameters. + * + * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of + * comparing for reference equality. + * @returns {function()} Returns a deregistration function for this listener. + */ + $watch: function(watchExp, listener, objectEquality) { + var scope = this, + get = compileToFn(watchExp, 'watch'), + array = scope.$$watchers, + watcher = { + fn: listener, + last: initWatchVal, + get: get, + exp: watchExp, + eq: !!objectEquality + }; + + lastDirtyWatch = null; + + // in the case user pass string, we need to compile it, do we really need this ? + if (!isFunction(listener)) { + var listenFn = compileToFn(listener || noop, 'listener'); + watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; + } + + if (typeof watchExp == 'string' && get.constant) { + var originalFn = watcher.fn; + watcher.fn = function(newVal, oldVal, scope) { + originalFn.call(this, newVal, oldVal, scope); + arrayRemove(array, watcher); + }; + } + + if (!array) { + array = scope.$$watchers = []; + } + // we use unshift since we use a while loop in $digest for speed. + // the while loop reads in reverse order. + array.unshift(watcher); + + return function deregisterWatch() { + arrayRemove(array, watcher); + lastDirtyWatch = null; + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$watchCollection + * @kind function + * + * @description + * Shallow watches the properties of an object and fires whenever any of the properties change + * (for arrays, this implies watching the array items; for object maps, this implies watching + * the properties). If a change is detected, the `listener` callback is fired. + * + * - The `obj` collection is observed via standard $watch operation and is examined on every + * call to $digest() to see if any items have been added, removed, or moved. + * - The `listener` is called whenever anything within the `obj` has changed. Examples include + * adding, removing, and moving items belonging to an object or array. + * + * + * # Example + * ```js + $scope.names = ['igor', 'matias', 'misko', 'james']; + $scope.dataCount = 4; + + $scope.$watchCollection('names', function(newNames, oldNames) { + $scope.dataCount = newNames.length; + }); + + expect($scope.dataCount).toEqual(4); + $scope.$digest(); + + //still at 4 ... no changes + expect($scope.dataCount).toEqual(4); + + $scope.names.pop(); + $scope.$digest(); + + //now there's been a change + expect($scope.dataCount).toEqual(3); + * ``` + * * - * @param {boolean=} objectEquality Compare object for equality rather than for reference. - * @returns {function()} Returns a deregistration function for this listener. + * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The + * expression value should evaluate to an object or an array which is observed on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the + * collection will trigger a call to the `listener`. + * + * @param {function(newCollection, oldCollection, scope)} listener a callback function called + * when a change is detected. + * - The `newCollection` object is the newly modified data obtained from the `obj` expression + * - The `oldCollection` object is a copy of the former collection data. + * Due to performance considerations, the`oldCollection` value is computed only if the + * `listener` function declares two or more arguments. + * - The `scope` argument refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the + * de-registration function is executed, the internal watch operation is terminated. */ - $watch: function(watchExp, listener, objectEquality) { - var scope = this, - get = compileToFn(watchExp, 'watch'), - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; + $watchCollection: function(obj, listener) { + var self = this; + // the current value, updated on each dirty-check run + var newValue; + // a shallow copy of the newValue from the last dirty-check run, + // updated to match newValue during dirty-check run + var oldValue; + // a shallow copy of the newValue from when the last change happened + var veryOldValue; + // only track veryOldValue if the listener is asking for it + var trackVeryOldValue = (listener.length > 1); + var changeDetected = 0; + var objGetter = $parse(obj); + var internalArray = []; + var internalObject = {}; + var initRun = true; + var oldLength = 0; + + function $watchCollectionWatch() { + newValue = objGetter(self); + var newLength, key, bothNaN; + + if (!isObject(newValue)) { // if primitive + if (oldValue !== newValue) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } - // in the case user pass string, we need to compile it, do we really need this ? - if (!isFunction(listener)) { - var listenFn = compileToFn(listener || noop, 'listener'); - watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; + newLength = newValue.length; + + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; i++) { + bothNaN = (oldValue[i] !== oldValue[i]) && + (newValue[i] !== newValue[i]); + if (!bothNaN && (oldValue[i] !== newValue[i])) { + changeDetected++; + oldValue[i] = newValue[i]; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (newValue.hasOwnProperty(key)) { + newLength++; + if (oldValue.hasOwnProperty(key)) { + bothNaN = (oldValue[key] !== oldValue[key]) && + (newValue[key] !== newValue[key]); + if (!bothNaN && (oldValue[key] !== newValue[key])) { + changeDetected++; + oldValue[key] = newValue[key]; + } + } else { + oldLength++; + oldValue[key] = newValue[key]; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for(key in oldValue) { + if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; } - if (!array) { - array = scope.$$watchers = []; + function $watchCollectionAction() { + if (initRun) { + initRun = false; + listener(newValue, newValue, self); + } else { + listener(newValue, veryOldValue, self); + } + + // make a copy for the next time a collection is changed + if (trackVeryOldValue) { + if (!isObject(newValue)) { + //primitive + veryOldValue = newValue; + } else if (isArrayLike(newValue)) { + veryOldValue = new Array(newValue.length); + for (var i = 0; i < newValue.length; i++) { + veryOldValue[i] = newValue[i]; + } + } else { // if object + veryOldValue = {}; + for (var key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + veryOldValue[key] = newValue[key]; + } + } + } + } } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); - return function() { - arrayRemove(array, watcher); - }; + return this.$watch($watchCollectionWatch, $watchCollectionAction); }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$digest - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$digest + * @kind function * * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. - * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the - * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are - * firing. This means that it is possible to get into an infinite loop. This function will throw - * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and + * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change + * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} + * until no more listeners are firing. This means that it is possible to get into an infinite + * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of + * iterations exceeds 10. * - * Usually you don't call `$digest()` directly in + * Usually, you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. - * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a - * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. + * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within + * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} - * with no `listener`. + * you can register a `watchExpression` function with + * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. * - * You may have a need to call `$digest()` from within unit-tests, to simulate the scope - * life-cycle. + * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * * # Example - *
    +       * ```js
                var scope = ...;
                scope.name = 'misko';
                scope.counter = 0;
    @@ -17297,39 +22224,51 @@ function $RootScopeProvider(){
                expect(scope.counter).toEqual(0);
     
                scope.$digest();
    -           // no variable change
    -           expect(scope.counter).toEqual(0);
    +           // the listener is always called during the first $digest loop after it was registered
    +           expect(scope.counter).toEqual(1);
     
    -           scope.name = 'adam';
                scope.$digest();
    +           // but now it will not be called unless the value changes
                expect(scope.counter).toEqual(1);
    -       * 
    + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + * ``` * */ $digest: function() { var watch, value, last, watchers, - asyncQueue, + asyncQueue = this.$$asyncQueue, + postDigestQueue = this.$$postDigestQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], - logIdx, logMsg; + logIdx, logMsg, asyncTask; beginPhase('$digest'); - do { + lastDirtyWatch = null; + + do { // "while dirty" loop dirty = false; current = target; - do { - asyncQueue = current.$$asyncQueue; - while(asyncQueue.length) { - try { - current.$eval(asyncQueue.shift()); - } catch (e) { - $exceptionHandler(e); - } + + while(asyncQueue.length) { + try { + asyncTask = asyncQueue.shift(); + asyncTask.scope.$eval(asyncTask.expression); + } catch (e) { + clearPhase(); + $exceptionHandler(e); } + lastDirtyWatch = null; + } + + traverseScopesLoop: + do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; @@ -17338,25 +22277,34 @@ function $RootScopeProvider(){ watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals - if ((value = watch.get(current)) !== (last = watch.last) && - !(watch.eq - ? equals(value, last) - : (typeof value == 'number' && typeof last == 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - watch.last = watch.eq ? copy(value) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); + if (watch) { + if ((value = watch.get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (typeof value === 'number' && typeof last === 'number' + && isNaN(value) && isNaN(last)))) { + dirty = true; + lastDirtyWatch = watch; + watch.last = watch.eq ? copy(value, null) : value; + watch.fn(value, ((last === initWatchVal) ? value : last), current); + if (ttl < 5) { + logIdx = 4 - ttl; + if (!watchLog[logIdx]) watchLog[logIdx] = []; + logMsg = (isFunction(watch.exp)) + ? 'fn: ' + (watch.exp.name || watch.exp.toString()) + : watch.exp; + logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); + watchLog[logIdx].push(logMsg); + } + } else if (watch === lastDirtyWatch) { + // If the most recently dirty watcher is now clean, short circuit since the remaining watchers + // have already been tested. + dirty = false; + break traverseScopesLoop; } } } catch (e) { + clearPhase(); $exceptionHandler(e); } } @@ -17365,39 +22313,54 @@ function $RootScopeProvider(){ // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { + if (!(next = (current.$$childHead || + (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); - if(dirty && !(ttl--)) { + // `break traverseScopesLoop;` takes us to here + + if((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); - throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + - 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\n' + + 'Watchers fired in the last 5 iterations: {1}', + TTL, toJson(watchLog)); } + } while (dirty || asyncQueue.length); clearPhase(); + + while(postDigestQueue.length) { + try { + postDigestQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } + } }, /** * @ngdoc event - * @name ng.$rootScope.Scope#$destroy - * @eventOf ng.$rootScope.Scope + * @name $rootScope.Scope#$destroy * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. */ /** - * @ngdoc function - * @name ng.$rootScope.Scope#$destroy - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$destroy + * @kind function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies @@ -17409,54 +22372,78 @@ function $RootScopeProvider(){ * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * - * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. - * Application code can register a `$destroy` event handler that will give it chance to + * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. + * Application code can register a `$destroy` event handler that will give it a chance to * perform any necessary cleanup. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed - if ($rootScope == this || this.$$destroyed) return; + if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; + if (this === $rootScope) return; + forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); + + // sever all the references to parent scopes (after this cleanup, the current scope should + // not be retained by any of our references and should be eligible for garbage collection) if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; - // This is bogus code that works around Chrome's GC leak - // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + + // All of the code below is bogus code that works around V8's memory leak via optimized code + // and inline caches. + // + // see: + // - https://code.google.com/p/v8/issues/detail?id=2073#c26 + // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 + // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = null; + this.$$childTail = this.$root = null; + + // don't reset these to null in case some async task tries to register a listener/watch/task + this.$$listeners = {}; + this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = []; + + // prevent NPEs since these methods have references to properties we nulled out + this.$destroy = this.$digest = this.$apply = noop; + this.$on = this.$watch = function() { return noop; }; }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$eval - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$eval + * @kind function * * @description - * Executes the `expression` on the current scope returning the result. Any exceptions in the - * expression are propagated (uncaught). This is useful when evaluating Angular expressions. + * Executes the `expression` on the current scope and returns the result. Any exceptions in + * the expression are propagated (uncaught). This is useful when evaluating Angular + * expressions. * * # Example - *
    +       * ```js
                var scope = ng.$rootScope.Scope();
                scope.a = 1;
                scope.b = 2;
     
                expect(scope.$eval('a+b')).toEqual(3);
                expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
    -       * 
    + * ``` * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { @@ -17464,50 +22451,68 @@ function $RootScopeProvider(){ }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$evalAsync - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$evalAsync + * @kind function * * @description * Executes the expression on the current scope at a later point in time. * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only + * that: * - * - it will execute in the current script execution context (before any DOM rendering). + * - it will execute after the function that scheduled the evaluation (preferably before DOM + * rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * + * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle + * will be scheduled. However, it is encouraged to always call code that changes the model + * from within an `$apply` call. That includes code evaluated via `$evalAsync`. + * * @param {(string|function())=} expression An angular expression to be executed. * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { - this.$$asyncQueue.push(expr); + // if we are outside of an $digest loop and this is the first time we are scheduling async + // task also schedule async auto-flush + if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { + $browser.defer(function() { + if ($rootScope.$$asyncQueue.length) { + $rootScope.$digest(); + } + }); + } + + this.$$asyncQueue.push({scope: this, expression: expr}); + }, + + $$postDigest : function(fn) { + this.$$postDigestQueue.push(fn); }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$apply - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$apply + * @kind function * * @description - * `$apply()` is used to execute an expression in angular from outside of the angular framework. - * (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life-cycle - * of {@link ng.$exceptionHandler exception handling}, + * `$apply()` is used to execute an expression in angular from outside of the angular + * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). + * Because we are calling into the angular framework we need to perform proper scope life + * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` - *
    +       * ```js
                function $apply(expr) {
                  try {
                    return $eval(expr);
    @@ -17517,7 +22522,7 @@ function $RootScopeProvider(){
                    $root.$digest();
                  }
                }
    -       * 
    + * ``` * * * Scope's `$apply()` method transitions through the following stages: @@ -17526,8 +22531,8 @@ function $RootScopeProvider(){ * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression - * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the + * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. @@ -17555,28 +22560,29 @@ function $RootScopeProvider(){ }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$on - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$on + * @kind function * * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of - * event life cycle. + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for + * discussion of event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or + * `$broadcast`-ed. * - `currentScope` - `{Scope}`: the current scope which is handling the event. - * - `name` - `{string}`: Name of the event. - * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event - * propagation (available only for events that were `$emit`-ed). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. + * - `name` - `{string}`: name of the event. + * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel + * further event propagation (available only for events that were `$emit`-ed). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag + * to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. - * @param {function(event, args...)} listener Function to call when the event is emitted. + * @param {function(event, ...args)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { @@ -17586,33 +22592,43 @@ function $RootScopeProvider(){ } namedListeners.push(listener); + var current = this; + do { + if (!current.$$listenerCount[name]) { + current.$$listenerCount[name] = 0; + } + current.$$listenerCount[name]++; + } while ((current = current.$parent)); + + var self = this; return function() { namedListeners[indexOf(namedListeners, listener)] = null; + decrementListenerCount(self, 1, name); }; }, /** - * @ngdoc function - * @name ng.$rootScope.Scope#$emit - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$emit + * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. - * Afterwards, the event traverses upwards toward the root scope and calls all registered - * listeners along the way. The event will stop propagating if one of the listeners cancels it. + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event traverses upwards toward the root scope and calls all + * registered listeners along the way. The event will stop propagating if one of the listeners + * cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. - * @param {...*} args Optional set of arguments which will be passed onto the event listeners. - * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). */ $emit: function(name, args) { var empty = [], @@ -17644,12 +22660,14 @@ function $RootScopeProvider(){ continue; } try { + //allow all listeners attached to the current scope to run namedListeners[i].apply(null, listenerArgs); - if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } + //if any listener on the current scope stops propagation, prevent bubbling + if (stopPropagation) return event; //traverse upwards scope = scope.$parent; } while (scope); @@ -17659,25 +22677,24 @@ function $RootScopeProvider(){ /** - * @ngdoc function - * @name ng.$rootScope.Scope#$broadcast - * @methodOf ng.$rootScope.Scope - * @function + * @ngdoc method + * @name $rootScope.Scope#$broadcast + * @kind function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. - * Afterwards, the event propagates to all direct and indirect scopes of the current scope and - * calls all registered listeners along the way. The event cannot be canceled. + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event propagates to all direct and indirect scopes of the current + * scope and calls all registered listeners along the way. The event cannot be canceled. * - * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. - * @param {...*} args Optional set of arguments which will be passed onto the event listeners. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { @@ -17696,8 +22713,7 @@ function $RootScopeProvider(){ listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root - do { - current = next; + while ((current = next)) { event.currentScope = current; listeners = current.$$listeners[name] || []; for (i=0, length = listeners.length; i 7), - hasEvent: function(event) { - // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have - // it. In particular the event is not fired when backspace or delete key are pressed or - // when cut operation is performed. - if (event == 'input' && msie == 9) return false; - - if (isUndefined(eventSupport[event])) { - var divElm = $window.document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } - - return eventSupport[event]; - }, - // TODO(i): currently there is no way to feature detect CSP without triggering alerts - csp: false - }; - }]; -} - -/** - * @ngdoc object - * @name ng.$window - * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overriden, removed or mocked for testing. - * - * All expressions are evaluated with respect to current scope so they don't - * suffer from window globality. - * - * @example - - - -
    - - -
    -
    - - it('should display the greeting in the input box', function() { - input('greeting').enter('Hello, E2E Tests'); - // If we click the button it will block the test runner - // element(':button').click(); - }); - -
    - */ -function $WindowProvider(){ - this.$get = valueFn(window); -} - -/** - * Parse headers into key value object - * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object - */ -function parseHeaders(headers) { - var parsed = {}, key, val, i; - - if (!headers) return parsed; - - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); - - if (key) { - if (parsed[key]) { - parsed[key] += ', ' + val; - } else { - parsed[key] = val; - } - } - }); - - return parsed; -} - - -/** - * Returns a function that provides access to parsed headers. - * - * Headers are lazy parsed when first requested. - * @see parseHeaders - * - * @param {(string|Object)} headers Headers to provide access to. - * @returns {function(string=)} Returns a getter function which if called with: - * - * - if called with single an argument returns a single header value or null - * - if called with no arguments returns an object containing all headers. - */ -function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; - - return function(name) { - if (!headersObj) headersObj = parseHeaders(headers); - - if (name) { - return headersObj[lowercase(name)] || null; - } - - return headersObj; - }; -} - - -/** - * Chain all given functions - * - * This function is used for both request and response transforming - * - * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. - * @param {(function|Array.)} fns Function or an array of functions. - * @returns {*} Transformed data. - */ -function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); - - forEach(fns, function(fn) { - data = fn(data, headers); - }); - - return data; -} - - -function isSuccess(status) { - return 200 <= status && status < 300; -} - + function decrementListenerCount(current, count, name) { + do { + current.$$listenerCount[name] -= count; -function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/; + if (current.$$listenerCount[name] === 0) { + delete current.$$listenerCount[name]; + } + } while ((current = current.$parent)); + } - var $config = this.defaults = { - // transform incoming response data - transformResponse: [function(data) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - if (JSON_START.test(data) && JSON_END.test(data)) - data = fromJson(data, true); - } - return data; - }], + /** + * function used as an initial value for watchers. + * because it's unique we can easily tell it apart from other values + */ + function initWatchVal() {} + }]; +} - // transform outgoing request data - transformRequest: [function(d) { - return isObject(d) && !isFile(d) ? toJson(d) : d; - }], +/** + * @description + * Private service to sanitize uris for links and images. Used by $compile and $sanitize. + */ +function $$SanitizeUriProvider() { + var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, + imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; - // default headers - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'X-Requested-With': 'XMLHttpRequest' - }, - post: {'Content-Type': 'application/json;charset=utf-8'}, - put: {'Content-Type': 'application/json;charset=utf-8'} + /** + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during a[href] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + aHrefSanitizationWhitelist = regexp; + return this; } + return aHrefSanitizationWhitelist; }; - var providerResponseInterceptors = this.responseInterceptors = []; - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { + /** + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.imgSrcSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + imgSrcSanitizationWhitelist = regexp; + return this; + } + return imgSrcSanitizationWhitelist; + }; - var defaultCache = $cacheFactory('$http'), - responseInterceptors = []; + this.$get = function() { + return function sanitizeUri(uri, isImage) { + var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; + var normalizedVal; + // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. + if (!msie || msie >= 8 ) { + normalizedVal = urlResolve(uri).href; + if (normalizedVal !== '' && !normalizedVal.match(regex)) { + return 'unsafe:'+normalizedVal; + } + } + return uri; + }; + }; +} - forEach(providerResponseInterceptors, function(interceptor) { - responseInterceptors.push( - isString(interceptor) - ? $injector.get(interceptor) - : $injector.invoke(interceptor) - ); - }); +var $sceMinErr = minErr('$sce'); +var SCE_CONTEXTS = { + HTML: 'html', + CSS: 'css', + URL: 'url', + // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a + // url. (e.g. ng-include, script src, templateUrl) + RESOURCE_URL: 'resourceUrl', + JS: 'js' +}; - /** - * @ngdoc function - * @name ng.$http - * @requires $httpBackend - * @requires $browser - * @requires $cacheFactory - * @requires $rootScope - * @requires $q - * @requires $injector - * - * @description - * The `$http` service is a core Angular service that facilitates communication with the remote - * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest - * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. - * - * For unit testing applications that use `$http` service, see - * {@link ngMock.$httpBackend $httpBackend mock}. - * - * For a higher level of abstraction, please check out the {@link ngResource.$resource - * $resource} service. - * - * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by - * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage - * it is important to familiarize yourself with these APIs and the guarantees they provide. - * - * - * # General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. - * - *
    -     *   $http({method: 'GET', url: '/someUrl'}).
    -     *     success(function(data, status, headers, config) {
    -     *       // this callback will be called asynchronously
    -     *       // when the response is available
    -     *     }).
    -     *     error(function(data, status, headers, config) {
    -     *       // called asynchronously if an error occurs
    -     *       // or server returns response with an error status.
    -     *     });
    -     * 
    - * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. - * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. - * - * # Shortcut methods - * - * Since all invocations of the $http service require passing in an HTTP method and URL, and - * POST/PUT requests require request data to be provided as well, shortcut methods - * were created: - * - *
    -     *   $http.get('/someUrl').success(successCallback);
    -     *   $http.post('/someUrl', data).success(successCallback);
    -     * 
    - * - * Complete list of shortcut methods: - * - * - {@link ng.$http#get $http.get} - * - {@link ng.$http#head $http.head} - * - {@link ng.$http#post $http.post} - * - {@link ng.$http#put $http.put} - * - {@link ng.$http#delete $http.delete} - * - {@link ng.$http#jsonp $http.jsonp} - * - * - * # Setting HTTP Headers - * - * The $http service will automatically add certain HTTP headers to all requests. These defaults - * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration - * object, which currently contains this default configuration: - * - * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` - * - `X-Requested-With: XMLHttpRequest` - * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) - * - `Content-Type: application/json` - * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) - * - `Content-Type: application/json` - * - * To add or overwrite these defaults, simply add or remove a property from these configuration - * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object - * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get['My-Header']='value'`. - * - * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same - * fashion. - * - * - * # Transforming Requests and Responses - * - * Both requests and responses can be transformed using transform functions. By default, Angular - * applies these transformations: - * - * Request transformations: - * - * - If the `data` property of the request configuration object contains an object, serialize it into - * JSON format. - * - * Response transformations: - * - * - If XSRF prefix is detected, strip it (see Security Considerations section below). - * - If JSON response is detected, deserialize it using a JSON parser. - * - * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and - * `$httpProvider.defaults.transformResponse` properties. These properties are by default an - * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the - * transformation chain. You can also decide to completely override any default transformations by assigning your - * transformation functions to these properties directly without the array wrapper. - * - * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or - * `transformResponse` properties of the configuration object passed into `$http`. - * - * - * # Caching - * - * To enable caching, set the configuration property `cache` to `true`. When the cache is - * enabled, `$http` stores the response from the server in local cache. Next time the - * response is served from the cache without sending a request to the server. - * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. - * - * If there are multiple GET requests for the same URL that should be cached using the same - * cache, but the cache is not populated yet, only one request to the server will be made and - * the remaining requests will be fulfilled using the response from the first request. - * - * - * # Response interceptors - * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. - * - * For purposes of global error handling, authentication or any kind of synchronous or - * asynchronous preprocessing of received responses, it is desirable to be able to intercept - * responses for http requests before they are handed over to the application code that - * initiated these requests. The response interceptors leverage the {@link ng.$q - * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. - * - * The interceptors are service factories that are registered with the $httpProvider by - * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor — a function that - * takes a {@link ng.$q promise} and returns the original or a new promise. - * - *
    -     *   // register the interceptor as a service
    -     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    -     *     return function(promise) {
    -     *       return promise.then(function(response) {
    -     *         // do something on success
    -     *       }, function(response) {
    -     *         // do something on error
    -     *         if (canRecover(response)) {
    -     *           return responseOrNewPromise
    -     *         }
    -     *         return $q.reject(response);
    -     *       });
    -     *     }
    -     *   });
    -     *
    -     *   $httpProvider.responseInterceptors.push('myHttpInterceptor');
    -     *
    -     *
    -     *   // register the interceptor via an anonymous factory
    -     *   $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
    -     *     return function(promise) {
    -     *       // same as above
    -     *     }
    -     *   });
    -     * 
    - * - * - * # Security Considerations - * - * When designing web applications, consider security threats from: - * - * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} - * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} - * - * Both server and the client must cooperate in order to eliminate these threats. Angular comes - * pre-configured with strategies that address these issues, but for this to work backend server - * cooperation is required. - * - * ## JSON Vulnerability Protection - * - * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} allows third party website to turn your JSON resource URL into - * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To - * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. - * - * For example if your server needs to return: - *
    -     * ['one','two']
    -     * 
    - * - * which is vulnerable to attack, your server can return: - *
    -     * )]}',
    -     * ['one','two']
    -     * 
    - * - * Angular will strip the prefix, before processing the JSON. - * - * - * ## Cross Site Request Forgery (XSRF) Protection - * - * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that - * runs on your domain could read the cookie, your server can be assured that the XHR came from - * JavaScript running on your domain. - * - * To take advantage of this, your server needs to set a token in a JavaScript readable session - * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the - * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure - * that only JavaScript running on your domain could have sent the request. The token must be - * unique for each user and must be verifiable by the server (to prevent the JavaScript from making - * up its own tokens). We recommend that the token is a digest of your site's authentication - * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. - * +// Helper functions follow. + +// Copied from: +// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 +// Prereq: s is a string. +function escapeForRegexp(s) { + return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) { + throw $sceMinErr('iwcard', + 'Illegal sequence *** in string matcher. String: {0}', matcher); + } + matcher = escapeForRegexp(matcher). + replace('\\*\\*', '.*'). + replace('\\*', '[^:/.?&;]*'); + return new RegExp('^' + matcher + '$'); + } else if (isRegExp(matcher)) { + // The only other type of matcher allowed is a Regexp. + // Match entire URL / disallow partial matches. + // Flags are reset (i.e. no global, ignoreCase or multiline) + return new RegExp('^' + matcher.source + '$'); + } else { + throw $sceMinErr('imatcher', + 'Matchers may only be "self", string patterns or RegExp objects'); + } +} + + +function adjustMatchers(matchers) { + var adjustedMatchers = []; + if (isDefined(matchers)) { + forEach(matchers, function(matcher) { + adjustedMatchers.push(adjustMatcher(matcher)); + }); + } + return adjustedMatchers; +} + + +/** + * @ngdoc service + * @name $sceDelegate + * @kind function + * + * @description + * + * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict + * Contextual Escaping (SCE)} services to AngularJS. + * + * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of + * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is + * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to + * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things + * work because `$sce` delegates to `$sceDelegate` for these operations. + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. + * + * The default instance of `$sceDelegate` should work out of the box with little pain. While you + * can override it completely to change the behavior of `$sce`, the common case would + * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting + * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as + * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist + * $sceDelegateProvider.resourceUrlWhitelist} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + */ + +/** + * @ngdoc provider + * @name $sceDelegateProvider + * @description + * + * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate + * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure + * that the URLs used for sourcing Angular templates are safe. Refer {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and + * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + * + * For the general details about this service in Angular, read the main page for {@link ng.$sce + * Strict Contextual Escaping (SCE)}. + * + * **Example**: Consider the following case. + * + * - your app is hosted at url `http://myapp.example.com/` + * - but some of your templates are hosted on other domains you control such as + * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc. + * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. + * + * Here is what a secure configuration for this scenario might look like: + * + * ``` + * angular.module('myApp', []).config(function($sceDelegateProvider) { + * $sceDelegateProvider.resourceUrlWhitelist([ + * // Allow same origin resource loads. + * 'self', + * // Allow loading from our assets domain. Notice the difference between * and **. + * 'http://srv*.assets.example.com/**' + * ]); + * + * // The blacklist overrides the whitelist so the open redirect here is blocked. + * $sceDelegateProvider.resourceUrlBlacklist([ + * 'http://myapp.example.com/clickThru**' + * ]); + * }); + * ``` + */ + +function $SceDelegateProvider() { + this.SCE_CONTEXTS = SCE_CONTEXTS; + + // Resource URLs can also be trusted by policy. + var resourceUrlWhitelist = ['self'], + resourceUrlBlacklist = []; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function + * + * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * Note: **an empty whitelist array will block all URLs**! + * + * @return {Array} the currently set whitelist array. + * + * The **default value** when no whitelist has been explicitly set is `['self']` allowing only + * same origin resource requests. + * + * @description + * Sets/Gets the whitelist of trusted resource URLs. + */ + this.resourceUrlWhitelist = function (value) { + if (arguments.length) { + resourceUrlWhitelist = adjustMatchers(value); + } + return resourceUrlWhitelist; + }; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlBlacklist + * @kind function + * + * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * The typical usage for the blacklist is to **block + * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as + * these would otherwise be trusted but actually return content from the redirected domain. + * + * Finally, **the blacklist overrides the whitelist** and has the final say. + * + * @return {Array} the currently set blacklist array. + * + * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there + * is no blacklist.) + * + * @description + * Sets/Gets the blacklist of trusted resource URLs. + */ + + this.resourceUrlBlacklist = function (value) { + if (arguments.length) { + resourceUrlBlacklist = adjustMatchers(value); + } + return resourceUrlBlacklist; + }; + + this.$get = ['$injector', function($injector) { + + var htmlSanitizer = function htmlSanitizer(html) { + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + }; + + if ($injector.has('$sanitize')) { + htmlSanitizer = $injector.get('$sanitize'); + } + + + function matchUrl(matcher, parsedUrl) { + if (matcher === 'self') { + return urlIsSameOrigin(parsedUrl); + } else { + // definitely a regex. See adjustMatchers() + return !!matcher.exec(parsedUrl.href); + } + } + + function isResourceUrlAllowedByPolicy(url) { + var parsedUrl = urlResolve(url.toString()); + var i, n, allowed = false; + // Ensure that at least one item from the whitelist allows this url. + for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { + if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { + allowed = true; + break; + } + } + if (allowed) { + // Ensure that no item from the blacklist blocked this url. + for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { + if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { + allowed = false; + break; + } + } + } + return allowed; + } + + function generateHolderType(Base) { + var holderType = function TrustedValueHolderType(trustedValue) { + this.$$unwrapTrustedValue = function() { + return trustedValue; + }; + }; + if (Base) { + holderType.prototype = new Base(); + } + holderType.prototype.valueOf = function sceValueOf() { + return this.$$unwrapTrustedValue(); + }; + holderType.prototype.toString = function sceToString() { + return this.$$unwrapTrustedValue().toString(); + }; + return holderType; + } + + var trustedValueHolderBase = generateHolderType(), + byType = {}; + + byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + + /** + * @ngdoc method + * @name $sceDelegate#trustAs * - * @param {object} config Object describing the request to be made and how it should be - * processed. The object has following properties: + * @description + * Returns an object that is trusted by angular for use in specified strict + * contextual escaping contexts (such as ng-bind-html, ng-include, any src + * attribute interpolation, any dom event binding attribute interpolation + * such as for onclick, etc.) that uses the provided value. + * See {@link ng.$sce $sce} for enabling strict contextual escaping. * - * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned to - * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. - * - **data** – `{string|Object}` – Data to be sent as the request message data. - * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. - * - **transformRequest** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * request body and headers and returns its transformed (typically serialized) version. - * - **transformResponse** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **timeout** – `{number}` – timeout in milliseconds. - * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the - * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 - * requests with credentials} for more information. + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resourceUrl, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + function trustAs(type, trustedValue) { + var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (!Constructor) { + throw $sceMinErr('icontext', + 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', + type, trustedValue); + } + if (trustedValue === null || trustedValue === undefined || trustedValue === '') { + return trustedValue; + } + // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting + // mutable objects, we ensure here that the value passed in is actually a string. + if (typeof trustedValue !== 'string') { + throw $sceMinErr('itype', + 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', + type); + } + return new Constructor(trustedValue); + } + + /** + * @ngdoc method + * @name $sceDelegate#valueOf * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: + * @description + * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. * - * - **data** – `{string|Object}` – The response body transformed with the transform functions. - * - **status** – `{number}` – HTTP status code of the response. - * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. + * If the passed parameter is not a value that had been returned by {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. * - * @property {Array.} pendingRequests Array of config objects for currently pending - * requests. This is primarily meant to be used for debugging purposes. + * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} + * call or anything else. + * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns + * `value` unchanged. + */ + function valueOf(maybeTrusted) { + if (maybeTrusted instanceof trustedValueHolderBase) { + return maybeTrusted.$$unwrapTrustedValue(); + } else { + return maybeTrusted; + } + } + + /** + * @ngdoc method + * @name $sceDelegate#getTrusted * + * @description + * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and + * returns the originally supplied value if the queried context type is a supertype of the + * created type. If this condition isn't satisfied, throws an exception. * - * @example - - -
    - - -
    - - - -
    http status code: {{status}}
    -
    http response data: {{data}}
    -
    -
    - - function FetchCtrl($scope, $http, $templateCache) { - $scope.method = 'GET'; - $scope.url = 'http-hello.html'; - - $scope.fetch = function() { - $scope.code = null; - $scope.response = null; - - $http({method: $scope.method, url: $scope.url, cache: $templateCache}). - success(function(data, status) { - $scope.status = status; - $scope.data = data; - }). - error(function(data, status) { - $scope.data = data || "Request failed"; - $scope.status = status; - }); - }; + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} call. + * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. + */ + function getTrusted(type, maybeTrusted) { + if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { + return maybeTrusted; + } + var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (constructor && maybeTrusted instanceof constructor) { + return maybeTrusted.$$unwrapTrustedValue(); + } + // If we get here, then we may only take one of two actions. + // 1. sanitize the value for the requested type, or + // 2. throw an exception. + if (type === SCE_CONTEXTS.RESOURCE_URL) { + if (isResourceUrlAllowedByPolicy(maybeTrusted)) { + return maybeTrusted; + } else { + throw $sceMinErr('insecurl', + 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', + maybeTrusted.toString()); + } + } else if (type === SCE_CONTEXTS.HTML) { + return htmlSanitizer(maybeTrusted); + } + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + } - $scope.updateModel = function(method, url) { - $scope.method = method; - $scope.url = url; - }; - } - - - Hello, $http! - - - it('should make an xhr GET request', function() { - element(':button:contains("Sample GET")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Hello, \$http!/); - }); + return { trustAs: trustAs, + getTrusted: getTrusted, + valueOf: valueOf }; + }]; +} - it('should make a JSONP request to angularjs.org', function() { - element(':button:contains("Sample JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Super Hero!/); - }); - it('should make JSONP request to invalid URL and invoke the error handler', - function() { - element(':button:contains("Invalid JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('0'); - expect(binding('data')).toBe('Request failed'); - }); - -
    - */ - function $http(config) { - config.method = uppercase(config.method); +/** + * @ngdoc provider + * @name $sceProvider + * @description + * + * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. + * - enable/disable Strict Contextual Escaping (SCE) in a module + * - override the default implementation with a custom delegate + * + * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. + */ - var reqTransformFn = config.transformRequest || $config.transformRequest, - respTransformFn = config.transformResponse || $config.transformResponse, - defHeaders = $config.headers, - reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, - defHeaders.common, defHeaders[lowercase(config.method)], config.headers), - reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), - promise; - - // strip content-type if data is undefined - if (isUndefined(config.data)) { - delete reqHeaders['Content-Type']; - } +/* jshint maxlen: false*/ - // send request - promise = sendReq(config, reqData, reqHeaders); +/** + * @ngdoc service + * @name $sce + * @kind function + * + * @description + * + * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. + * + * # Strict Contextual Escaping + * + * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain + * contexts to result in a value that is marked as safe to use for that context. One example of + * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer + * to these contexts as privileged or SCE contexts. + * + * As of version 1.2, Angular ships with SCE enabled by default. + * + * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows + * one to execute arbitrary javascript by the use of the expression() syntax. Refer + * to learn more about them. + * You can ensure your document is in standards mode and not quirks mode by adding `` + * to the top of your HTML document. + * + * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for + * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * + * Here's an example of a binding in a privileged context: + * + * ``` + * + *
    + * ``` + * + * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE + * disabled, this application allows the user to render arbitrary HTML into the DIV. + * In a more realistic example, one may be rendering user comments, blog articles, etc. via + * bindings. (HTML is just one example of a context where rendering user controlled input creates + * security vulnerabilities.) + * + * For the case of HTML, you might use a library, either on the client side, or on the server side, + * to sanitize unsafe HTML before binding to the value and rendering it in the document. + * + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some + * properties/fields and forgot to update the binding to the sanitized value? + * + * To be secure by default, you want to ensure that any such bindings are disallowed unless you can + * determine that something explicitly says it's safe to use a value for binding in that + * context. You can then audit your code (a simple grep would do) to ensure that this is only done + * for those values that you can easily tell are safe - because they were received from your server, + * sanitized by your library, etc. You can organize your codebase to help with this - perhaps + * allowing only the files in a specific directory to do this. Ensuring that the internal API + * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. + * + * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} + * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to + * obtain values that will be accepted by SCE / privileged contexts. + * + * + * ## How does it work? + * + * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted + * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link + * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the + * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. + * + * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link + * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly + * simplified): + * + * ``` + * var ngBindHtmlDirective = ['$sce', function($sce) { + * return function(scope, element, attr) { + * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { + * element.html(value || ''); + * }); + * }; + * }]; + * ``` + * + * ## Impact on loading templates + * + * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as + * `templateUrl`'s specified by {@link guide/directive directives}. + * + * By default, Angular only loads templates from the same domain and protocol as the application + * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or + * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist + * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * + * *Please note*: + * The browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. + * + * ## This feels like too much overhead for the developer? + * + * It's important to remember that SCE only applies to interpolation expressions. + * + * If your expressions are constant literals, they're automatically trusted and you don't need to + * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. + * `
    `) just works. + * + * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them + * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. + * + * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load + * templates in `ng-include` from your application's domain without having to even know about SCE. + * It blocks loading templates from other domains or loading templates over http from an https + * served document. You can change these by setting your own custom {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * + * This significantly reduces the overhead. It is far easier to pay the small overhead and have an + * application that's secure and can be audited to verify that with much more ease than bolting + * security onto an application later. + * + * + * ## What trusted context types are supported? + * + * | Context | Notes | + * |---------------------|----------------| + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | + * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | + * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
    Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | + * + * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
    + * + * Each element in these arrays must be one of the following: + * + * - **'self'** + * - The special **string**, `'self'`, can be used to match against all URLs of the **same + * domain** as the application document using the **same protocol**. + * - **String** (except the special value `'self'`) + * - The string is matched against the full *normalized / absolute URL* of the resource + * being tested (substring matches are not good enough.) + * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters + * match themselves. + * - `*`: matches zero or more occurrences of any character other than one of the following 6 + * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use + * in a whitelist. + * - `**`: matches zero or more occurrences of *any* character. As such, it's not + * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. + * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might + * not have been the intention.) Its usage at the very end of the path is ok. (e.g. + * http://foo.example.com/templates/**). + * - **RegExp** (*see caveat below*) + * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax + * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to + * accidentally introduce a bug when one updates a complex expression (imho, all regexes should + * have good test coverage.). For instance, the use of `.` in the regex is correct only in a + * small number of cases. A `.` character in the regex used when matching the scheme or a + * subdomain could be matched against a `:` or literal `.` that was likely not intended. It + * is highly recommended to use the string patterns and only fall back to regular expressions + * if they as a last resort. + * - The regular expression must be an instance of RegExp (i.e. not a string.) It is + * matched against the **entire** *normalized / absolute URL* of the resource being tested + * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags + * present on the RegExp (such as multiline, global, ignoreCase) are ignored. + * - If you are generating your JavaScript from some other templating engine (not + * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), + * remember to escape your regular expression (and be aware that you might need more than + * one level of escaping depending on your templating engine and the way you interpolated + * the value.) Do make use of your platform's escaping mechanism as it might be good + * enough before coding your own. e.g. Ruby has + * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) + * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). + * Javascript lacks a similar built in function for escaping. Take a look at Google + * Closure library's [goog.string.regExpEscape(s)]( + * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. + * + * ## Show me an example using SCE. + * + * + * + *
    + *

    + * User comments
    + * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when + * $sanitize is available. If $sanitize isn't available, this results in an error instead of an + * exploit. + *
    + *
    + * {{userComment.name}}: + * + *
    + *
    + *
    + *
    + *
    + * + * + * var mySceApp = angular.module('mySceApp', ['ngSanitize']); + * + * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { + * var self = this; + * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { + * self.userComments = userComments; + * }); + * self.explicitlyTrustedHtml = $sce.trustAsHtml( + * 'Hover over this text.'); + * }); + * + * + * + * [ + * { "name": "Alice", + * "htmlComment": + * "Is anyone reading this?" + * }, + * { "name": "Bob", + * "htmlComment": "Yes! Am I the only other one?" + * } + * ] + * + * + * + * describe('SCE doc demo', function() { + * it('should sanitize untrusted values', function() { + * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) + * .toBe('Is anyone reading this?'); + * }); + * + * it('should NOT sanitize explicitly trusted values', function() { + * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( + * 'Hover over this text.'); + * }); + * }); + * + *
    + * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * for little coding overhead. It will be much harder to take an SCE disabled application and + * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE + * for cases where you have a lot of existing code that was written before SCE was introduced and + * you're migrating them a module at a time. + * + * That said, here's how you can completely disable SCE: + * + * ``` + * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { + * // Completely disable SCE. For demonstration purposes only! + * // Do not use in new projects. + * $sceProvider.enabled(false); + * }); + * ``` + * + */ +/* jshint maxlen: 100 */ +function $SceProvider() { + var enabled = true; - // transform future response - promise = promise.then(transformResponse, transformResponse); + /** + * @ngdoc method + * @name $sceProvider#enabled + * @kind function + * + * @param {boolean=} value If provided, then enables/disables SCE. + * @return {boolean} true if SCE is enabled, false otherwise. + * + * @description + * Enables/disables SCE and returns the current value. + */ + this.enabled = function (value) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; - // apply interceptors - forEach(responseInterceptors, function(interceptor) { - promise = interceptor(promise); - }); - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * This function should return the a value that is safe to use in the context specified by + * contextEnum or throw and exception otherwise. + * + * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be + * opaque or wrapped in some holder object. That happens to be an implementation detail. For + * instance, an implementation could maintain a registry of all trusted objects by context. In + * such a case, trustAs() would return the same object that was passed in. getTrusted() would + * return the same object passed in if it was found in the registry under a compatible context or + * throw an exception otherwise. An implementation might only wrap values some of the time based + * on some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) + * will also succeed. + * + * Inheritance happens to capture this in a natural way. In some future, we + * may not use inheritance anymore. That is OK because no code outside of + * sce.js and sceSpecs.js would need to be aware of this detail. + */ - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; + this.$get = ['$parse', '$sniffer', '$sceDelegate', function( + $parse, $sniffer, $sceDelegate) { + // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows + // the "expression(javascript expression)" syntax which is insecure. + if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { + throw $sceMinErr('iequirks', + 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + + 'mode. You can fix this by adding the text to the top of your HTML ' + + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + } - return promise; + var sce = shallowCopy(SCE_CONTEXTS); - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response, { - data: transformData(response.data, response.headers, respTransformFn) - }); - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); - } - } + /** + * @ngdoc method + * @name $sce#isEnabled + * @kind function + * + * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * + * @description + * Returns a boolean indicating if SCE is enabled. + */ + sce.isEnabled = function () { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; - $http.pendingRequests = []; + if (!enabled) { + sce.trustAs = sce.getTrusted = function(type, value) { return value; }; + sce.valueOf = identity; + } /** * @ngdoc method - * @name ng.$http#get - * @methodOf ng.$http + * @name $sce#parseAs * * @description - * Shortcut method to perform `GET` request. + * Converts Angular {@link guide/expression expression} into a function. This is like {@link + * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it + * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, + * *result*)} * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {string} type The kind of SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return function sceParseAsTrusted(self, locals) { + return sce.getTrusted(type, parsed(self, locals)); + }; + } + }; /** * @ngdoc method - * @name ng.$http#delete - * @methodOf ng.$http + * @name $sce#trustAs * * @description - * Shortcut method to perform `DELETE` request. + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, + * returns an object that is trusted by angular for use in specified strict contextual + * escaping contexts (such as ng-bind-html, ng-include, any src attribute + * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) + * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual + * escaping. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resource_url, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. */ /** * @ngdoc method - * @name ng.$http#head - * @methodOf ng.$http + * @name $sce#trustAsHtml * * @description - * Shortcut method to perform `HEAD` request. + * Shorthand method. `$sce.trustAsHtml(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml + * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method - * @name ng.$http#jsonp - * @methodOf ng.$http + * @name $sce#trustAsUrl * * @description - * Shortcut method to perform `JSONP` request. + * Shorthand method. `$sce.trustAsUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} * - * @param {string} url Relative or absolute URL specifying the destination of the request. - * Should contain `JSON_CALLBACK` string. - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl + * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ - createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method - * @name ng.$http#post - * @methodOf ng.$http + * @name $sce#trustAsResourceUrl * * @description - * Shortcut method to perform `POST` request. + * Shorthand method. `$sce.trustAsResourceUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the return + * value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method - * @name ng.$http#put - * @methodOf ng.$http + * @name $sce#trustAsJs * * @description - * Shortcut method to perform `PUT` request. + * Shorthand method. `$sce.trustAsJs(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs + * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ - createShortMethodsWithData('post', 'put'); - - /** - * @ngdoc property - * @name ng.$http#defaults - * @propertyOf ng.$http - * - * @description - * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of - * default headers as well as request and response transformations. - * - * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. - */ - $http.defaults = $config; - - - return $http; - - - function createShortMethods(names) { - forEach(arguments, function(name) { - $http[name] = function(url, config) { - return $http(extend(config || {}, { - method: name, - url: url - })); - }; - }); - } - - - function createShortMethodsWithData(name) { - forEach(arguments, function(name) { - $http[name] = function(url, data, config) { - return $http(extend(config || {}, { - method: name, - url: url, - data: data - })); - }; - }); - } - /** - * Makes the request. + * @ngdoc method + * @name $sce#getTrusted * - * !!! ACCESSES CLOSURE VARS: - * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, + * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the + * originally supplied value if the queried context type is a supertype of the created type. + * If this condition isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} + * call. + * @returns {*} The value the was originally provided to + * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. + * Otherwise, throws an exception. */ - function sendReq(config, reqData, reqHeaders) { - var deferred = $q.defer(), - promise = deferred.promise, - cache, - cachedResp, - url = buildUrl(config.url, config.params); - - $http.pendingRequests.push(config); - promise.then(removePendingReq, removePendingReq); - - - if (config.cache && config.method == 'GET') { - cache = isObject(config.cache) ? config.cache : defaultCache; - } - - if (cache) { - cachedResp = cache.get(url); - if (cachedResp) { - if (cachedResp.then) { - // cached request has already been sent, but there is no response yet - cachedResp.then(removePendingReq, removePendingReq); - return cachedResp; - } else { - // serving from cache - if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); - } else { - resolvePromise(cachedResp, 200, {}); - } - } - } else { - // put the promise for the non-transformed response into cache as a placeholder - cache.put(url, promise); - } - } - - // if we won't have the response in cache, send the request to the backend - if (!cachedResp) { - $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, - config.withCredentials); - } - - return promise; - - - /** - * Callback registered to $httpBackend(): - * - caches the response if desired - * - resolves the raw $http promise - * - calls $apply - */ - function done(status, response, headersString) { - if (cache) { - if (isSuccess(status)) { - cache.put(url, [status, response, parseHeaders(headersString)]); - } else { - // remove promise from the cache - cache.remove(url); - } - } - - resolvePromise(response, status, headersString); - $rootScope.$apply(); - } - - - /** - * Resolves the raw $http promise. - */ - function resolvePromise(response, status, headers) { - // normalize internal statuses to 0 - status = Math.max(status, 0); - - (isSuccess(status) ? deferred.resolve : deferred.reject)({ - data: response, - status: status, - headers: headersGetter(headers), - config: config - }); - } - - - function removePendingReq() { - var idx = indexOf($http.pendingRequests, config); - if (idx !== -1) $http.pendingRequests.splice(idx, 1); - } - } - - - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value == null || value == undefined) return; - if (isObject(value)) { - value = toJson(value); - } - parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); - }); - return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); - } - - - }]; -} - -var XHR = window.XMLHttpRequest || function() { - try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} - try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} - try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} - throw new Error("This browser does not support XMLHttpRequest."); -}; - - -/** - * @ngdoc object - * @name ng.$httpBackend - * @requires $browser - * @requires $window - * @requires $document - * - * @description - * HTTP backend used by the {@link ng.$http service} that delegates to - * XMLHttpRequest object or JSONP and deals with browser incompatibilities. - * - * You should never need to use this service directly, instead use the higher-level abstractions: - * {@link ng.$http $http} or {@link ngResource.$resource $resource}. - * - * During testing this implementation is swapped with {@link ngMock.$httpBackend mock - * $httpBackend} which can be trained with responses. - */ -function $HttpBackendProvider() { - this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { - return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, - $document[0], $window.location.protocol.replace(':', '')); - }]; -} - -function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { - // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials) { - $browser.$$incOutstandingRequestCount(); - url = url || $browser.url(); - - if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - }; - - jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - function() { - if (callbacks[callbackId].data) { - completeRequest(callback, 200, callbacks[callbackId].data); - } else { - completeRequest(callback, -2); - } - delete callbacks[callbackId]; - }); - } else { - var xhr = new XHR(); - xhr.open(method, url, true); - forEach(headers, function(value, key) { - if (value) xhr.setRequestHeader(key, value); - }); - var status; - - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the - // response is in the cache. the promise api will ensure that to the app code the api is - // always async - xhr.onreadystatechange = function() { - if (xhr.readyState == 4) { - var responseHeaders = xhr.getAllResponseHeaders(); - - // TODO(vojta): remove once Firefox 21 gets released. - // begin: workaround to overcome Firefox CORS http response headers bug - // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 - // Firefox already patched in nightly. Should land in Firefox 21. - - // CORS "simple response headers" http://www.w3.org/TR/cors/ - var value, - simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", - "Expires", "Last-Modified", "Pragma"]; - if (!responseHeaders) { - responseHeaders = ""; - forEach(simpleHeaders, function (header) { - var value = xhr.getResponseHeader(header); - if (value) { - responseHeaders += header + ": " + value + "\n"; - } - }); - } - // end of the workaround. - - completeRequest(callback, status || xhr.status, xhr.responseText, - responseHeaders); - } - }; + /** + * @ngdoc method + * @name $sce#getTrustedHtml + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ - if (withCredentials) { - xhr.withCredentials = true; - } + /** + * @ngdoc method + * @name $sce#getTrustedCss + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ - xhr.send(post || ''); + /** + * @ngdoc method + * @name $sce#getTrustedUrl + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ - if (timeout > 0) { - $browserDefer(function() { - status = -1; - xhr.abort(); - }, timeout); - } - } + /** + * @ngdoc method + * @name $sce#getTrustedResourceUrl + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ + /** + * @ngdoc method + * @name $sce#getTrustedJs + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ - function completeRequest(callback, status, response, headersString) { - // URL_MATCH is defined in src/service/location.js - var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; + /** + * @ngdoc method + * @name $sce#parseAsHtml + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - // fix status code for file protocol (it's always 0) - status = (protocol == 'file') ? (response ? 200 : 404) : status; + /** + * @ngdoc method + * @name $sce#parseAsCss + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - // normalize IE bug (http://bugs.jquery.com/ticket/1450) - status = status == 1223 ? 204 : status; + /** + * @ngdoc method + * @name $sce#parseAsUrl + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - callback(status, response, headersString); - $browser.$$completeOutstandingRequest(noop); - } - }; + /** + * @ngdoc method + * @name $sce#parseAsResourceUrl + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - function jsonpReq(url, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: - // - fetches local scripts via XHR and evals them - // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), - doneWrapper = function() { - rawDocument.body.removeChild(script); - if (done) done(); - }; + /** + * @ngdoc method + * @name $sce#parseAsJs + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - script.type = 'text/javascript'; - script.src = url; + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; - if (msie) { - script.onreadystatechange = function() { - if (/loaded|complete/.test(script.readyState)) doneWrapper(); + forEach(SCE_CONTEXTS, function (enumValue, name) { + var lName = lowercase(name); + sce[camelCase("parse_as_" + lName)] = function (expr) { + return parse(enumValue, expr); }; - } else { - script.onload = script.onerror = doneWrapper; - } + sce[camelCase("get_trusted_" + lName)] = function (value) { + return getTrusted(enumValue, value); + }; + sce[camelCase("trust_as_" + lName)] = function (value) { + return trustAs(enumValue, value); + }; + }); - rawDocument.body.appendChild(script); - } + return sce; + }]; } /** - * @ngdoc object - * @name ng.$locale + * !!! This is an undocumented "private" service !!! * - * @description - * $locale service provides localization rules for various Angular components. As of right now the - * only public api is: + * @name $sniffer + * @requires $window + * @requires $document * - * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + * @property {boolean} history Does the browser support html5 history api ? + * @property {boolean} hashchange Does the browser support hashchange event ? + * @property {boolean} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? + * + * @description + * This is very simple implementation of testing browser's features. */ -function $LocaleProvider(){ - this.$get = function() { - return { - id: 'en-us', +function $SnifferProvider() { + this.$get = ['$window', '$document', function($window, $document) { + var eventSupport = {}, + android = + int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + boxee = /Boxee/i.test(($window.navigator || {}).userAgent), + document = $document[0] || {}, + documentMode = document.documentMode, + vendorPrefix, + vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false, + match; + + if (bodyStyle) { + for(var prop in bodyStyle) { + if(match = vendorRegex.exec(prop)) { + vendorPrefix = match[0]; + vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); + break; + } + } - NUMBER_FORMATS: { - DECIMAL_SEP: '.', - GROUP_SEP: ',', - PATTERNS: [ - { // Decimal Pattern - minInt: 1, - minFrac: 0, - maxFrac: 3, - posPre: '', - posSuf: '', - negPre: '-', - negSuf: '', - gSize: 3, - lgSize: 3 - },{ //Currency Pattern - minInt: 1, - minFrac: 2, - maxFrac: 2, - posPre: '\u00A4', - posSuf: '', - negPre: '(\u00A4', - negSuf: ')', - gSize: 3, - lgSize: 3 - } - ], - CURRENCY_SYM: '$' - }, + if(!vendorPrefix) { + vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; + } - DATETIME_FORMATS: { - MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' - .split(','), - SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), - DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), - SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), - AMPMS: ['AM','PM'], - medium: 'MMM d, y h:mm:ss a', - short: 'M/d/yy h:mm a', - fullDate: 'EEEE, MMMM d, y', - longDate: 'MMMM d, y', - mediumDate: 'MMM d, y', - shortDate: 'M/d/yy', - mediumTime: 'h:mm:ss a', - shortTime: 'h:mm a' - }, + transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); + animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); - pluralCat: function(num) { - if (num === 1) { - return 'one'; - } - return 'other'; + if (android && (!transitions||!animations)) { + transitions = isString(document.body.style.webkitTransition); + animations = isString(document.body.style.webkitAnimation); } + } + + + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 + + // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has + // so let's not use the history API also + // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined + // jshint -W018 + history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), + // jshint +W018 + hashchange: 'onhashchange' in $window && + // IE8 compatible mode lies + (!documentMode || documentMode > 7), + hasEvent: function(event) { + // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have + // it. In particular the event is not fired when backspace or delete key are pressed or + // when cut operation is performed. + if (event == 'input' && msie == 9) return false; + + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; + } + + return eventSupport[event]; + }, + csp: csp(), + vendorPrefix: vendorPrefix, + transitions : transitions, + animations : animations, + android: android, + msie : msie, + msieDocumentMode: documentMode }; - }; + }]; } function $TimeoutProvider() { @@ -18844,9 +24018,8 @@ function $TimeoutProvider() { /** - * @ngdoc function - * @name ng.$timeout - * @requires $browser + * @ngdoc service + * @name $timeout * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch @@ -18867,12 +24040,13 @@ function $TimeoutProvider() { * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. + * */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), - timeoutId, cleanup; + timeoutId; timeoutId = $browser.defer(function() { try { @@ -18881,26 +24055,23 @@ function $TimeoutProvider() { deferred.reject(e); $exceptionHandler(e); } + finally { + delete deferreds[promise.$$timeoutId]; + } if (!skipApply) $rootScope.$apply(); }, delay); - cleanup = function() { - delete deferreds[promise.$$timeoutId]; - }; - promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; - promise.then(cleanup, cleanup); return promise; } /** - * @ngdoc function - * @name ng.$timeout#cancel - * @methodOf ng.$timeout + * @ngdoc method + * @name $timeout#cancel * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be @@ -18913,6 +24084,7 @@ function $TimeoutProvider() { timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); + delete deferreds[promise.$$timeoutId]; return $browser.defer.cancel(promise.$$timeoutId); } return false; @@ -18922,16 +24094,175 @@ function $TimeoutProvider() { }]; } +// NOTE: The usage of window and document instead of $window and $document here is +// deliberate. This service depends on the specific behavior of anchor nodes created by the +// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and +// cause us to break tests. In addition, when the browser resolves a URL for XHR, it +// doesn't know about mocked locations and resolves URLs to the real document - which is +// exactly the behavior needed here. There is little value is mocking these out for this +// service. +var urlParsingNode = document.createElement("a"); +var originUrl = urlResolve(window.location.href, true); + + /** - * @ngdoc object - * @name ng.$filterProvider + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * URL will be resolved into an absolute URL in the context of the application document. + * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related + * properties are all populated to reflect the normalized URL. This approach has wide + * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other + * browsers. However, the parsed components will not be set if the URL assigned did not specify + * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We + * work around that by performing the parsing in a 2nd step by taking a previously normalized + * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the + * properties such as protocol, hostname, port, etc. + * + * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one + * uses the inner HTML approach to assign the URL as part of an HTML snippet - + * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. + * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. + * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that + * method and IE < 8 is unsupported. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @kind function + * @param {string} url The URL to be parsed. + * @description Normalizes and parses a URL. + * @returns {object} Returns the normalized URL as a dictionary. + * + * | member name | Description | + * |---------------|----------------| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | protocol | The protocol including the trailing colon | + * | host | The host and port (if the port is non-default) of the normalizedUrl | + * | search | The search params, minus the question mark | + * | hash | The hash string, minus the hash symbol + * | hostname | The hostname + * | port | The port, without ":" + * | pathname | The pathname, beginning with "/" + * + */ +function urlResolve(url, base) { + var href = url; + + if (msie) { + // Normalize before parse. Refer Implementation Notes on why this is + // done in two steps on IE. + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') + ? urlParsingNode.pathname + : '/' + urlParsingNode.pathname + }; +} + +/** + * Parse a request URL and determine whether this is a same-origin request as the application document. + * + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the request is for the same origin as the application document. + */ +function urlIsSameOrigin(requestUrl) { + var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); +} + +/** + * @ngdoc service + * @name $window + * * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In angular we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. * - * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To - * achieve this a filter definition consists of a factory function which is annotated with dependencies and is - * responsible for creating a filter function. + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. * - *
    + * @example
    +   
    +     
    +       
    +       
    + + +
    +
    + + it('should display the greeting in the input box', function() { + element(by.model('greeting')).sendKeys('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
    + */ +function $WindowProvider(){ + this.$get = valueFn(window); +} + +/* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ + +/** + * @ngdoc provider + * @name $filterProvider + * @description + * + * Filters are just functions which transform input to an output. However filters need to be + * Dependency Injected. To achieve this a filter definition consists of a factory function which is + * annotated with dependencies and is responsible for creating a filter function. + * + * ```js * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) @@ -18950,10 +24281,12 @@ function $TimeoutProvider() { * }; * }); * } - *
    + * ``` * - * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. - *
    + * The filter function is registered with the `$injector` under the filter name suffix with
    + * `Filter`.
    + *
    + * ```js
      *   it('should be the same instance', inject(
      *     function($filterProvider) {
      *       $filterProvider.register('reverse', function(){
    @@ -18963,29 +24296,27 @@ function $TimeoutProvider() {
      *     function($filter, reverseFilter) {
      *       expect($filter('reverse')).toBe(reverseFilter);
      *     });
    - * 
    + * ``` * * * For more information about how angular filters work, and how to create your own filters, see - * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer - * Guide. + * {@link guide/filter Filters} in the Angular Developer Guide. */ /** * @ngdoc method - * @name ng.$filterProvider#register - * @methodOf ng.$filterProvider + * @name $filterProvider#register * @description * Register filter factory function. * * @param {String} name Name of the filter. - * @param {function} fn The filter factory function which is injectable. + * @param {Function} fn The filter factory function which is injectable. */ /** - * @ngdoc function - * @name ng.$filter - * @function + * @ngdoc service + * @name $filter + * @kind function * @description * Filters are used for formatting data displayed to the user. * @@ -18995,24 +24326,69 @@ function $TimeoutProvider() { * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function - */ + * @example + + +
    +

    {{ originalText }}

    +

    {{ filteredText }}

    +
    +
    + + + angular.module('filterExample', []) + .controller('MainCtrl', function($scope, $filter) { + $scope.originalText = 'hello'; + $scope.filteredText = $filter('uppercase')($scope.originalText); + }); + +
    + */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; + /** + * @ngdoc method + * @name $controllerProvider#register + * @param {string|Object} name Name of the filter function, or an object map of filters where + * the keys are the filter names and the values are the filter factories. + * @returns {Object} Registered filter instance, or if a map of filters was provided then a map + * of the registered filter instances. + */ function register(name, factory) { - return $provide.factory(name + suffix, factory); + if(isObject(name)) { + var filters = {}; + forEach(name, function(filter, key) { + filters[key] = register(key, filter); + }); + return filters; + } else { + return $provide.factory(name + suffix, factory); + } } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); - } + }; }]; //////////////////////////////////////// + /* global + currencyFilter: false, + dateFilter: false, + filterFilter: false, + jsonFilter: false, + limitToFilter: false, + lowercaseFilter: false, + numberFilter: false, + orderByFilter: false, + uppercaseFilter: false, + */ + register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); @@ -19026,23 +24402,20 @@ function $FilterProvider($provide) { /** * @ngdoc filter - * @name ng.filter:filter - * @function + * @name filter + * @kind function * * @description * Selects a subset of items from `array` and returns it as a new array. * - * Note: This function is used to augment the `Array` type in Angular expressions. See - * {@link ng.$filter} for more information about Angular arrays. - * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * - * - `string`: Predicate that results in a substring match using the value of `expression` - * string. All strings or objects with string properties in `array` that contain this string + * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against + * the contents of the `array`. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained @@ -19052,18 +24425,35 @@ function $FilterProvider($provide) { * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * - * - `function`: A predicate function can be used to write arbitrary filters. The function is + * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * + * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in + * determining if the expected value (from the filter expression) and actual value (from + * the object in the array) should be considered a match. + * + * Can be one of: + * + * - `function(actual, expected)`: + * The function will be given the object value and the predicate value to compare and + * should return true if the item should be included in filtered result. + * + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. + * this is essentially strict comparison of expected and actual. + * + * - `false|undefined`: A short hand for a function which will look for a substring match in case + * insensitive way. + * * @example - - + +
    + {name:'Julie', phone:'555-8765'}, + {name:'Juliette', phone:'555-5678'}]"> Search: @@ -19077,37 +24467,59 @@ function $FilterProvider($provide) { Any:
    Name only
    Phone only
    + Equality
    - - - + + +
    NamePhone
    {{friend.name}}{{friend.phone}}
    {{friendObj.name}}{{friendObj.phone}}
    -
    - - it('should search across all fields when filtering with a string', function() { - input('searchText').enter('m'); - expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Mike', 'Adam']); + + + var expectFriendNames = function(expectedNames, key) { + element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { + arr.forEach(function(wd, i) { + expect(wd.getText()).toMatch(expectedNames[i]); + }); + }); + }; - input('searchText').enter('76'); - expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). - toEqual(['John', 'Julie']); + it('should search across all fields when filtering with a string', function() { + var searchText = element(by.model('searchText')); + searchText.clear(); + searchText.sendKeys('m'); + expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); + + searchText.clear(); + searchText.sendKeys('76'); + expectFriendNames(['John', 'Julie'], 'friend'); }); it('should search in specific fields when filtering with a predicate object', function() { - input('search.$').enter('i'); - expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Mike', 'Julie']); + var searchAny = element(by.model('search.$')); + searchAny.clear(); + searchAny.sendKeys('i'); + expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); + }); + it('should use a equal comparison when comparator is true', function() { + var searchName = element(by.model('search.name')); + var strict = element(by.model('strict')); + searchName.clear(); + searchName.sendKeys('Julie'); + strict.click(); + expectFriendNames(['Julie'], 'friendObj'); }); - -
    + + */ function filterFilter() { - return function(array, expression) { + return function(array, expression, comparator) { if (!isArray(array)) return array; - var predicates = []; + + var comparatorType = typeof(comparator), + predicates = []; + predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { @@ -19116,20 +24528,49 @@ function filterFilter() { } return true; }; + + if (comparatorType !== 'function') { + if (comparatorType === 'boolean' && comparator) { + comparator = function(obj, text) { + return angular.equals(obj, text); + }; + } else { + comparator = function(obj, text) { + if (obj && text && typeof obj === 'object' && typeof text === 'object') { + for (var objKey in obj) { + if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && + comparator(obj[objKey], text[objKey])) { + return true; + } + } + return false; + } + text = (''+text).toLowerCase(); + return (''+obj).toLowerCase().indexOf(text) > -1; + }; + } + } + var search = function(obj, text){ - if (text.charAt(0) === '!') { + if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": - return ('' + obj).toLowerCase().indexOf(text) > -1; + return comparator(obj, text); case "object": - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } + switch (typeof text) { + case "object": + return comparator(obj, text); + default: + for ( var objKey in obj) { + if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { + return true; + } + } + break; } return false; case "array": @@ -19147,27 +24588,18 @@ function filterFilter() { case "boolean": case "number": case "string": + // Set up expression object and fall through expression = {$:expression}; + // jshint -W086 case "object": + // jshint +W086 for (var key in expression) { - if (key == '$') { - (function() { - var text = (''+expression[key]).toLowerCase(); - if (!text) return; - predicates.push(function(value) { - return search(value, text); - }); - })(); - } else { - (function() { - var path = key; - var text = (''+expression[key]).toLowerCase(); - if (!text) return; - predicates.push(function(value) { - return search(getter(value, path), text); - }); - })(); - } + (function(path) { + if (typeof expression[path] === 'undefined') return; + predicates.push(function(value) { + return search(path == '$' ? value : (value && value[path]), expression[path]); + }); + })(key); } break; case 'function': @@ -19184,13 +24616,13 @@ function filterFilter() { } } return filtered; - } + }; } /** * @ngdoc filter - * @name ng.filter:currency - * @function + * @name currency + * @kind function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default @@ -19202,31 +24634,38 @@ function filterFilter() { * * * @example - - + + -
    +

    - default currency symbol ($): {{amount | currency}}
    - custom currency identifier (USD$): {{amount | currency:"USD$"}} + default currency symbol ($): {{amount | currency}}
    + custom currency identifier (USD$): {{amount | currency:"USD$"}}
    - - + + it('should init with 1234.56', function() { - expect(binding('amount | currency')).toBe('$1,234.56'); - expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); + expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); + expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); }); it('should update', function() { - input('amount').enter('-1234'); - expect(binding('amount | currency')).toBe('($1,234.00)'); - expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); + if (browser.params.browser == 'safari') { + // Safari does not understand the minus key. See + // https://github.com/angular/protractor/issues/481 + return; + } + element(by.model('amount')).clear(); + element(by.model('amount')).sendKeys('-1234'); + expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); + expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); }); - - + + */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { @@ -19240,8 +24679,8 @@ function currencyFilter($locale) { /** * @ngdoc filter - * @name ng.filter:number - * @function + * @name number + * @kind function * * @description * Formats a number as text. @@ -19249,39 +24688,43 @@ function currencyFilter($locale) { * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. - * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. + * @param {(number|string)=} fractionSize Number of decimal places to round the number to. + * If this is not provided then the fraction size is computed from the current locale's number + * formatting pattern. In the case of the default locale, it will be 3. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example - - + + -
    +
    Enter number:
    - Default formatting: {{val | number}}
    - No fractions: {{val | number:0}}
    - Negative number: {{-val | number:4}} + Default formatting: {{val | number}}
    + No fractions: {{val | number:0}}
    + Negative number: {{-val | number:4}}
    - - + + it('should format numbers', function() { - expect(binding('val | number')).toBe('1,234.568'); - expect(binding('val | number:0')).toBe('1,235'); - expect(binding('-val | number:4')).toBe('-1,234.5679'); + expect(element(by.id('number-default')).getText()).toBe('1,234.568'); + expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); it('should update', function() { - input('val').enter('3374.333'); - expect(binding('val | number')).toBe('3,374.333'); - expect(binding('val | number:0')).toBe('3,374'); - expect(binding('-val | number:4')).toBe('-3,374.3330'); - }); - - + element(by.model('val')).clear(); + element(by.model('val')).sendKeys('3374.333'); + expect(element(by.id('number-default')).getText()).toBe('3,374.333'); + expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); + }); + + */ @@ -19296,7 +24739,7 @@ function numberFilter($locale) { var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (isNaN(number) || !isFinite(number)) return ''; + if (number == null || !isFinite(number) || isObject(number)) return ''; var isNegative = number < 0; number = Math.abs(number); @@ -19309,6 +24752,7 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; + number = 0; } else { formatedText = numStr; hasExponent = true; @@ -19323,19 +24767,22 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } - var pow = Math.pow(10, fractionSize); - number = Math.round(number * pow) / pow; + // safely round numbers in JS without hitting imprecisions of floating-point arithmetics + // inspired by: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round + number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); + var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; - var pos = 0, + var i, pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; - for (var i = 0; i < pos; i++) { + for (i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } @@ -19356,6 +24803,11 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); + } else { + + if (fractionSize > 0 && number > -1 && number < 1) { + formatedText = number.toFixed(fractionSize); + } } parts.push(isNegative ? pattern.negPre : pattern.posPre); @@ -19430,6 +24882,9 @@ var DATE_FORMATS = { m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, @@ -19437,12 +24892,12 @@ var DATE_FORMATS = { }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, - NUMBER_STRING = /^\d+$/; + NUMBER_STRING = /^\-?\d+$/; /** * @ngdoc filter - * @name ng.filter:date - * @function + * @name date + * @kind function * * @description * Formats `date` to a string based on the requested `format`. @@ -19468,6 +24923,7 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) + * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * @@ -19479,7 +24935,7 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) - * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 + * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) @@ -19487,10 +24943,10 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence - * (e.g. `"h o''clock"`). + * (e.g. `"h 'o''clock'"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or - * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its + * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, @@ -19498,44 +24954,52 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example - - + + {{1288323623006 | date:'medium'}}: - {{1288323623006 | date:'medium'}}
    + {{1288323623006 | date:'medium'}}
    {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
    + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
    {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: - {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
    -
    - + {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
    + + it('should format date', function() { - expect(binding("1288323623006 | date:'medium'")). + expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); - expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). + expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); - expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). + expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); -
    -
    + + */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - function jsonStringToDate(string){ + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, - tzMin = 0; + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } - date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); - date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); + dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); + var h = int(match[4]||0) - tzHour; + var m = int(match[5]||0) - tzMin; + var s = int(match[6]||0); + var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); + timeSetter.call(date, h, m, s, ms); return date; } return string; @@ -19550,11 +25014,7 @@ function dateFilter($locale) { format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { - if (NUMBER_STRING.test(date)) { - date = int(date); - } else { - date = jsonStringToDate(date); - } + date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); } if (isNumber(date)) { @@ -19589,8 +25049,8 @@ function dateFilter($locale) { /** * @ngdoc filter - * @name ng.filter:json - * @function + * @name json + * @kind function * * @description * Allows you to convert a JavaScript object into JSON string. @@ -19602,17 +25062,17 @@ function dateFilter($locale) { * @returns {string} JSON string. * * - * @example: - - + * @example + +
    {{ {'name':'value'} | json }}
    -
    - + + it('should jsonify filtered objects', function() { - expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); + expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); }); - -
    + + * */ function jsonFilter() { @@ -19624,8 +25084,8 @@ function jsonFilter() { /** * @ngdoc filter - * @name ng.filter:lowercase - * @function + * @name lowercase + * @kind function * @description * Converts string to lowercase. * @see angular.lowercase @@ -19635,8 +25095,8 @@ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter - * @name ng.filter:uppercase - * @function + * @name uppercase + * @kind function * @description * Converts string to uppercase. * @see angular.uppercase @@ -19644,101 +25104,128 @@ var lowercaseFilter = valueFn(lowercase); var uppercaseFilter = valueFn(uppercase); /** - * @ngdoc function - * @name ng.filter:limitTo - * @function + * @ngdoc filter + * @name limitTo + * @kind function * * @description - * Creates a new array containing only a specified number of elements in an array. The elements - * are taken from either the beginning or the end of the source array, as specified by the - * value and sign (positive or negative) of `limit`. - * - * Note: This function is used to augment the `Array` type in Angular expressions. See - * {@link ng.$filter} for more information about Angular arrays. - * - * @param {Array} array Source array to be limited. - * @param {string|Number} limit The length of the returned array. If the `limit` number is - * positive, `limit` number of items from the beginning of the source array are copied. - * If the number is negative, `limit` number of items from the end of the source array are - * copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` - * elements. + * Creates a new array or string containing only a specified number of elements. The elements + * are taken from either the beginning or the end of the source array or string, as specified by + * the value and sign (positive or negative) of `limit`. + * + * @param {Array|string} input Source array or string to be limited. + * @param {string|number} limit The length of the returned array or string. If the `limit` number + * is positive, `limit` number of items from the beginning of the source array/string are copied. + * If the number is negative, `limit` number of items from the end of the source array/string + * are copied. The `limit` will be trimmed if it exceeds `array.length` + * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array + * had less than `limit` elements. * * @example - - + + -
    - Limit {{numbers}} to: -

    Output: {{ numbers | limitTo:limit }}

    +
    + Limit {{numbers}} to: +

    Output numbers: {{ numbers | limitTo:numLimit }}

    + Limit {{letters}} to: +

    Output letters: {{ letters | limitTo:letterLimit }}

    - - - it('should limit the numer array to first three items', function() { - expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); - expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); + + + var numLimitInput = element(by.model('numLimit')); + var letterLimitInput = element(by.model('letterLimit')); + var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); + var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + + it('should limit the number array to first three items', function() { + expect(numLimitInput.getAttribute('value')).toBe('3'); + expect(letterLimitInput.getAttribute('value')).toBe('3'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); + expect(limitedLetters.getText()).toEqual('Output letters: abc'); }); it('should update the output when -3 is entered', function() { - input('limit').enter(-3); - expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); + numLimitInput.clear(); + numLimitInput.sendKeys('-3'); + letterLimitInput.clear(); + letterLimitInput.sendKeys('-3'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); + expect(limitedLetters.getText()).toEqual('Output letters: ghi'); }); it('should not exceed the maximum size of input array', function() { - input('limit').enter(100); - expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); + numLimitInput.clear(); + numLimitInput.sendKeys('100'); + letterLimitInput.clear(); + letterLimitInput.sendKeys('100'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); + expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); }); - - + + */ function limitToFilter(){ - return function(array, limit) { - if (!(array instanceof Array)) return array; - limit = int(limit); + return function(input, limit) { + if (!isArray(input) && !isString(input)) return input; + + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = int(limit); + } + + if (isString(input)) { + //NaN check on limit + if (limit) { + return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); + } else { + return ""; + } + } + var out = [], i, n; - // check that array is iterable - if (!array || !(array instanceof Array)) - return out; - // if abs(limit) exceeds maximum length, trim it - if (limit > array.length) - limit = array.length; - else if (limit < -array.length) - limit = -array.length; + if (limit > input.length) + limit = input.length; + else if (limit < -input.length) + limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { - i = array.length + limit; - n = array.length; + i = input.length + limit; + n = input.length; } for (; i} expression A predicate to be @@ -19754,31 +25241,32 @@ function limitToFilter(){ * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * - * @param {boolean=} reverse Reverse the order the array. + * @param {boolean=} reverse Reverse the order of the array. * @returns {Array} Sorted copy of the source array. * * @example - - + + -
    +
    Sorting predicate = {{predicate}}; reverse = {{reverse}}

    [ unsorted ] + (^) @@ -19789,31 +25277,53 @@ function limitToFilter(){
    Name - (^) Phone Number Age
    - - - it('should be reverse ordered by aged', function() { - expect(binding('predicate')).toBe('-age'); - expect(repeater('table.friend', 'friend in friends').column('friend.age')). - toEqual(['35', '29', '21', '19', '10']); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); - }); + + + * + * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the + * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the + * desired parameters. + * + * Example: + * + * @example + + +
    + + + + + + + + + + + +
    Name + (^)Phone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    +
    +
    - it('should reorder the table when user selects different predicate', function() { - element('.doc-example-live a:contains("Name")').click(); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); - expect(repeater('table.friend', 'friend in friends').column('friend.age')). - toEqual(['35', '10', '29', '19', '21']); - - element('.doc-example-live a:contains("Phone")').click(); - expect(repeater('table.friend', 'friend in friends').column('friend.phone')). - toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); - }); -
    - + + angular.module('orderByExample', []) + .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { + var orderBy = $filter('orderBy'); + $scope.friends = [ + { name: 'John', phone: '555-1212', age: 10 }, + { name: 'Mary', phone: '555-9876', age: 19 }, + { name: 'Mike', phone: '555-4321', age: 21 }, + { name: 'Adam', phone: '555-5678', age: 35 }, + { name: 'Julie', phone: '555-8765', age: 29 } + ]; + $scope.order = function(predicate, reverse) { + $scope.friends = orderBy($scope.friends, predicate, reverse); + }; + $scope.order('-age',false); + }]); + + */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ @@ -19829,6 +25339,12 @@ function orderByFilter($parse){ predicate = predicate.substring(1); } get = $parse(predicate); + if (get.constant) { + var key = get(); + return reverseComparator(function(a,b) { + return compare(a[key], b[key]); + }, descending); + } } return reverseComparator(function(a,b){ return compare(get(a),get(b)); @@ -19854,22 +25370,28 @@ function orderByFilter($parse){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { - if (t1 == "string") v1 = v1.toLowerCase(); - if (t1 == "string") v2 = v2.toLowerCase(); + if (isDate(v1) && isDate(v2)) { + v1 = v1.valueOf(); + v2 = v2.valueOf(); + } + if (t1 == "string") { + v1 = v1.toLowerCase(); + v2 = v2.toLowerCase(); + } if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } - } + }; } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive - } + }; } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); @@ -19877,16 +25399,16 @@ function ngDirective(directive) { /** * @ngdoc directive - * @name ng.directive:a + * @name a * @restrict E * * @description - * Modifies the default behavior of html A tag, so that the default action is prevented when href - * attribute is empty. + * Modifies the default behavior of the html A tag so that the default action is prevented when + * the href attribute is empty. * - * The reasoning for this change is to allow easy creation of action links with `ngClick` directive + * This change permits the easy creation of action links with the `ngClick` directive * without changing the location or causing page reloads, e.g.: - * `Save` + * `Add Item` */ var htmlAnchorDirective = valueFn({ restrict: 'E', @@ -19907,46 +25429,55 @@ var htmlAnchorDirective = valueFn({ element.append(document.createComment('IE fix')); } - return function(scope, element) { - element.bind('click', function(event){ - // if we have no href url, then don't navigate anywhere. - if (!element.attr('href')) { - event.preventDefault(); - } - }); + if (!attr.href && !attr.xlinkHref && !attr.name) { + return function(scope, element) { + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. + var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? + 'xlink:href' : 'href'; + element.on('click', function(event){ + // if we have no href url, then don't navigate anywhere. + if (!element.attr(href)) { + event.preventDefault(); + } + }); + }; } } }); /** * @ngdoc directive - * @name ng.directive:ngHref + * @name ngHref * @restrict A + * @priority 99 * * @description - * Using Angular markup like {{hash}} in an href attribute makes - * the page open to a wrong URL, if the user clicks that link before - * angular has a chance to replace the {{hash}} with actual URL, the - * link will be broken and will most likely return a 404 error. + * Using Angular markup like `{{hash}}` in an href attribute will + * make the link go to the wrong URL if the user clicks it before + * Angular has a chance to replace the `{{hash}}` markup with its + * value. Until Angular replaces the markup the link will be broken + * and will most likely return a 404 error. + * * The `ngHref` directive solves this problem. * - * The buggy way to write it: - *
    + * The wrong way to write it:
    + * ```html
      * 
    - * 
    + * ``` * * The correct way to write it: - *
    + * ```html
      * 
    - * 
    + * ``` * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example - * This example uses `link` variable inside `href` attribute: - - + * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes + * in links and their different behaviors: + +
    link 1 (link, don't reload)
    link 2 (link, don't reload)
    @@ -19954,54 +25485,71 @@ var htmlAnchorDirective = valueFn({ anchor (link, don't reload)
    anchor (no link)
    link (link, change location) - - + + it('should execute ng-click but not reload when href without value', function() { - element('#link-1').click(); - expect(input('value').val()).toEqual('1'); - expect(element('#link-1').attr('href')).toBe(""); + element(by.id('link-1')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('1'); + expect(element(by.id('link-1')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when href empty string', function() { - element('#link-2').click(); - expect(input('value').val()).toEqual('2'); - expect(element('#link-2').attr('href')).toBe(""); + element(by.id('link-2')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('2'); + expect(element(by.id('link-2')).getAttribute('href')).toBe(''); }); it('should execute ng-click and change url when ng-href specified', function() { - expect(element('#link-3').attr('href')).toBe("/123"); + expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + + element(by.id('link-3')).click(); - element('#link-3').click(); - expect(browser().window().path()).toEqual('/123'); + // At this point, we navigate away from an Angular page, so we need + // to use browser.driver to get the base webdriver. + + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/123$/); + }); + }, 5000, 'page should navigate to /123'); }); - it('should execute ng-click but not reload when href empty string and name specified', function() { - element('#link-4').click(); - expect(input('value').val()).toEqual('4'); - expect(element('#link-4').attr('href')).toBe(''); + xit('should execute ng-click but not reload when href empty string and name specified', function() { + element(by.id('link-4')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('4'); + expect(element(by.id('link-4')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { - element('#link-5').click(); - expect(input('value').val()).toEqual('5'); - expect(element('#link-5').attr('href')).toBe(undefined); + element(by.id('link-5')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('5'); + expect(element(by.id('link-5')).getAttribute('href')).toBe(null); }); it('should only change url when only ng-href', function() { - input('value').enter('6'); - expect(element('#link-6').attr('href')).toBe('6'); + element(by.model('value')).clear(); + element(by.model('value')).sendKeys('6'); + expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); - element('#link-6').click(); - expect(browser().location().url()).toEqual('/6'); + element(by.id('link-6')).click(); + + // At this point, we navigate away from an Angular page, so we need + // to use browser.driver to get the base webdriver. + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/6$/); + }); + }, 5000, 'page should navigate to /6'); }); - - + + */ /** * @ngdoc directive - * @name ng.directive:ngSrc + * @name ngSrc * @restrict A + * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't @@ -20010,14 +25558,14 @@ var htmlAnchorDirective = valueFn({ * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: - *
    + * ```html
      * 
    - * 
    + * ``` * * The correct way to write it: - *
    + * ```html
      * 
    - * 
    + * ``` * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. @@ -20025,227 +25573,286 @@ var htmlAnchorDirective = valueFn({ /** * @ngdoc directive - * @name ng.directive:ngDisabled + * @name ngSrcset + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. + * + * The buggy way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ + +/** + * @ngdoc directive + * @name ngDisabled * @restrict A + * @priority 100 * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: - *
    + * ```html
      * 
    * *
    - *
    + * ``` * - * The HTML specs do not require browsers to preserve the special attributes such as disabled. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngDisabled` directive. + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as disabled. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngDisabled` directive solves this problem for the `disabled` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. * * @example - - + + Click me to toggle:
    -
    - + + it('should toggle button', function() { - expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); + expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); - -
    + + * * @element INPUT - * @param {expression} ngDisabled Angular expression that will be evaluated. + * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, + * then special attribute "disabled" will be set on the element */ /** * @ngdoc directive - * @name ng.directive:ngChecked + * @name ngChecked * @restrict A + * @priority 100 * * @description - * The HTML specs do not require browsers to preserve the special attributes such as checked. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngChecked` directive. + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as checked. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngChecked` directive solves this problem for the `checked` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. * @example - - + + Check me to check both:
    -
    - + + it('should check both checkBoxes', function() { - expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); - input('master').check(); - expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); + expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); + element(by.model('master')).click(); + expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); - -
    + + * * @element INPUT - * @param {expression} ngChecked Angular expression that will be evaluated. - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMultiple - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as multiple. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngMultiple` directive. - * - * @example - - - Check me check multiple:
    - -
    - - it('should toggle multiple', function() { - expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); - }); - -
    - * - * @element SELECT - * @param {expression} ngMultiple Angular expression that will be evaluated. + * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, + * then special attribute "checked" will be set on the element */ /** * @ngdoc directive - * @name ng.directive:ngReadonly + * @name ngReadonly * @restrict A + * @priority 100 * * @description - * The HTML specs do not require browsers to preserve the special attributes such as readonly. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngReadonly` directive. + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as readonly. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngReadonly` directive solves this problem for the `readonly` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. * @example - - + + Check me to make text readonly:
    -
    - + + it('should toggle readonly attr', function() { - expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); }); - -
    + + * * @element INPUT - * @param {string} expression Angular expression that will be evaluated. + * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, + * then special attribute "readonly" will be set on the element */ /** * @ngdoc directive - * @name ng.directive:ngSelected + * @name ngSelected * @restrict A + * @priority 100 * * @description - * The HTML specs do not require browsers to preserve the special attributes such as selected. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduced the `ngSelected` directive. + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as selected. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngSelected` directive solves this problem for the `selected` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * * @example - - + + Check me to select:
    -
    - + + it('should select Greetings!', function() { - expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); - input('selected').check(); - expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); + expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); + element(by.model('selected')).click(); + expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); }); - -
    + + * * @element OPTION - * @param {string} expression Angular expression that will be evaluated. + * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, + * then special attribute "selected" will be set on the element */ +/** + * @ngdoc directive + * @name ngOpen + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as open. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngOpen` directive solves this problem for the `open` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me check multiple:
    +
    + Show/Hide me +
    +
    + + it('should toggle open', function() { + expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); + element(by.model('open')).click(); + expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); + }); + +
    + * + * @element DETAILS + * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, + * then special attribute "open" will be set on the element + */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { + // binding to multiple is not supported + if (propName == "multiple") return; + var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, - compile: function() { - return function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); - }); - }; + link: function(scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); } }; }; }); -// ng-src, ng-href are interpolated -forEach(['src', 'href'], function(attrName) { +// ng-src, ng-srcset, ng-href are interpolated +forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { + var propName = attrName, + name = attrName; + + if (attrName === 'href' && + toString.call(element.prop('href')) === '[object SVGAnimatedString]') { + name = 'xlinkHref'; + attr.$attr[name] = 'xlink:href'; + propName = null; + } + attr.$observe(normalized, function(value) { if (!value) return; - attr.$set(attrName, value); + attr.$set(name, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. - if (msie) element.prop(attrName, attr[attrName]); + if (msie && propName) element.prop(propName, attr[name]); }); } }; }; }); +/* global -nullFormCtrl */ var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, - $setDirty: noop + $setDirty: noop, + $setPristine: noop }; /** - * @ngdoc object - * @name ng.directive:form.FormController + * @ngdoc type + * @name form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. @@ -20255,11 +25862,24 @@ var nullFormCtrl = { * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * - * - keys are validation tokens (error names) — such as `required`, `url` or `email`), - * - values are arrays of controls or forms that are invalid with given error. + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that are invalid for given error name. + * + * + * Built-in validation tokens: + * + * - `email` + * - `max` + * - `maxlength` + * - `min` + * - `minlength` + * - `number` + * - `pattern` + * - `required` + * - `url` * * @description - * `FormController` keeps track of all its controls and nested forms as well as state of them, + * `FormController` keeps track of all its controls and nested forms as well as the state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance @@ -20267,15 +25887,16 @@ var nullFormCtrl = { * */ //asks for $scope to fool the BC controller module -FormController.$inject = ['$element', '$attrs', '$scope']; -function FormController(element, attrs) { +FormController.$inject = ['$element', '$attrs', '$scope', '$animate']; +function FormController(element, attrs, $scope, $animate) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid - errors = form.$error = {}; + errors = form.$error = {}, + controls = []; // init state - form.$name = attrs.name; + form.$name = attrs.name || attrs.ngForm; form.$dirty = false; form.$pristine = true; form.$valid = true; @@ -20290,17 +25911,39 @@ function FormController(element, attrs) { // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - element. - removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). - addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); + $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } + /** + * @ngdoc method + * @name form.FormController#$addControl + * + * @description + * Register a control with the form. + * + * Input elements using ngModelController do this automatically when they are linked. + */ form.$addControl = function(control) { - if (control.$name && !form.hasOwnProperty(control.$name)) { + // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored + // and not added to the scope. Now we throw an error. + assertNotHasOwnProperty(control.$name, 'input'); + controls.push(control); + + if (control.$name) { form[control.$name] = control; } }; + /** + * @ngdoc method + * @name form.FormController#$removeControl + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + */ form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; @@ -20308,8 +25951,19 @@ function FormController(element, attrs) { forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); + + arrayRemove(controls, control); }; + /** + * @ngdoc method + * @name form.FormController#$setValidity + * + * @description + * Sets the validity of a form control. + * + * This method will also propagate to parent forms. + */ form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; @@ -20348,19 +26002,53 @@ function FormController(element, attrs) { } }; + /** + * @ngdoc method + * @name form.FormController#$setDirty + * + * @description + * Sets the form to a dirty state. + * + * This method can be called to add the 'ng-dirty' class and set the form to a dirty + * state (ng-dirty class). This method will also propagate to parent forms. + */ form.$setDirty = function() { - element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); + $animate.removeClass(element, PRISTINE_CLASS); + $animate.addClass(element, DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; + /** + * @ngdoc method + * @name form.FormController#$setPristine + * + * @description + * Sets the form to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the form to its pristine + * state (ng-pristine class). This method will also propagate to all the controls contained + * in this form. + * + * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after + * saving or resetting it. + */ + form.$setPristine = function () { + $animate.removeClass(element, DIRTY_CLASS); + $animate.addClass(element, PRISTINE_CLASS); + form.$dirty = false; + form.$pristine = true; + forEach(controls, function(control) { + control.$setPristine(); + }); + }; } /** * @ngdoc directive - * @name ng.directive:ngForm + * @name ngForm * @restrict EAC * * @description @@ -20368,44 +26056,54 @@ function FormController(element, attrs) { * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * - * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into + * Note: the purpose of `ngForm` is to group controls, + * but not to be a replacement for the `
    ` tag with all of its capabilities + * (e.g. posting to the server, ...). + * + * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive - * @name ng.directive:form + * @name form * @restrict E * * @description * Directive that instantiates - * {@link ng.directive:form.FormController FormController}. + * {@link form.FormController FormController}. * - * If `name` attribute is specified, the form controller is published onto the current scope under + * If the `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * - * In angular forms can be nested. This means that the outer form is valid when all of the child - * forms are valid as well. However browsers do not allow nesting of `` elements, for this - * reason angular provides {@link ng.directive:ngForm `ngForm`} alias - * which behaves identical to `` but allows form nesting. + * In Angular forms can be nested. This means that the outer form is valid when all of the child + * forms are valid as well. However, browsers do not allow nesting of `` elements, so + * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to + * `` but can be nested. This allows you to have nested forms, which is very useful when + * using Angular validation directives in forms that are dynamically generated using the + * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` + * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an + * `ngForm` directive and nest these in an outer `form` element. * * * # CSS classes - * - `ng-valid` Is set if the form is valid. - * - `ng-invalid` Is set if the form is invalid. - * - `ng-pristine` Is set if the form is pristine. - * - `ng-dirty` Is set if the form is dirty. + * - `ng-valid` is set if the form is valid. + * - `ng-invalid` is set if the form is invalid. + * - `ng-pristine` is set if the form is pristine. + * - `ng-dirty` is set if the form is dirty. + * + * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * - * # Submitting a form and preventing default action + * # Submitting a form and preventing the default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered - * to handle the form submission in application specific way. + * to handle the form submission in an application-specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `` element has an `action` attribute specified. @@ -20417,12 +26115,13 @@ function FormController(element, attrs) { * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * - * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This - * is because of the following form submission rules coming from the html spec: + * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} + * or {@link ng.directive:ngClick ngClick} directives. + * This is because of the following form submission rules in the HTML specification: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) - * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter + * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or @@ -20431,15 +26130,50 @@ function FormController(element, attrs) { * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * + * ## Animation Hooks + * + * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. + * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any + * other validations that are performed within the form. Animations in ngForm are similar to how + * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well + * as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style a form element + * that has been rendered as invalid after it has been validated: + * + *
    + * //be sure to include ngAnimate as a module to hook into more
    + * //advanced animations
    + * .my-form {
    + *   transition:0.5s linear all;
    + *   background: white;
    + * }
    + * .my-form.ng-invalid {
    + *   background: red;
    + *   color:white;
    + * }
    + * 
    + * * @example - - + + - + + userType: Required!
    userType = {{userType}}
    @@ -20448,26 +26182,36 @@ function FormController(element, attrs) { myForm.$valid = {{myForm.$valid}}
    myForm.$error.required = {{!!myForm.$error.required}}
    -
    - + + it('should initialize to model', function() { - expect(binding('userType')).toEqual('guest'); - expect(binding('myForm.input.$valid')).toEqual('true'); + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + + expect(userType.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { - input('userType').enter(''); - expect(binding('userType')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + var userInput = element(by.model('userType')); + + userInput.clear(); + userInput.sendKeys(''); + + expect(userType.getText()).toEqual('userType ='); + expect(valid.getText()).toContain('false'); }); - -
    + + + * */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', - restrict: 'E', + restrict: isNgForm ? 'EAC' : 'E', controller: FormController, compile: function() { return { @@ -20489,7 +26233,7 @@ var formDirectiveFactory = function(isNgForm) { // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. - formElement.bind('$destroy', function() { + formElement.on('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); @@ -20500,13 +26244,13 @@ var formDirectiveFactory = function(isNgForm) { alias = attr.name || attr.ngForm; if (alias) { - scope[alias] = controller; + setter(scope, alias, controller, alias); } if (parentFormCtrl) { - formElement.bind('$destroy', function() { + formElement.on('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { - scope[alias] = undefined; + setter(scope, alias, undefined, alias); } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); @@ -20516,22 +26260,28 @@ var formDirectiveFactory = function(isNgForm) { } }; - return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; + return formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); +/* global VALID_CLASS: true, + INVALID_CLASS: true, + PRISTINE_CLASS: true, + DIRTY_CLASS: true +*/ + var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; -var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; +var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** - * @ngdoc inputType - * @name ng.directive:input.text + * @ngdoc input + * @name input[text] * * @description * Standard HTML text input with angular data binding. @@ -20551,19 +26301,21 @@ var inputType = { * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * * @example - - + + -
    + Single word: + ng-pattern="word" required ng-trim="false"> Required! @@ -20575,32 +26327,40 @@ var inputType = { myForm.$valid = {{myForm.$valid}}
    myForm.$error.required = {{!!myForm.$error.required}}
    -
    - + + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + it('should initialize to model', function() { - expect(binding('text')).toEqual('guest'); - expect(binding('myForm.input.$valid')).toEqual('true'); + expect(text.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); }); it('should be invalid if multi word', function() { - input('text').enter('hello world'); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys('hello world'); + + expect(valid.getText()).toContain('false'); }); - -
    + + */ 'text': textInputType, /** - * @ngdoc inputType - * @name ng.directive:input.number + * @ngdoc input + * @name input[number] * * @description * Text input with number validation and transformation. Sets the `number` validation @@ -20625,19 +26385,20 @@ var inputType = { * interaction with the input element. * * @example - - + + -
    + Number: - + Required! - + Not valid number! value = {{value}}
    myForm.input.$valid = {{myForm.input.$valid}}
    @@ -20645,33 +26406,39 @@ var inputType = { myForm.$valid = {{myForm.$valid}}
    myForm.$error.required = {{!!myForm.$error.required}}
    -
    - + + + var value = element(by.binding('value')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + it('should initialize to model', function() { - expect(binding('value')).toEqual('12'); - expect(binding('myForm.input.$valid')).toEqual('true'); + expect(value.getText()).toContain('12'); + expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { - input('value').enter(''); - expect(binding('value')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); }); it('should be invalid if over max', function() { - input('value').enter('123'); - expect(binding('value')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys('123'); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); }); - -
    + + */ 'number': numberInputType, /** - * @ngdoc inputType - * @name ng.directive:input.url + * @ngdoc input + * @name input[url] * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a @@ -20694,14 +26461,15 @@ var inputType = { * interaction with the input element. * * @example - - + + -
    + URL: Required! @@ -20714,32 +26482,40 @@ var inputType = { myForm.$error.required = {{!!myForm.$error.required}}
    myForm.$error.url = {{!!myForm.$error.url}}
    -
    - + + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + it('should initialize to model', function() { - expect(binding('text')).toEqual('http://google.com'); - expect(binding('myForm.input.$valid')).toEqual('true'); + expect(text.getText()).toContain('http://google.com'); + expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); }); it('should be invalid if not url', function() { - input('text').enter('xxx'); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys('box'); + + expect(valid.getText()).toContain('false'); }); - -
    + + */ 'url': urlInputType, /** - * @ngdoc inputType - * @name ng.directive:input.email + * @ngdoc input + * @name input[email] * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email @@ -20758,16 +26534,19 @@ var inputType = { * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. * * @example - - + + -
    + Email: Required! @@ -20780,32 +26559,39 @@ var inputType = { myForm.$error.required = {{!!myForm.$error.required}}
    myForm.$error.email = {{!!myForm.$error.email}}
    -
    - + + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + it('should initialize to model', function() { - expect(binding('text')).toEqual('me@example.com'); - expect(binding('myForm.input.$valid')).toEqual('true'); + expect(text.getText()).toContain('me@example.com'); + expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys(''); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); }); it('should be invalid if not email', function() { - input('text').enter('xxx'); - expect(binding('myForm.input.$valid')).toEqual('false'); + input.clear(); + input.sendKeys('xxx'); + + expect(valid.getText()).toContain('false'); }); - -
    + + */ 'email': emailInputType, /** - * @ngdoc inputType - * @name ng.directive:input.radio + * @ngdoc input + * @name input[radio] * * @description * HTML radio button. @@ -20815,38 +26601,49 @@ var inputType = { * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. + * @param {string} ngValue Angular expression which sets the value to which the expression should + * be set when selected. * * @example - - + + -
    + Red
    - Green
    + Green
    Blue
    - color = {{color}}
    + color = {{color | json}}
    -
    - + Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. + + it('should change state', function() { - expect(binding('color')).toEqual('blue'); + var color = element(by.binding('color')); + + expect(color.getText()).toContain('blue'); + + element.all(by.model('color')).get(0).click(); - input('color').select('red'); - expect(binding('color')).toEqual('red'); + expect(color.getText()).toContain('red'); }); - -
    + + */ 'radio': radioInputType, /** - * @ngdoc inputType - * @name ng.directive:input.checkbox + * @ngdoc input + * @name input[checkbox] * * @description * HTML checkbox. @@ -20859,65 +26656,148 @@ var inputType = { * interaction with the input element. * * @example - - + + -
    + Value1:
    Value2:
    value1 = {{value1}}
    value2 = {{value2}}
    -
    - + + it('should change state', function() { - expect(binding('value1')).toEqual('true'); - expect(binding('value2')).toEqual('YES'); + var value1 = element(by.binding('value1')); + var value2 = element(by.binding('value2')); + + expect(value1.getText()).toContain('true'); + expect(value2.getText()).toContain('YES'); - input('value1').check(); - input('value2').check(); - expect(binding('value1')).toEqual('false'); - expect(binding('value2')).toEqual('NO'); + element(by.model('value1')).click(); + element(by.model('value2')).click(); + + expect(value1.getText()).toContain('false'); + expect(value2.getText()).toContain('NO'); }); - -
    + + */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, - 'reset': noop + 'reset': noop, + 'file': noop }; +// A helper function to call $setValidity and return the value / undefined, +// a pattern that is repeated a lot in the input validation logic. +function validate(ctrl, validatorName, validity, value){ + ctrl.$setValidity(validatorName, validity); + return validity ? value : undefined; +} -function isEmpty(value) { - return isUndefined(value) || value === '' || value === null || value !== value; +function testFlags(validity, flags) { + var i, flag; + if (flags) { + for (i=0; i + if (toBoolean(attr.ngTrim || 'T')) { + value = trim(value); + } + + // If a control is suffering from bad input, browsers discard its value, so it may be + // necessary to revalidate even if the control's value is the same empty value twice in + // a row. + var revalidate = validity && ctrl.$$hasNativeValidators; + if (ctrl.$viewValue !== value || (value === '' && revalidate)) { + if (scope.$$phase) { ctrl.$setViewValue(value); - }); + } else { + scope.$apply(function() { + ctrl.$setViewValue(value); + }); + } } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { - element.bind('input', listener); + element.on('input', listener); } else { var timeout; @@ -20930,7 +26810,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { } }; - element.bind('keydown', function(event) { + element.on('keydown', function(event) { var key = event.keyCode; // ignore @@ -20940,48 +26820,45 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { deferListener(); }); - // if user paste into input using mouse, we need "change" event to catch it - element.bind('change', listener); - // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { - element.bind('paste cut', deferListener); + element.on('paste cut', deferListener); } } + // if user paste into input using mouse on older browser + // or form autocomplete on newer browser, we need "change" event to catch it + element.on('change', listener); ctrl.$render = function() { - element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); + element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, - patternValidator; - - var validate = function(regexp, value) { - if (isEmpty(value) || regexp.test(value)) { - ctrl.$setValidity('pattern', true); - return value; - } else { - ctrl.$setValidity('pattern', false); - return undefined; - } - }; + patternValidator, + match; if (pattern) { - if (pattern.match(/^\/(.*)\/$/)) { - pattern = new RegExp(pattern.substr(1, pattern.length - 2)); + var validateRegex = function(regexp, value) { + return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value); + }; + match = pattern.match(/^\/(.*)\/([gim]*)$/); + if (match) { + pattern = new RegExp(match[1], match[2]); patternValidator = function(value) { - return validate(pattern, value) + return validateRegex(pattern, value); }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { - throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); + throw minErr('ngPattern')('noregexp', + 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, + patternObj, startingTag(element)); } - return validate(patternObj, value); + return validateRegex(patternObj, value); }; } @@ -20993,13 +26870,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { - if (!isEmpty(value) && value.length < minlength) { - ctrl.$setValidity('minlength', false); - return undefined; - } else { - ctrl.$setValidity('minlength', true); - return value; - } + return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value); }; ctrl.$parsers.push(minLengthValidator); @@ -21010,13 +26881,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { - if (!isEmpty(value) && value.length > maxlength) { - ctrl.$setValidity('maxlength', false); - return undefined; - } else { - ctrl.$setValidity('maxlength', true); - return value; - } + return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value); }; ctrl.$parsers.push(maxLengthValidator); @@ -21024,11 +26889,13 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { } } +var numberBadFlags = ['badInput']; + function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { - var empty = isEmpty(value); + var empty = ctrl.$isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); @@ -21038,20 +26905,16 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { } }); + addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState); + ctrl.$formatters.push(function(value) { - return isEmpty(value) ? '' : '' + value; + return ctrl.$isEmpty(value) ? '' : '' + value; }); if (attr.min) { - var min = parseFloat(attr.min); var minValidator = function(value) { - if (!isEmpty(value) && value < min) { - ctrl.$setValidity('min', false); - return undefined; - } else { - ctrl.$setValidity('min', true); - return value; - } + var min = parseFloat(attr.min); + return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value); }; ctrl.$parsers.push(minValidator); @@ -21059,15 +26922,9 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { } if (attr.max) { - var max = parseFloat(attr.max); var maxValidator = function(value) { - if (!isEmpty(value) && value > max) { - ctrl.$setValidity('max', false); - return undefined; - } else { - ctrl.$setValidity('max', true); - return value; - } + var max = parseFloat(attr.max); + return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value); }; ctrl.$parsers.push(maxValidator); @@ -21075,14 +26932,7 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { } ctrl.$formatters.push(function(value) { - - if (isEmpty(value) || isNumber(value)) { - ctrl.$setValidity('number', true); - return value; - } else { - ctrl.$setValidity('number', false); - return undefined; - } + return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value); }); } @@ -21090,13 +26940,7 @@ function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { - if (isEmpty(value) || URL_REGEXP.test(value)) { - ctrl.$setValidity('url', true); - return value; - } else { - ctrl.$setValidity('url', false); - return undefined; - } + return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value); }; ctrl.$formatters.push(urlValidator); @@ -21107,13 +26951,7 @@ function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { - if (isEmpty(value) || EMAIL_REGEXP.test(value)) { - ctrl.$setValidity('email', true); - return value; - } else { - ctrl.$setValidity('email', false); - return undefined; - } + return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value); }; ctrl.$formatters.push(emailValidator); @@ -21126,7 +26964,7 @@ function radioInputType(scope, element, attr, ctrl) { element.attr('name', nextUid()); } - element.bind('click', function() { + element.on('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); @@ -21149,7 +26987,7 @@ function checkboxInputType(scope, element, attr, ctrl) { if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; - element.bind('click', function() { + element.on('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); @@ -21159,6 +26997,11 @@ function checkboxInputType(scope, element, attr, ctrl) { element[0].checked = ctrl.$viewValue; }; + // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox. + ctrl.$isEmpty = function(value) { + return value !== trueValue; + }; + ctrl.$formatters.push(function(value) { return value === trueValue; }); @@ -21171,7 +27014,7 @@ function checkboxInputType(scope, element, attr, ctrl) { /** * @ngdoc directive - * @name ng.directive:textarea + * @name textarea * @restrict E * * @description @@ -21194,12 +27037,13 @@ function checkboxInputType(scope, element, attr, ctrl) { * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. */ /** * @ngdoc directive - * @name ng.directive:input + * @name input * @restrict E * * @description @@ -21221,14 +27065,15 @@ function checkboxInputType(scope, element, attr, ctrl) { * interaction with the input element. * * @example - - + + -
    +
    User name: @@ -21251,46 +27096,61 @@ function checkboxInputType(scope, element, attr, ctrl) { myForm.$error.minlength = {{!!myForm.$error.minlength}}
    myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
    - - + + + var user = element(by.binding('{{user}}')); + var userNameValid = element(by.binding('myForm.userName.$valid')); + var lastNameValid = element(by.binding('myForm.lastName.$valid')); + var lastNameError = element(by.binding('myForm.lastName.$error')); + var formValid = element(by.binding('myForm.$valid')); + var userNameInput = element(by.model('user.name')); + var userLastInput = element(by.model('user.last')); + it('should initialize to model', function() { - expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); - expect(binding('myForm.userName.$valid')).toEqual('true'); - expect(binding('myForm.$valid')).toEqual('true'); + expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); + expect(userNameValid.getText()).toContain('true'); + expect(formValid.getText()).toContain('true'); }); it('should be invalid if empty when required', function() { - input('user.name').enter(''); - expect(binding('user')).toEqual('{"last":"visitor"}'); - expect(binding('myForm.userName.$valid')).toEqual('false'); - expect(binding('myForm.$valid')).toEqual('false'); + userNameInput.clear(); + userNameInput.sendKeys(''); + + expect(user.getText()).toContain('{"last":"visitor"}'); + expect(userNameValid.getText()).toContain('false'); + expect(formValid.getText()).toContain('false'); }); it('should be valid if empty when min length is set', function() { - input('user.last').enter(''); - expect(binding('user')).toEqual('{"name":"guest","last":""}'); - expect(binding('myForm.lastName.$valid')).toEqual('true'); - expect(binding('myForm.$valid')).toEqual('true'); + userLastInput.clear(); + userLastInput.sendKeys(''); + + expect(user.getText()).toContain('{"name":"guest","last":""}'); + expect(lastNameValid.getText()).toContain('true'); + expect(formValid.getText()).toContain('true'); }); it('should be invalid if less than required min length', function() { - input('user.last').enter('xx'); - expect(binding('user')).toEqual('{"name":"guest"}'); - expect(binding('myForm.lastName.$valid')).toEqual('false'); - expect(binding('myForm.lastName.$error')).toMatch(/minlength/); - expect(binding('myForm.$valid')).toEqual('false'); + userLastInput.clear(); + userLastInput.sendKeys('xx'); + + expect(user.getText()).toContain('{"name":"guest"}'); + expect(lastNameValid.getText()).toContain('false'); + expect(lastNameError.getText()).toContain('minlength'); + expect(formValid.getText()).toContain('false'); }); it('should be invalid if longer than max length', function() { - input('user.last').enter('some ridiculously long name'); - expect(binding('user')) - .toEqual('{"name":"guest"}'); - expect(binding('myForm.lastName.$valid')).toEqual('false'); - expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); - expect(binding('myForm.$valid')).toEqual('false'); + userLastInput.clear(); + userLastInput.sendKeys('some ridiculously long name'); + + expect(user.getText()).toContain('{"name":"guest"}'); + expect(lastNameValid.getText()).toContain('false'); + expect(lastNameError.getText()).toContain('maxlength'); + expect(formValid.getText()).toContain('false'); }); - - + + */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { @@ -21311,18 +27171,37 @@ var VALID_CLASS = 'ng-valid', DIRTY_CLASS = 'ng-dirty'; /** - * @ngdoc object - * @name ng.directive:ngModel.NgModelController + * @ngdoc type + * @name ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. - * @property {Array.} $parsers Whenever the control reads value from the DOM, it executes - * all of these functions to sanitize / convert the value as well as validate. + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + the control reads value from the DOM. Each function is called, in turn, passing the value + through to the next. The last return value is used to populate the model. + Used to sanitize / convert the value as well as validation. For validation, + the parsers should update the validity state using + {@link ngModel.NgModelController#$setValidity $setValidity()}, + and return `undefined` for invalid values. + + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the model value changes. Each function is called, in turn, passing the value through to the + next. Used to format / convert values for display in the control and validation. + * ```js + * function formatter(value) { + * if (value) { + * return value.toUpperCase(); + * } + * } + * ngModel.$formatters.push(formatter); + * ``` * - * @property {Array.} $formatters Whenever the model value changes, it executes all of - * these functions to convert the value as well as validate. + * @property {Array.} $viewChangeListeners Array of functions to execute whenever the + * view value has changed. It is called with no arguments, and its return value is ignored. + * This can be used in place of additional $watches against the model value. * - * @property {Object} $error An bject hash with all errors as keys. + * @property {Object} $error An object hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. @@ -21332,16 +27211,25 @@ var VALID_CLASS = 'ng-valid', * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains - * services for data-binding, validation, CSS update, value formatting and parsing. It - * specifically does not contain any logic which deals with DOM rendering or listening to - * DOM events. The `NgModelController` is meant to be extended by other directives where, the - * directive provides DOM manipulation and the `NgModelController` provides the data-binding. + * services for data-binding, validation, CSS updates, and value formatting and parsing. It + * purposefully does not contain any logic which deals with DOM rendering or listening to + * DOM events. Such DOM related logic should be provided by other directives which make use of + * `NgModelController` for data-binding. * + * ## Custom Control Example * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * - * + * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. This will not work on older browsers. + * + * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} + * module to automatically remove "bad" content like inline event listener (e.g. ``). + * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks + * that content using the `$sce` service. + * + * [contenteditable] { border: 1px solid black; @@ -21355,8 +27243,8 @@ var VALID_CLASS = 'ng-valid', - angular.module('customControl', []). - directive('contenteditable', function() { + angular.module('customControl', ['ngSanitize']). + directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController @@ -21365,48 +27253,64 @@ var VALID_CLASS = 'ng-valid', // Specify how UI should be updated ngModel.$render = function() { - element.html(ngModel.$viewValue || ''); + element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding - element.bind('blur keyup change', function() { + element.on('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { - ngModel.$setViewValue(element.html()); + var html = element.html(); + // When we clear the content editable the browser leaves a
    behind + // If strip-br attribute is provided then we strip this out + if( attrs.stripBr && html == '
    ' ) { + html = ''; + } + ngModel.$setViewValue(html); } } }; - }); + }]);
    Change me!
    Required!
    - - it('should data-bind and become invalid', function() { - var contentEditable = element('[contenteditable]'); - - expect(contentEditable.text()).toEqual('Change me!'); - input('userContent').enter(''); - expect(contentEditable.text()).toEqual(''); - expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); - }); + + it('should data-bind and become invalid', function() { + if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { + // SafariDriver can't handle contenteditable + // and Firefox driver can't clear contenteditables very well + return; + } + var contentEditable = element(by.css('[contenteditable]')); + var content = 'Change me!'; + + expect(contentEditable.getText()).toEqual(content); + + contentEditable.clear(); + contentEditable.sendKeys(protractor.Key.BACK_SPACE); + expect(contentEditable.getText()).toEqual(''); + expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); + }); *
    * + * */ -var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', - function($scope, $exceptionHandler, $attr, $element, $parse) { +var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', + function($scope, $exceptionHandler, $attr, $element, $parse, $animate) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; @@ -21422,14 +27326,13 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ ngModelSet = ngModelGet.assign; if (!ngModelSet) { - throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + - ' (' + startingTag($element) + ')'); + throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", + $attr.ngModel, startingTag($element)); } /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$render - * @methodOf ng.directive:ngModel.NgModelController + * @ngdoc method + * @name ngModel.NgModelController#$render * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model @@ -21437,6 +27340,27 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ */ this.$render = noop; + /** + * @ngdoc method + * @name ngModel.NgModelController#$isEmpty + * + * @description + * This is called when we need to determine if the value of the input is empty. + * + * For instance, the required directive does this to work out if the input has data or not. + * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. + * + * You can override this for input directives whose concept of being empty is different to the + * default. The `checkboxInputType` directive does this because in its case a value of `false` + * implies empty. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is empty. + */ + this.$isEmpty = function(value) { + return isUndefined(value) || value === '' || value === null || value !== value; + }; + var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here @@ -21449,15 +27373,13 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $element. - removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). - addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); + $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$setValidity - * @methodOf ng.directive:ngModel.NgModelController + * @ngdoc method + * @name ngModel.NgModelController#$setValidity * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it @@ -21466,14 +27388,17 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. + * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { + // Purposeful use of ! here to cast isValid to boolean in case it is undefined + // jshint -W018 if ($error[validationErrorKey] === !isValid) return; + // jshint +W018 if (isValid) { if ($error[validationErrorKey]) invalidCount--; @@ -21495,21 +27420,41 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ parentForm.$setValidity(validationErrorKey, isValid, this); }; + /** + * @ngdoc method + * @name ngModel.NgModelController#$setPristine + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the control to its pristine + * state (ng-pristine class). + */ + this.$setPristine = function () { + this.$dirty = false; + this.$pristine = true; + $animate.removeClass($element, DIRTY_CLASS); + $animate.addClass($element, PRISTINE_CLASS); + }; /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$setViewValue - * @methodOf ng.directive:ngModel.NgModelController + * @ngdoc method + * @name ngModel.NgModelController#$setViewValue * * @description - * Read a value from view. + * Update the view value. * - * This method should be called from within a DOM event handler. - * For example {@link ng.directive:input input} or + * This method should be called when the view value changes, typically from within a DOM event handler. + * For example {@link ng.directive:input input} and * {@link ng.directive:select select} directives call it. * - * It internally calls all `parsers` and if resulted value is valid, updates the model and - * calls all registered change listeners. + * It will update the $viewValue, then pass this value through each of the functions in `$parsers`, + * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to + * `$modelValue` and the **expression** specified in the `ng-model` attribute. + * + * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. + * + * Note that calling this function does not trigger a `$digest`. * * @param {string} value Value from the view. */ @@ -21520,7 +27465,8 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ if (this.$pristine) { this.$dirty = true; this.$pristine = false; - $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); + $animate.removeClass($element, PRISTINE_CLASS); + $animate.addClass($element, DIRTY_CLASS); parentForm.$setDirty(); } @@ -21537,7 +27483,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ } catch(e) { $exceptionHandler(e); } - }) + }); } }; @@ -21563,41 +27509,114 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ ctrl.$render(); } } + + return value; }); }]; /** * @ngdoc directive - * @name ng.directive:ngModel + * @name ngModel * * @element input * * @description - * Is directive that tells Angular to do two-way data binding. It works together with `input`, - * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. + * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a + * property on the scope using {@link ngModel.NgModelController NgModelController}, + * which is created and exposed by this directive. * * `ngModel` is responsible for: * - * - binding the view into the model, which other directives such as `input`, `textarea` or `select` - * require, - * - providing validation behavior (i.e. required, number, email, url), - * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), - * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), - * - register the control with parent {@link ng.directive:form form}. + * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` + * require. + * - Providing validation behavior (i.e. required, number, email, url). + * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors). + * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations. + * - Registering the control with its parent {@link ng.directive:form form}. + * + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. + * + * For best practices on using `ngModel`, see: + * + * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes] * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} - * - {@link ng.directive:input.text text} - * - {@link ng.directive:input.checkbox checkbox} - * - {@link ng.directive:input.radio radio} - * - {@link ng.directive:input.number number} - * - {@link ng.directive:input.email email} - * - {@link ng.directive:input.url url} + * - {@link input[text] text} + * - {@link input[checkbox] checkbox} + * - {@link input[radio] radio} + * - {@link input[number] number} + * - {@link input[email] email} + * - {@link input[url] url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * + * # CSS classes + * The following CSS classes are added and removed on the associated input/select/textarea element + * depending on the validity of the model. + * + * - `ng-valid` is set if the model is valid. + * - `ng-invalid` is set if the model is invalid. + * - `ng-pristine` is set if the model is pristine. + * - `ng-dirty` is set if the model is dirty. + * + * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * + * ## Animation Hooks + * + * Animations within models are triggered when any of the associated CSS classes are added and removed + * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, + * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. + * The animations that are triggered within ngModel are similar to how they work in ngClass and + * animations can be hooked into using CSS transitions, keyframes as well as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style an input element + * that has been rendered as invalid after it has been validated: + * + *
    + * //be sure to include ngAnimate as a module to hook into more
    + * //advanced animations
    + * .my-input {
    + *   transition:0.5s linear all;
    + *   background: white;
    + * }
    + * .my-input.ng-invalid {
    + *   background: red;
    + *   color:white;
    + * }
    + * 
    + * + * @example + * + + + + Update input to see transitions when valid/invalid. + Integer is a valid value. +
    + +
    +
    + *
    */ var ngModelDirective = function() { return { @@ -21611,7 +27630,7 @@ var ngModelDirective = function() { formCtrl.$addControl(modelCtrl); - element.bind('$destroy', function() { + scope.$on('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } @@ -21621,51 +27640,62 @@ var ngModelDirective = function() { /** * @ngdoc directive - * @name ng.directive:ngChange - * @restrict E + * @name ngChange * * @description - * Evaluate given expression when user changes the input. + * Evaluate the given expression when the user changes the input. + * The expression is evaluated immediately, unlike the JavaScript onchange event + * which only triggers at the end of a change (usually, when the user leaves the + * form element or presses the return key). * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input + * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change + * in input value. * * @example - * - * + * + * * - *
    + *
    * * *
    - * debug = {{confirmed}}
    - * counter = {{counter}} + * debug = {{confirmed}}
    + * counter = {{counter}}
    *
    - * - * + * + * + * var counter = element(by.binding('counter')); + * var debug = element(by.binding('confirmed')); + * * it('should evaluate the expression if changing from view', function() { - * expect(binding('counter')).toEqual('0'); - * element('#ng-change-example1').click(); - * expect(binding('counter')).toEqual('1'); - * expect(binding('confirmed')).toEqual('true'); + * expect(counter.getText()).toContain('0'); + * + * element(by.id('ng-change-example1')).click(); + * + * expect(counter.getText()).toContain('1'); + * expect(debug.getText()).toContain('true'); * }); * * it('should not evaluate the expression if changing from model', function() { - * element('#ng-change-example2').click(); - * expect(binding('counter')).toEqual('0'); - * expect(binding('confirmed')).toEqual('true'); + * element(by.id('ng-change-example2')).click(); + + * expect(counter.getText()).toContain('0'); + * expect(debug.getText()).toContain('true'); * }); - * - * + * + * */ var ngChangeDirective = valueFn({ require: 'ngModel', @@ -21685,7 +27715,7 @@ var requiredDirective = function() { attr.required = true; // force truthy in case we are on non input element var validator = function(value) { - if (attr.required && (isEmpty(value) || value === false)) { + if (attr.required && ctrl.$isEmpty(value)) { ctrl.$setValidity('required', false); return; } else { @@ -21707,47 +27737,58 @@ var requiredDirective = function() { /** * @ngdoc directive - * @name ng.directive:ngList + * @name ngList * * @description - * Text input that converts between comma-separated string into an array of strings. + * Text input that converts between a delimited string and an array of strings. The delimiter + * can be a fixed string (by default a comma) or a regular expression. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example - - + + -
    + List: - + Required! +
    names = {{names}}
    myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
    myForm.namesInput.$error = {{myForm.namesInput.$error}}
    myForm.$valid = {{myForm.$valid}}
    myForm.$error.required = {{!!myForm.$error.required}}
    -
    - + + + var listInput = element(by.model('names')); + var names = element(by.binding('{{names}}')); + var valid = element(by.binding('myForm.namesInput.$valid')); + var error = element(by.css('span.error')); + it('should initialize to model', function() { - expect(binding('names')).toEqual('["igor","misko","vojta"]'); - expect(binding('myForm.namesInput.$valid')).toEqual('true'); + expect(names.getText()).toContain('["igor","misko","vojta"]'); + expect(valid.getText()).toContain('true'); + expect(error.getCssValue('display')).toBe('none'); }); it('should be invalid if empty', function() { - input('names').enter(''); - expect(binding('names')).toEqual('[]'); - expect(binding('myForm.namesInput.$valid')).toEqual('false'); - }); - -
    + listInput.clear(); + listInput.sendKeys(''); + + expect(names.getText()).toContain(''); + expect(valid.getText()).toContain('false'); + expect(error.getCssValue('display')).not.toBe('none'); }); + + */ var ngListDirective = function() { return { @@ -21757,6 +27798,9 @@ var ngListDirective = function() { separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; + var list = []; if (viewValue) { @@ -21776,25 +27820,81 @@ var ngListDirective = function() { return undefined; }); + + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function(value) { + return !value || !value.length; + }; } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; +/** + * @ngdoc directive + * @name ngValue + * + * @description + * Binds the given expression to the value of `input[select]` or `input[radio]`, so + * that when the element is selected, the `ngModel` of that element is set to the + * bound value. + * + * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as + * shown below. + * + * @element input + * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute + * of the `input` element + * + * @example + + + +
    +

    Which is your favorite?

    + +
    You chose {{my.favorite}}
    +
    +
    + + var favorite = element(by.binding('my.favorite')); + it('should initialize to model', function() { + expect(favorite.getText()).toContain('unicorns'); + }); + it('should bind the values to the inputs', function() { + element.all(by.model('my.favorite')).get(0).click(); + expect(favorite.getText()).toContain('pizza'); + }); + +
    + */ var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { - return function(scope, elm, attr) { + return function ngValueConstantLink(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { - return function(scope, elm, attr) { + return function ngValueLink(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value, false); + attr.$set('value', value); }); }; } @@ -21804,7 +27904,8 @@ var ngValueDirective = function() { /** * @ngdoc directive - * @name ng.directive:ngBind + * @name ngBind + * @restrict AC * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element @@ -21814,10 +27915,9 @@ var ngValueDirective = function() { * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * - * One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when - * it's desirable to put bindings into template that is momentarily displayed by the browser in its - * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the - * bindings invisible to the user while the page is loading. + * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily + * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. @@ -21828,45 +27928,58 @@ var ngValueDirective = function() { * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. - - + + -
    +
    Enter name:
    Hello !
    - - + + it('should check ng-bind', function() { - expect(using('.doc-example-live').binding('name')).toBe('Whirled'); - using('.doc-example-live').input('name').enter('world'); - expect(using('.doc-example-live').binding('name')).toBe('world'); + var nameInput = element(by.model('name')); + + expect(element(by.binding('name')).getText()).toBe('Whirled'); + nameInput.clear(); + nameInput.sendKeys('world'); + expect(element(by.binding('name')).getText()).toBe('world'); }); - - + + */ -var ngBindDirective = ngDirective(function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBind); - scope.$watch(attr.ngBind, function ngBindWatchAction(value) { - element.text(value == undefined ? '' : value); - }); +var ngBindDirective = ngDirective({ + compile: function(templateElement) { + templateElement.addClass('ng-binding'); + return function (scope, element, attr) { + element.data('$binding', attr.ngBind); + scope.$watch(attr.ngBind, function ngBindWatchAction(value) { + // We are purposefully using == here rather than === because we want to + // catch when value is "null or undefined" + // jshint -W041 + element.text(value == undefined ? '' : value); + }); + }; + } }); /** * @ngdoc directive - * @name ng.directive:ngBindTemplate + * @name ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element - * text should be replaced with the template in ngBindTemplate. - * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` - * expressions. (This is required since some HTML elements - * can not have SPAN elements such as TITLE, or OPTION to name a few.) + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. * * @element ANY * @param {string} ngBindTemplate template of form @@ -21874,35 +27987,38 @@ var ngBindDirective = ngDirective(function(scope, element, attr) { * * @example * Try it here: enter text in text box and watch the greeting change. - - + + -
    +
    Salutation:
    Name:
    
            
    - - + + it('should check ng-bind', function() { - expect(using('.doc-example-live').binding('salutation')). - toBe('Hello'); - expect(using('.doc-example-live').binding('name')). - toBe('World'); - using('.doc-example-live').input('salutation').enter('Greetings'); - using('.doc-example-live').input('name').enter('user'); - expect(using('.doc-example-live').binding('salutation')). - toBe('Greetings'); - expect(using('.doc-example-live').binding('name')). - toBe('user'); + var salutationElem = element(by.binding('salutation')); + var salutationInput = element(by.model('salutation')); + var nameInput = element(by.model('name')); + + expect(salutationElem.getText()).toBe('Hello World!'); + + salutationInput.clear(); + salutationInput.sendKeys('Greetings'); + nameInput.clear(); + nameInput.sendKeys('user'); + + expect(salutationElem.getText()).toBe('Greetings user!'); }); - - + + */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { @@ -21912,152 +28028,351 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { attr.$observe('ngBindTemplate', function(value) { element.text(value); }); - } + }; }]; /** * @ngdoc directive - * @name ng.directive:ngBindHtmlUnsafe + * @name ngBindHtml * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if - * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too - * restrictive and when you absolutely trust the source of the content you are binding to. + * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link + * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` + * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in + * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. * - * See {@link ngSanitize.$sanitize $sanitize} docs for examples. + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) * * @element ANY - * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + * + * @example + Try it here: enter text in text box and watch the greeting change. + + + +
    +

    +
    +
    + + + angular.module('bindHtmlExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.myHTML = + 'I am an HTMLstring with ' + + 'links! and other stuff'; + }]); + + + + it('should check ng-bind-html', function() { + expect(element(by.binding('myHTML')).getText()).toBe( + 'I am an HTMLstring with links! and other stuff'); + }); + +
    */ -var ngBindHtmlUnsafeDirective = [function() { - return function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); - scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) { - element.html(value || ''); - }); +var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { + return { + compile: function (tElement) { + tElement.addClass('ng-binding'); + + return function (scope, element, attr) { + element.data('$binding', attr.ngBindHtml); + + var parsed = $parse(attr.ngBindHtml); + + function getStringValue() { + return (parsed(scope) || '').toString(); + } + + scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { + element.html($sce.getTrustedHtml(parsed(scope)) || ''); + }); + }; + } }; }]; function classDirective(name, selector) { name = 'ngClass' + name; - return ngDirective(function(scope, element, attr) { - var oldVal = undefined; + return ['$animate', function($animate) { + return { + restrict: 'AC', + link: function(scope, element, attr) { + var oldVal; - scope.$watch(attr[name], ngClassWatchAction, true); + scope.$watch(attr[name], ngClassWatchAction, true); - attr.$observe('class', function(value) { - var ngClass = scope.$eval(attr[name]); - ngClassWatchAction(ngClass, ngClass); - }); + attr.$observe('class', function(value) { + ngClassWatchAction(scope.$eval(attr[name])); + }); + + + if (name !== 'ngClass') { + scope.$watch('$index', function($index, old$index) { + // jshint bitwise: false + var mod = $index & 1; + if (mod !== (old$index & 1)) { + var classes = arrayClasses(scope.$eval(attr[name])); + mod === selector ? + addClasses(classes) : + removeClasses(classes); + } + }); + } + + function addClasses(classes) { + var newClasses = digestClassCounts(classes, 1); + attr.$addClass(newClasses); + } + + function removeClasses(classes) { + var newClasses = digestClassCounts(classes, -1); + attr.$removeClass(newClasses); + } + + function digestClassCounts (classes, count) { + var classCounts = element.data('$classCounts') || {}; + var classesToUpdate = []; + forEach(classes, function (className) { + if (count > 0 || classCounts[className]) { + classCounts[className] = (classCounts[className] || 0) + count; + if (classCounts[className] === +(count > 0)) { + classesToUpdate.push(className); + } + } + }); + element.data('$classCounts', classCounts); + return classesToUpdate.join(' '); + } + function updateClasses (oldClasses, newClasses) { + var toAdd = arrayDifference(newClasses, oldClasses); + var toRemove = arrayDifference(oldClasses, newClasses); + toRemove = digestClassCounts(toRemove, -1); + toAdd = digestClassCounts(toAdd, 1); - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - var mod = $index & 1; - if (mod !== old$index & 1) { - if (mod === selector) { - addClass(scope.$eval(attr[name])); + if (toAdd.length === 0) { + $animate.removeClass(element, toRemove); + } else if (toRemove.length === 0) { + $animate.addClass(element, toAdd); } else { - removeClass(scope.$eval(attr[name])); + $animate.setClass(element, toAdd, toRemove); } } - }); - } - - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - if (oldVal && !equals(newVal,oldVal)) { - removeClass(oldVal); + function ngClassWatchAction(newVal) { + if (selector === true || scope.$index % 2 === selector) { + var newClasses = arrayClasses(newVal || []); + if (!oldVal) { + addClasses(newClasses); + } else if (!equals(newVal,oldVal)) { + var oldClasses = arrayClasses(oldVal); + updateClasses(oldClasses, newClasses); + } + } + oldVal = shallowCopy(newVal); } - addClass(newVal); } - oldVal = copy(newVal); - } + }; + function arrayDifference(tokens1, tokens2) { + var values = []; - function removeClass(classVal) { - if (isObject(classVal) && !isArray(classVal)) { - classVal = map(classVal, function(v, k) { if (v) return k }); + outer: + for(var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for(var j = 0; j < tokens2.length; j++) { + if(token == tokens2[j]) continue outer; + } + values.push(token); } - element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal); + return values; } - - function addClass(classVal) { - if (isObject(classVal) && !isArray(classVal)) { - classVal = map(classVal, function(v, k) { if (v) return k }); - } - if (classVal) { - element.addClass(isArray(classVal) ? classVal.join(' ') : classVal); + function arrayClasses (classVal) { + if (isArray(classVal)) { + return classVal; + } else if (isString(classVal)) { + return classVal.split(' '); + } else if (isObject(classVal)) { + var classes = [], i = 0; + forEach(classVal, function(v, k) { + if (v) { + classes = classes.concat(k.split(' ')); + } + }); + return classes; } + return classVal; } - }); + }]; } /** * @ngdoc directive - * @name ng.directive:ngClass + * @name ngClass + * @restrict AC * * @description - * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an - * expression that represents all classes to be added. + * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding + * an expression that represents all classes to be added. + * + * The directive operates in three different ways, depending on which of three types the expression + * evaluates to: + * + * 1. If the expression evaluates to a string, the string should be one or more space-delimited class + * names. + * + * 2. If the expression evaluates to an array, each element of the array should be a string that is + * one or more space-delimited class names. + * + * 3. If the expression evaluates to an object, then for each key-value pair of the + * object with a truthy value the corresponding key is used as a class name. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * + * @animations + * add - happens just before the class is applied to the element + * remove - happens just before the class is removed from the element + * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. * - * @example + * @example Example that demonstrates basic bindings via ngClass directive. - - +

    Map Syntax Example

    + deleted (apply "strike" class)
    + important (apply "bold" class)
    + error (apply "red" class) +
    +

    Using String Syntax

    + +
    +

    Using Array Syntax

    +
    +
    +
    +
    + + .strike { + text-decoration: line-through; + } + .bold { + font-weight: bold; + } + .red { + color: red; + } + + + var ps = element.all(by.css('p')); + + it('should let you toggle the class', function() { + + expect(ps.first().getAttribute('class')).not.toMatch(/bold/); + expect(ps.first().getAttribute('class')).not.toMatch(/red/); + + element(by.model('important')).click(); + expect(ps.first().getAttribute('class')).toMatch(/bold/); + + element(by.model('error')).click(); + expect(ps.first().getAttribute('class')).toMatch(/red/); + }); + + it('should let you toggle string example', function() { + expect(ps.get(1).getAttribute('class')).toBe(''); + element(by.model('style')).clear(); + element(by.model('style')).sendKeys('red'); + expect(ps.get(1).getAttribute('class')).toBe('red'); + }); + + it('array example should have 3 classes', function() { + expect(ps.last().getAttribute('class')).toBe(''); + element(by.model('style1')).sendKeys('bold'); + element(by.model('style2')).sendKeys('strike'); + element(by.model('style3')).sendKeys('red'); + expect(ps.last().getAttribute('class')).toBe('bold strike red'); + }); + +
    + + ## Animations + + The example below demonstrates how to perform animations using ngClass. + + + + +
    - Sample Text + Sample Text
    - .my-class { + .base-class { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .base-class.my-class { color: red; + font-size:3em; } - + it('should check ng-class', function() { - expect(element('.doc-example-live span').prop('className')).not(). + expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); - using('.doc-example-live').element(':button:first').click(); + element(by.id('setbtn')).click(); - expect(element('.doc-example-live span').prop('className')). + expect(element(by.css('.base-class')).getAttribute('class')). toMatch(/my-class/); - using('.doc-example-live').element(':button:last').click(); + element(by.id('clearbtn')).click(); - expect(element('.doc-example-live span').prop('className')).not(). + expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); });
    + + + ## ngClass and pre-existing CSS3 Transitions/Animations + The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. + Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder + any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure + to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and + {@link ngAnimate.$animate#removeclass $animate.removeClass}. */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive - * @name ng.directive:ngClassOdd + * @name ngClassOdd + * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except it works in - * conjunction with `ngRepeat` and takes affect only on odd (even) rows. + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. * - * This directive can be applied only within a scope of an + * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY @@ -22083,11 +28398,11 @@ var ngClassDirective = classDirective('', true); color: blue; } - + it('should check ng-class-odd and ng-class-even', function() { - expect(element('.doc-example-live li:first span').prop('className')). + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); - expect(element('.doc-example-live li:last span').prop('className')). + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); @@ -22097,14 +28412,15 @@ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive - * @name ng.directive:ngClassEven + * @name ngClassEven + * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except it works in - * conjunction with `ngRepeat` and takes affect only on odd (even) rows. + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. * - * This directive can be applied only within a scope of an + * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY @@ -22130,11 +28446,11 @@ var ngClassOddDirective = classDirective('Odd', 0); color: blue; } - + it('should check ng-class-odd and ng-class-even', function() { - expect(element('.doc-example-live li:first span').prop('className')). + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); - expect(element('.doc-example-live li:last span').prop('className')). + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); @@ -22144,55 +28460,58 @@ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive - * @name ng.directive:ngCloak + * @name ngCloak + * @restrict AC * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * - * The directive can be applied to the `` element, but typically a fine-grained application is - * prefered in order to benefit from progressive rendering of the browser view. + * The directive can be applied to the `` element, but the preferred usage is to apply + * multiple `ngCloak` directives to small portions of the page to permit progressive rendering + * of the browser view. * - * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and - * `angular.min.js` files. Following is the css rule: + * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and + * `angular.min.js`. + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * - *
    + * ```css
      * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    - *   display: none;
    + *   display: none !important;
      * }
    - * 
    + * ``` * * When this css rule is loaded by the browser, all html elements (including their children) that - * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive - * during the compilation of the template it deletes the `ngCloak` element attribute, which - * makes the compiled element visible. + * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive + * during the compilation of the template it deletes the `ngCloak` element attribute, making + * the compiled element visible. * - * For the best result, `angular.js` script must be loaded in the head section of the html file; - * alternatively, the css rule (above) must be included in the external stylesheet of the + * For the best result, the `angular.js` script must be loaded in the head section of the html + * document; alternatively, the css rule above must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css - * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. + * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. * * @element ANY * * @example - - + +
    {{ 'hello' }}
    {{ 'hello IE7' }}
    -
    - +
    + it('should remove the template directive and css class', function() { - expect(element('.doc-example-live #template1').attr('ng-cloak')). - not().toBeDefined(); - expect(element('.doc-example-live #template2').attr('ng-cloak')). - not().toBeDefined(); + expect($('#template1').getAttribute('ng-cloak')). + toBeNull(); + expect($('#template2').getAttribute('ng-cloak')). + toBeNull(); }); - - + + * */ var ngCloakDirective = ngDirective({ @@ -22204,175 +28523,315 @@ var ngCloakDirective = ngDirective({ /** * @ngdoc directive - * @name ng.directive:ngController + * @name ngController * * @description - * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular + * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * - * * Model — The Model is data in scope properties; scopes are attached to the DOM. - * * View — The template (HTML with data bindings) is rendered into the View. - * * Controller — The `ngController` directive specifies a Controller class; the class has - * methods that typically express the business logic behind the application. + * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties + * are accessed through bindings. + * * View — The template (HTML with data bindings) that is rendered into the View. + * * Controller — The `ngController` directive specifies a Controller class; the class contains business + * logic behind the application to decorate the scope with functions and values * - * Note that an alternative way to define controllers is via the {@link ng.$route $route} service. + * Note that you can also attach controllers to the DOM by declaring it in a route definition + * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller + * again using `ng-controller` in the template itself. This will cause the controller to be attached + * and executed twice. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a - * constructor function. + * constructor function. The controller instance can be published into a scope property + * by specifying `as propertyName`. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can - * easily be called from the angular markup. Notice that the scope becomes the `this` for the - * controller's instance. This allows for easy access to the view data from the controller. Also - * notice that any changes to the data are automatically reflected in the View without the need - * for a manual update. - - - -
    - Name: - [ greet ]
    - Contact: -
      -
    • - - - [ clear - | X ] -
    • -
    • [ add ]
    • -
    -
    -
    - - it('should check controller', function() { - expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); - expect(element('.doc-example-live li:nth-child(1) input').val()) - .toBe('408 555 1212'); - expect(element('.doc-example-live li:nth-child(2) input').val()) - .toBe('john.smith@example.org'); - - element('.doc-example-live li:first a:contains("clear")').click(); - expect(element('.doc-example-live li:first input').val()).toBe(''); - - element('.doc-example-live li:last a:contains("add")').click(); - expect(element('.doc-example-live li:nth-child(3) input').val()) - .toBe('yourname@example.org'); - }); - -
    */ var ngControllerDirective = [function() { return { scope: true, - controller: '@' + controller: '@', + priority: 500 }; }]; /** * @ngdoc directive - * @name ng.directive:ngCsp - * @priority 1000 + * @name ngCsp * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. - * + * * This is necessary when developing things like Google Chrome Extensions. - * + * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). - * For us to be compatible, we just need to implement the "getterFn" in $parse without violating - * any of these restrictions. - * - * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp` - * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will + * For Angular to be CSP compatible there are only two things that we need to do differently: + * + * - don't use `Function` constructor to generate optimized value getters + * - don't inject custom stylesheet into the document + * + * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` + * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. - * - * In order to use this feature put `ngCsp` directive on the root element of the application. - * + * + * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically + * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). + * To make those directives work in CSP mode, include the `angular-csp.css` manually. + * + * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This + * autodetection however triggers a CSP error to be logged in the console: + * + * ``` + * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of + * script in the following Content Security Policy directive: "default-src 'self'". Note that + * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. + * ``` + * + * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` + * directive on the root element of the application or on the `angular.js` script tag, whichever + * appears first in the html document. + * + * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* + * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. -
    +   ```html
          
          
          ...
          ...
          
    -   
    + ``` */ -var ngCspDirective = ['$sniffer', function($sniffer) { - return { - priority: 1000, - compile: function() { - $sniffer.csp = true; - } - }; -}]; +// ngCsp is not implemented as a proper directive any more, because we need it be processed while we +// bootstrap the system (before $parse is instantiated), for this reason we just have +// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc /** * @ngdoc directive - * @name ng.directive:ngClick + * @name ngClick * * @description - * The ngClick allows you to specify custom behavior when - * element is clicked. + * The ngClick directive allows you to specify custom behavior when + * an element is clicked. * * @element ANY + * @priority 0 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon - * click. (Event object is available as `$event`) + * click. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example - - + + count: {{count}} - - + + it('should check ng-click', function() { - expect(binding('count')).toBe('0'); - element('.doc-example-live :button').click(); - expect(binding('count')).toBe('1'); + expect(element(by.binding('count')).getText()).toMatch('0'); + element(by.css('button')).click(); + expect(element(by.binding('count')).getText()).toMatch('1'); }); - - + + */ /* * A directive that allows creation of custom onclick handlers that are defined as angular @@ -22382,17 +28841,21 @@ var ngCspDirective = ['$sniffer', function($sniffer) { */ var ngEventDirectives = {}; forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), + 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { - return function(scope, element, attr) { - var fn = $parse(attr[directiveName]); - element.bind(lowercase(name), function(event) { - scope.$apply(function() { - fn(scope, {$event:event}); - }); - }); + return { + compile: function($element, attr) { + var fn = $parse(attr[directiveName]); + return function ngEventHandler(scope, element) { + element.on(lowercase(name), function(event) { + scope.$apply(function() { + fn(scope, {$event:event}); + }); + }); + }; + } }; }]; } @@ -22400,188 +28863,556 @@ forEach( /** * @ngdoc directive - * @name ng.directive:ngDblclick + * @name ngDblclick + * + * @description + * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. + * + * @element ANY + * @priority 0 + * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon + * a dblclick. (The Event object is available as `$event`) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMousedown + * + * @description + * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon + * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseup + * + * @description + * Specify custom behavior on mouseup event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon + * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + +/** + * @ngdoc directive + * @name ngMouseover + * + * @description + * Specify custom behavior on mouseover event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon + * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseenter + * + * @description + * Specify custom behavior on mouseenter event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon + * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseleave + * + * @description + * Specify custom behavior on mouseleave event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon + * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMousemove + * + * @description + * Specify custom behavior on mousemove event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon + * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngKeydown * * @description - * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. + * Specify custom behavior on keydown event. * * @element ANY - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * dblclick. (Event object is available as `$event`) + * @priority 0 + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example - * See {@link ng.directive:ngClick ngClick} + + + + key down count: {{count}} + + */ /** * @ngdoc directive - * @name ng.directive:ngMousedown + * @name ngKeyup * * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * Specify custom behavior on keyup event. * * @element ANY - * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon - * mousedown. (Event object is available as `$event`) + * @priority 0 + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example - * See {@link ng.directive:ngClick ngClick} + + +

    Typing in the input box below updates the key count

    + key up count: {{count}} + +

    Typing in the input box below updates the keycode

    + +

    event keyCode: {{ event.keyCode }}

    +

    event altKey: {{ event.altKey }}

    +
    +
    */ /** * @ngdoc directive - * @name ng.directive:ngMouseup + * @name ngKeypress * * @description - * Specify custom behavior on mouseup event. + * Specify custom behavior on keypress event. * * @element ANY - * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon - * mouseup. (Event object is available as `$event`) + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. ({@link guide/expression#-event- Event object is available as `$event`} + * and can be interrogated for keyCode, altKey, etc.) * * @example - * See {@link ng.directive:ngClick ngClick} + + + + key press count: {{count}} + + */ + /** * @ngdoc directive - * @name ng.directive:ngMouseover + * @name ngSubmit * * @description - * Specify custom behavior on mouseover event. + * Enables binding angular expressions to onsubmit events. * - * @element ANY - * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon - * mouseover. (Event object is available as `$event`) + * Additionally it prevents the default action (which for form means sending the request to the + * server and reloading the current page), but only if the form does not contain `action`, + * `data-action`, or `x-action` attributes. + * + *
    + * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and + * `ngSubmit` handlers together. See the + * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} + * for a detailed discussion of when `ngSubmit` may be triggered. + *
    + * + * @element form + * @priority 0 + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * ({@link guide/expression#-event- Event object is available as `$event`}) * * @example - * See {@link ng.directive:ngClick ngClick} + + + +
    + Enter text and hit enter: + + +
    list={{list}}
    +
    +
    + + it('should check ng-submit', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + expect(element(by.model('text')).getAttribute('value')).toBe(''); + }); + it('should ignore empty strings', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + }); + +
    */ - /** * @ngdoc directive - * @name ng.directive:ngMouseenter + * @name ngFocus * * @description - * Specify custom behavior on mouseenter event. + * Specify custom behavior on focus event. * - * @element ANY - * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon - * mouseenter. (Event object is available as `$event`) + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ - /** * @ngdoc directive - * @name ng.directive:ngMouseleave + * @name ngBlur * * @description - * Specify custom behavior on mouseleave event. + * Specify custom behavior on blur event. * - * @element ANY - * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon - * mouseleave. (Event object is available as `$event`) + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ - /** * @ngdoc directive - * @name ng.directive:ngMousemove + * @name ngCopy * * @description - * Specify custom behavior on mousemove event. + * Specify custom behavior on copy event. * - * @element ANY - * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon - * mousemove. (Event object is available as `$event`) + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon + * copy. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example - * See {@link ng.directive:ngClick ngClick} + + + + copied: {{copied}} + + */ +/** + * @ngdoc directive + * @name ngCut + * + * @description + * Specify custom behavior on cut event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon + * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + cut: {{cut}} + + + */ /** * @ngdoc directive - * @name ng.directive:ngSubmit + * @name ngPaste * * @description - * Enables binding angular expressions to onsubmit events. + * Specify custom behavior on paste event. * - * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page). + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon + * paste. ({@link guide/expression#-event- Event object is available as `$event`}) * - * @element form - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * @example + + + + pasted: {{paste}} + + + */ + +/** + * @ngdoc directive + * @name ngIf + * @restrict A + * + * @description + * The `ngIf` directive removes or recreates a portion of the DOM tree based on an + * {expression}. If the expression assigned to `ngIf` evaluates to a false + * value then the element is removed from the DOM, otherwise a clone of the + * element is reinserted into the DOM. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope + * is created when the element is restored. The scope created within `ngIf` inherits from + * its parent scope using + * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance). + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` + * and `leave` effects. + * + * @animations + * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container + * leave - happens just before the ngIf contents are removed from the DOM + * + * @element ANY + * @scope + * @priority 600 + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree. If it is truthy a copy of the compiled + * element is added to the DOM tree. * * @example - - - -
    - Enter text and hit enter: - - -
    list={{list}}
    -
    -
    - - it('should check ng-submit', function() { - expect(binding('list')).toBe('[]'); - element('.doc-example-live #submit').click(); - expect(binding('list')).toBe('["hello"]'); - expect(input('text').val()).toBe(''); - }); - it('should ignore empty strings', function() { - expect(binding('list')).toBe('[]'); - element('.doc-example-live #submit').click(); - element('.doc-example-live #submit').click(); - expect(binding('list')).toBe('["hello"]'); - }); - -
    + + + Click me:
    + Show when checked: + + I'm removed when the checkbox is unchecked. + +
    + + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } + + .animate-if.ng-enter, .animate-if.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } + + .animate-if.ng-leave, + .animate-if.ng-enter.ng-enter-active { + opacity:1; + } + +
    */ -var ngSubmitDirective = ngDirective(function(scope, element, attrs) { - element.bind('submit', function() { - scope.$apply(attrs.ngSubmit); - }); -}); +var ngIfDirective = ['$animate', function($animate) { + return { + transclude: 'element', + priority: 600, + terminal: true, + restrict: 'A', + $$tlb: true, + link: function ($scope, $element, $attr, ctrl, $transclude) { + var block, childScope, previousElements; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + + if (toBoolean(value)) { + if (!childScope) { + childScope = $scope.$new(); + $transclude(childScope, function (clone) { + clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block = { + clone: clone + }; + $animate.enter(clone, $element.parent(), $element); + }); + } + } else { + if(previousElements) { + previousElements.remove(); + previousElements = null; + } + if(childScope) { + childScope.$destroy(); + childScope = null; + } + if(block) { + previousElements = getBlockElements(block.clone); + $animate.leave(previousElements, function() { + previousElements = null; + }); + block = null; + } + } + }); + } + }; +}]; /** * @ngdoc directive - * @name ng.directive:ngInclude + * @name ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * - * Keep in mind that Same Origin Policy applies to included resources - * (e.g. ngInclude won't work for cross-domain requests on all browsers and for - * file:// access on some browsers). + * By default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols + * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or + * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link + * ng.$sce Strict Contextual Escaping}. + * + * In addition, the browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy may further restrict whether the template is successfully loaded. + * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. * * @scope + * @priority 400 * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, - * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. + * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll @@ -22592,24 +29423,27 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example - + -
    +
    url of the template: {{template.url}}
    -
    +
    +
    +
    - function Ctrl($scope) { - $scope.templates = - [ { name: 'template1.html', url: 'template1.html'} - , { name: 'template2.html', url: 'template2.html'} ]; - $scope.template = $scope.templates[0]; - } + angular.module('includeExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.templates = + [ { name: 'template1.html', url: 'template1.html'}, + { name: 'template2.html', url: 'template2.html'} ]; + $scope.template = $scope.templates[0]; + }]); Content of template1.html @@ -22617,19 +29451,73 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { Content of template2.html - + + .slide-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .slide-animate { + padding:10px; + } + + .slide-animate.ng-enter, .slide-animate.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .slide-animate.ng-enter { + top:-50px; + } + .slide-animate.ng-enter.ng-enter-active { + top:0; + } + + .slide-animate.ng-leave { + top:0; + } + .slide-animate.ng-leave.ng-leave-active { + top:50px; + } + + + var templateSelect = element(by.model('template')); + var includeElem = element(by.css('[ng-include]')); + it('should load template1.html', function() { - expect(element('.doc-example-live [ng-include]').text()). - toMatch(/Content of template1.html/); + expect(includeElem.getText()).toMatch(/Content of template1.html/); }); + it('should load template2.html', function() { - select('template').option('1'); - expect(element('.doc-example-live [ng-include]').text()). - toMatch(/Content of template2.html/); + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + // See https://github.com/angular/protractor/issues/480 + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(2).click(); + expect(includeElem.getText()).toMatch(/Content of template2.html/); }); + it('should change to blank', function() { - select('template').option(''); - expect(element('.doc-example-live [ng-include]').text()).toEqual(''); + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(0).click(); + expect(includeElem.isPresent()).toBe(false); }); @@ -22638,155 +29526,242 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { /** * @ngdoc event - * @name ng.directive:ngInclude#$includeContentLoaded - * @eventOf ng.directive:ngInclude + * @name ngInclude#$includeContentRequested + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentLoaded * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ -var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', - function($http, $templateCache, $anchorScroll, $compile) { +var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', + function($http, $templateCache, $anchorScroll, $animate, $sce) { return { restrict: 'ECA', + priority: 400, terminal: true, + transclude: 'element', + controller: angular.noop, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; - return function(scope, element) { + return function(scope, $element, $attr, ctrl, $transclude) { var changeCounter = 0, - childScope; - - var clearContent = function() { - if (childScope) { - childScope.$destroy(); - childScope = null; + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if(previousElement) { + previousElement.remove(); + previousElement = null; + } + if(currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement, function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; } - - element.html(''); }; - scope.$watch(srcExp, function ngIncludeWatchAction(src) { + scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { + var afterAnimation = function() { + if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }; var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + ctrl.template = response; + + // Note: This will also link all children of ng-include that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-include on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, null, $element, afterAnimation); + }); - if (childScope) childScope.$destroy(); - childScope = scope.$new(); - - element.html(response); - $compile(element.contents())(childScope); - - if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); - } + currentScope = newScope; + currentElement = clone; - childScope.$emit('$includeContentLoaded'); + currentScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { - if (thisChangeId === changeCounter) clearContent(); + if (thisChangeId === changeCounter) cleanupLastIncludeContent(); }); - } else clearContent(); + scope.$emit('$includeContentRequested'); + } else { + cleanupLastIncludeContent(); + ctrl.template = null; + } }); }; } }; }]; +// This directive is called during the $transclude call of the first `ngInclude` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngInclude +// is called. +var ngIncludeFillContentDirective = ['$compile', + function($compile) { + return { + restrict: 'ECA', + priority: -400, + require: 'ngInclude', + link: function(scope, $element, $attr, ctrl) { + $element.html(ctrl.template); + $compile($element.contents())(scope); + } + }; + }]; + /** * @ngdoc directive - * @name ng.directive:ngInit + * @name ngInit + * @restrict AC * * @description - * The `ngInit` directive specifies initialization tasks to be executed - * before the template enters execution mode during bootstrap. + * The `ngInit` directive allows you to evaluate an expression in the + * current scope. + * + *
    + * The only appropriate use of `ngInit` is for aliasing special properties of + * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you + * should use {@link guide/controller controllers} rather than `ngInit` + * to initialize values on a scope. + *
    + *
    + * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make + * sure you have parenthesis for correct precedence: + *
    + *   
    + *
    + *
    + * + * @priority 450 * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example - - -
    - {{greeting}} {{person}}! -
    -
    - - it('should check greeting', function() { - expect(binding('greeting')).toBe('Hello'); - expect(binding('person')).toBe('World'); + + + +
    +
    +
    + list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; +
    +
    +
    +
    + + it('should alias index positions', function() { + var elements = element.all(by.css('.example-init')); + expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); + expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); + expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); + expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); -
    -
    +
    + */ var ngInitDirective = ngDirective({ + priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } - } + }; } }); /** * @ngdoc directive - * @name ng.directive:ngNonBindable + * @name ngNonBindable + * @restrict AC * @priority 1000 * * @description - * Sometimes it is necessary to write code which looks like bindings but which should be left alone - * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. + * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current + * DOM element. This is useful if the element contains what appears to be Angular directives and + * bindings but which should be ignored by Angular. This could be the case if you have a site that + * displays snippets of code, for instance. * * @element ANY * * @example - * In this example there are two location where a simple binding (`{{}}`) is present, but the one - * wrapped in `ngNonBindable` is left alone. + * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, + * but the one wrapped in `ngNonBindable` is left alone. * * @example - - + +
    Normal: {{1 + 2}}
    Ignored: {{1 + 2}}
    -
    - +
    + it('should check ng-non-bindable', function() { - expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); - expect(using('.doc-example-live').element('div:last').text()). - toMatch(/1 \+ 2/); + expect(element(by.binding('1 + 2')).getText()).toContain('3'); + expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); }); - - + + */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive - * @name ng.directive:ngPluralize + * @name ngPluralize * @restrict EA * * @description - * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. - * These rules are bundled with angular.js and the rules can be overridden + * These rules are bundled with angular.js, but can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between - * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - * plural categories} and the strings to be displayed. + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * and the strings to be displayed. * * # Plural categories and explicit number rules * There are two - * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - * plural categories} in Angular's default en-US locale: "one" and "other". + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * in Angular's default en-US locale: "one" and "other". * - * While a pural category may match many numbers (for example, in en-US locale, "other" can match + * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the - * explicit number rule for "3" matches the number 3. You will see the use of plural categories - * and explicit number rules throughout later parts of this documentation. + * explicit number rule for "3" matches the number 3. There are examples of plural categories + * and explicit number rules throughout the rest of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. @@ -22796,18 +29771,17 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual - * string to be displayed. The value of the attribute should be a JSON object so that Angular - * can interpret it correctly. + * string to be displayed. The value of the attribute should be a JSON object. * * The following example shows how to configure ngPluralize: * - *
    + * ```html
      * 
      * 
    - *
    + *``` * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" @@ -22815,7 +29789,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * - * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted + * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * `{{personCount}}`. The closed braces `{}` is a placeholder * for {{numberExpression}}. @@ -22827,7 +29801,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * - *
    + * ```html
      * 
      * 
    - * 
    + * ``` * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. - * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" + * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for @@ -22850,21 +29824,22 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * - * @param {string|expression} count The variable to be bounded to. - * @param {string} when The mapping between plural category to its correspoding strings. + * @param {string|expression} count The variable to be bound to. + * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example - - + + -
    +
    Person 1:
    Person 2:
    Number of People:
    @@ -22887,51 +29862,55 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
    - - + + it('should show correct pluralized string', function() { - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('1 person is viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor is viewing.'); - - using('.doc-example-live').input('personCount').enter('0'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('Nobody is viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Nobody is viewing.'); - - using('.doc-example-live').input('personCount').enter('2'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('2 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor and Misko are viewing.'); - - using('.doc-example-live').input('personCount').enter('3'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('3 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and one other person are viewing.'); - - using('.doc-example-live').input('personCount').enter('4'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('4 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and 2 other people are viewing.'); - }); + var withoutOffset = element.all(by.css('ng-pluralize')).get(0); + var withOffset = element.all(by.css('ng-pluralize')).get(1); + var countInput = element(by.model('personCount')); - it('should show data-binded names', function() { - using('.doc-example-live').input('personCount').enter('4'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and 2 other people are viewing.'); + expect(withoutOffset.getText()).toEqual('1 person is viewing.'); + expect(withOffset.getText()).toEqual('Igor is viewing.'); - using('.doc-example-live').input('person1').enter('Di'); - using('.doc-example-live').input('person2').enter('Vojta'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Di, Vojta and 2 other people are viewing.'); + countInput.clear(); + countInput.sendKeys('0'); + + expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); + expect(withOffset.getText()).toEqual('Nobody is viewing.'); + + countInput.clear(); + countInput.sendKeys('2'); + + expect(withoutOffset.getText()).toEqual('2 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); + + countInput.clear(); + countInput.sendKeys('3'); + + expect(withoutOffset.getText()).toEqual('3 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); + + countInput.clear(); + countInput.sendKeys('4'); + + expect(withoutOffset.getText()).toEqual('4 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); + }); + it('should show data-bound names', function() { + var withOffset = element.all(by.css('ng-pluralize')).get(1); + var personCount = element(by.model('personCount')); + var person1 = element(by.model('person1')); + var person2 = element(by.model('person2')); + personCount.clear(); + personCount.sendKeys('4'); + person1.clear(); + person1.sendKeys('Di'); + person2.clear(); + person2.sendKeys('Vojta'); + expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); - - + + */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; @@ -22939,13 +29918,20 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, - whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, - whens = scope.$eval(whenExp), + whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(); + endSymbol = $interpolate.endSymbol(), + isWhen = /^when(Minus)?(.+)$/; + forEach(attr, function(expression, attributeName) { + if (isWhen.test(attributeName)) { + whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = + element.attr(attr.$attr[attributeName]); + } + }); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + @@ -22972,7 +29958,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp /** * @ngdoc directive - * @name ng.directive:ngRepeat + * @name ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template @@ -22981,278 +29967,725 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * * Special properties are exposed on the local scope of each template instance, including: * - * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) - * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. - * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. - * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. - * + * | Variable | Type | Details | + * |-----------|-----------------|-----------------------------------------------------------------------------| + * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | + * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | + * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | + * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | + * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | + * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | + * + * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. + * This may be useful when, for instance, nesting ngRepeats. + * + * # Special repeat start and end points + * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending + * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. + * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) + * up to and including the ending HTML tag where **ng-repeat-end** is placed. + * + * The example below makes use of this feature: + * ```html + *
    + * Header {{ item }} + *
    + *
    + * Body {{ item }} + *
    + *
    + * Footer {{ item }} + *
    + * ``` + * + * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: + * ```html + *
    + * Header A + *
    + *
    + * Body A + *
    + *
    + * Footer A + *
    + *
    + * Header B + *
    + *
    + * Body B + *
    + *
    + * Footer B + *
    + * ``` + * + * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such + * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). + * + * @animations + * **.enter** - when a new item is added to the list or when an item is revealed after a filter + * + * **.leave** - when an item is removed from the list or when an item is filtered out + * + * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 - * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two + * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * - * For example: `track in cd.tracks`. + * For example: `album in artist.albums`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * + * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function + * which can be used to associate the objects in the collection with the DOM elements. If no tracking function + * is specified the ng-repeat associates elements by identity in the collection. It is an error to have + * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are + * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, + * before specifying a tracking expression. + * + * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements + * will be associated by item identity in the array. + * + * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements + * with the corresponding item in the array by identity. Moving the same object in array would move the DOM + * element in the same way in the DOM. + * + * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this + * case the object identity does not matter. Two objects are considered equivalent as long as their `id` + * property is same. + * + * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter + * to items in conjunction with a tracking expression. + * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: - - -
    - I have {{friends.length}} friends. They are: -
      -
    • - [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. -
    • -
    -
    -
    - - it('should check ng-repeat', function() { - var r = using('.doc-example-live').repeater('ul li'); - expect(r.count()).toBe(2); - expect(r.row(0)).toEqual(["1","John","25"]); - expect(r.row(1)).toEqual(["2","Mary","28"]); - }); - -
    - */ -var ngRepeatDirective = ngDirective({ - transclude: 'element', - priority: 1000, - terminal: true, - compile: function(element, attr, linker) { - return function(scope, iterStartElement, attr){ - var expression = attr.ngRepeat; - var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), - lhs, rhs, valueIdent, keyIdent; - if (! match) { - throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + - expression + "'."); + + +
    + I have {{friends.length}} friends. They are: + +
      +
    • + [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. +
    • +
    +
    +
    + + .example-animate-container { + background:white; + border:1px solid black; + list-style:none; + margin:0; + padding:0 10px; + } + + .animate-repeat { + line-height:40px; + list-style:none; + box-sizing:border-box; + } + + .animate-repeat.ng-move, + .animate-repeat.ng-enter, + .animate-repeat.ng-leave { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; } - lhs = match[1]; - rhs = match[2]; - match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); - if (!match) { - throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + - lhs + "'."); + + .animate-repeat.ng-leave.ng-leave-active, + .animate-repeat.ng-move, + .animate-repeat.ng-enter { + opacity:0; + max-height:0; } - valueIdent = match[3] || match[1]; - keyIdent = match[2]; - - // Store a list of elements from previous run. This is a hash where key is the item from the - // iterator, and the value is an array of objects with following properties. - // - scope: bound scope - // - element: previous element. - // - index: position - // We need an array of these objects since the same object can be returned from the iterator. - // We expect this to be a rare case. - var lastOrder = new HashQueueMap(); - - scope.$watch(function ngRepeatWatch(scope){ - var index, length, - collection = scope.$eval(rhs), - cursor = iterStartElement, // current position of the node - // Same as lastOrder but it has the current state. It will become the - // lastOrder on the next iteration. - nextOrder = new HashQueueMap(), - arrayBound, - childScope, - key, value, // key/value of iteration - array, - last; // last object information {scope, element, index} - - - - if (!isArray(collection)) { - // if object, extract keys, sort them and use to determine order of iteration over obj props - array = []; - for(key in collection) { - if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { - array.push(key); - } - } - array.sort(); - } else { - array = collection || []; - } - arrayBound = array.length-1; + .animate-repeat.ng-leave, + .animate-repeat.ng-move.ng-move-active, + .animate-repeat.ng-enter.ng-enter-active { + opacity:1; + max-height:40px; + } + + + var friends = element.all(by.repeater('friend in friends')); + + it('should render initial data set', function() { + expect(friends.count()).toBe(10); + expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); + expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); + expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); + expect(element(by.binding('friends.length')).getText()) + .toMatch("I have 10 friends. They are:"); + }); + + it('should update repeater when filter predicate changes', function() { + expect(friends.count()).toBe(10); - // we are not using forEach for perf reasons (trying to avoid #call) - for (index = 0, length = array.length; index < length; index++) { - key = (collection === array) ? index : array[index]; - value = collection[key]; + element(by.model('q')).sendKeys('ma'); - last = lastOrder.shift(value); + expect(friends.count()).toBe(2); + expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); + expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); + }); + +
    + */ +var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { + var NG_REMOVED = '$$NG_REMOVED'; + var ngRepeatMinErr = minErr('ngRepeat'); + return { + transclude: 'element', + priority: 1000, + terminal: true, + $$tlb: true, + link: function($scope, $element, $attr, ctrl, $transclude){ + var expression = $attr.ngRepeat; + var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), + trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn, + lhs, rhs, valueIdentifier, keyIdentifier, + hashFnLocals = {$id: hashKey}; + + if (!match) { + throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } - if (last) { - // if we have already seen this object, then we need to reuse the - // associated scope/element - childScope = last.scope; - nextOrder.push(value, last); + lhs = match[1]; + rhs = match[2]; + trackByExp = match[3]; + + if (trackByExp) { + trackByExpGetter = $parse(trackByExp); + trackByIdExpFn = function(key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); + }; + } else { + trackByIdArrayFn = function(key, value) { + return hashKey(value); + }; + trackByIdObjFn = function(key) { + return key; + }; + } - if (index === last.index) { - // do nothing - cursor = last.element; - } else { - // existing item which got moved - last.index = index; - // This may be a noop, if the element is next, but I don't know of a good way to - // figure this out, since it would require extra DOM access, so let's just hope that - // the browsers realizes that it is noop, and treats it as such. - cursor.after(last.element); - cursor = last.element; - } + match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); + if (!match) { + throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + lhs); + } + valueIdentifier = match[3] || match[1]; + keyIdentifier = match[2]; + + // Store a list of elements from previous run. This is a hash where key is the item from the + // iterator, and the value is objects with following properties. + // - scope: bound scope + // - element: previous element. + // - index: position + var lastBlockMap = {}; + + //watch props + $scope.$watchCollection(rhs, function ngRepeatAction(collection){ + var index, length, + previousNode = $element[0], // current position of the node + nextNode, + // Same as lastBlockMap but it has the current state. It will become the + // lastBlockMap on the next iteration. + nextBlockMap = {}, + arrayLength, + childScope, + key, value, // key/value of iteration + trackById, + trackByIdFn, + collectionKeys, + block, // last object information {scope, element, id} + nextBlockOrder = [], + elementsToRemove; + + + if (isArrayLike(collection)) { + collectionKeys = collection; + trackByIdFn = trackByIdExpFn || trackByIdArrayFn; } else { - // new item which we don't know about - childScope = scope.$new(); + trackByIdFn = trackByIdExpFn || trackByIdObjFn; + // if object, extract keys, sort them and use to determine order of iteration over obj props + collectionKeys = []; + for (key in collection) { + if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { + collectionKeys.push(key); + } + } + collectionKeys.sort(); } - childScope[valueIdent] = value; - if (keyIdent) childScope[keyIdent] = key; - childScope.$index = index; - - childScope.$first = (index === 0); - childScope.$last = (index === arrayBound); - childScope.$middle = !(childScope.$first || childScope.$last); - - if (!last) { - linker(childScope, function(clone){ - cursor.after(clone); - last = { - scope: childScope, - element: (cursor = clone), - index: index - }; - nextOrder.push(value, last); - }); + arrayLength = collectionKeys.length; + + // locate existing items + length = nextBlockOrder.length = collectionKeys.length; + for(index = 0; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + trackById = trackByIdFn(key, value, index); + assertNotHasOwnProperty(trackById, '`track by` id'); + if(lastBlockMap.hasOwnProperty(trackById)) { + block = lastBlockMap[trackById]; + delete lastBlockMap[trackById]; + nextBlockMap[trackById] = block; + nextBlockOrder[index] = block; + } else if (nextBlockMap.hasOwnProperty(trackById)) { + // restore lastBlockMap + forEach(nextBlockOrder, function(block) { + if (block && block.scope) lastBlockMap[block.id] = block; + }); + // This is a duplicate and we need to throw an error + throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", + expression, trackById); + } else { + // new never before seen block + nextBlockOrder[index] = { id: trackById }; + nextBlockMap[trackById] = false; + } + } + + // remove existing items + for (key in lastBlockMap) { + // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn + if (lastBlockMap.hasOwnProperty(key)) { + block = lastBlockMap[key]; + elementsToRemove = getBlockElements(block.clone); + $animate.leave(elementsToRemove); + forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; }); + block.scope.$destroy(); + } } - } - //shrink children - for (key in lastOrder) { - if (lastOrder.hasOwnProperty(key)) { - array = lastOrder[key]; - while(array.length) { - value = array.pop(); - value.element.remove(); - value.scope.$destroy(); + // we are not using forEach for perf reasons (trying to avoid #call) + for (index = 0, length = collectionKeys.length; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + block = nextBlockOrder[index]; + if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]); + + if (block.scope) { + // if we have already seen this object, then we need to reuse the + // associated scope/element + childScope = block.scope; + + nextNode = previousNode; + do { + nextNode = nextNode.nextSibling; + } while(nextNode && nextNode[NG_REMOVED]); + + if (getBlockStart(block) != nextNode) { + // existing item which got moved + $animate.move(getBlockElements(block.clone), null, jqLite(previousNode)); + } + previousNode = getBlockEnd(block); + } else { + // new item which we don't know about + childScope = $scope.$new(); + } + + childScope[valueIdentifier] = value; + if (keyIdentifier) childScope[keyIdentifier] = key; + childScope.$index = index; + childScope.$first = (index === 0); + childScope.$last = (index === (arrayLength - 1)); + childScope.$middle = !(childScope.$first || childScope.$last); + // jshint bitwise: false + childScope.$odd = !(childScope.$even = (index&1) === 0); + // jshint bitwise: true + + if (!block.scope) { + $transclude(childScope, function(clone) { + clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' '); + $animate.enter(clone, null, jqLite(previousNode)); + previousNode = clone; + block.scope = childScope; + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block.clone = clone; + nextBlockMap[block.id] = block; + }); } } - } + lastBlockMap = nextBlockMap; + }); + } + }; - lastOrder = nextOrder; - }); - }; + function getBlockStart(block) { + return block.clone[0]; } -}); + + function getBlockEnd(block) { + return block.clone[block.clone.length - 1]; + } +}]; /** * @ngdoc directive - * @name ng.directive:ngShow + * @name ngShow * * @description - * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) - * conditionally. + * The `ngShow` directive shows or hides the given HTML element based on the expression + * provided to the ngShow attribute. The element is shown or hidden by removing or adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
    + * + * + *
    + * ``` + * + * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When true, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + *
    + * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):
    + * "f" / "0" / "false" / "no" / "n" / "[]" + *
    + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { + * //this is just another form of hiding an element + * display:block!important; + * position:absolute; + * top:-9999px; + * left:-9999px; + * } + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with ngShow + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass except that + * you must also include the !important flag to override the display property + * so that you can perform an animation when the element is hidden during the time of the animation. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * transition:0.5s linear all; + * } + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible + * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example - - - Click me:
    - Show: I show up when your checkbox is checked.
    - Hide: I hide when your checkbox is checked. -
    - - it('should check ng-show / ng-hide', function() { - expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); - expect(element('.doc-example-live span:last:visible').count()).toEqual(1); - - input('checked').check(); - - expect(element('.doc-example-live span:first:visible').count()).toEqual(1); - expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); - }); - -
    + + + Click me:
    +
    + Show: +
    + I show up when your checkbox is checked. +
    +
    +
    + Hide: +
    + I hide when your checkbox is checked. +
    +
    +
    + + @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-show { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .animate-show.ng-hide { + line-height:0; + opacity:0; + padding:0 10px; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + it('should check ng-show / ng-hide', function() { + expect(thumbsUp.isDisplayed()).toBeFalsy(); + expect(thumbsDown.isDisplayed()).toBeTruthy(); + + element(by.model('checked')).click(); + + expect(thumbsUp.isDisplayed()).toBeTruthy(); + expect(thumbsDown.isDisplayed()).toBeFalsy(); + }); + +
    */ -//TODO(misko): refactor to remove element from the DOM -var ngShowDirective = ngDirective(function(scope, element, attr){ - scope.$watch(attr.ngShow, function ngShowWatchAction(value){ - element.css('display', toBoolean(value) ? '' : 'none'); - }); -}); +var ngShowDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngShow, function ngShowWatchAction(value){ + $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); + }); + }; +}]; /** * @ngdoc directive - * @name ng.directive:ngHide + * @name ngHide * * @description - * The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML) - * conditionally. + * The `ngHide` directive shows or hides the given HTML element based on the expression + * provided to the ngHide attribute. The element is shown or hidden by removing or adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
    + * + * + *
    + * ``` + * + * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When false, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + *
    + * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):
    + * "f" / "0" / "false" / "no" / "n" / "[]" + *
    + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { + * //this is just another form of hiding an element + * display:block!important; + * position:absolute; + * top:-9999px; + * left:-9999px; + * } + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with ngHide + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` + * CSS class is added and removed for you instead of your own CSS class. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * transition:0.5s linear all; + * } + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden + * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example - - - Click me:
    - Show: I show up when you checkbox is checked?
    - Hide: I hide when you checkbox is checked? -
    - - it('should check ng-show / ng-hide', function() { - expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); - expect(element('.doc-example-live span:last:visible').count()).toEqual(1); - - input('checked').check(); - - expect(element('.doc-example-live span:first:visible').count()).toEqual(1); - expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); - }); - -
    + + + Click me:
    +
    + Show: +
    + I show up when your checkbox is checked. +
    +
    +
    + Hide: +
    + I hide when your checkbox is checked. +
    +
    +
    + + @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-hide { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .animate-hide.ng-hide { + line-height:0; + opacity:0; + padding:0 10px; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + it('should check ng-show / ng-hide', function() { + expect(thumbsUp.isDisplayed()).toBeFalsy(); + expect(thumbsDown.isDisplayed()).toBeTruthy(); + + element(by.model('checked')).click(); + + expect(thumbsUp.isDisplayed()).toBeTruthy(); + expect(thumbsDown.isDisplayed()).toBeFalsy(); + }); + +
    */ -//TODO(misko): refactor to remove element from the DOM -var ngHideDirective = ngDirective(function(scope, element, attr){ - scope.$watch(attr.ngHide, function ngHideWatchAction(value){ - element.css('display', toBoolean(value) ? 'none' : ''); - }); -}); +var ngHideDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngHide, function ngHideWatchAction(value){ + $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); + }); + }; +}]; /** * @ngdoc directive - * @name ng.directive:ngStyle + * @name ngStyle + * @restrict AC * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY - * @param {expression} ngStyle {@link guide/expression Expression} which evals to an - * object whose keys are CSS style names and values are corresponding values for those CSS - * keys. + * @param {expression} ngStyle + * + * {@link guide/expression Expression} which evals to an + * object whose keys are CSS style names and values are corresponding values for those CSS + * keys. + * + * Since some CSS style names are not valid keys for an object, they must be quoted. + * See the 'background-color' style in the example below. * * @example - + +
    Sample Text @@ -23263,13 +30696,15 @@ var ngHideDirective = ngDirective(function(scope, element, attr){ color: black; }
    - + + var colorSpan = element(by.css('span')); + it('should check ng-style', function() { - expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); - element('.doc-example-live :button[value=set]').click(); - expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); - element('.doc-example-live :button[value=clear]').click(); - expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); + expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); + element(by.css('input[value=\'set color\']')).click(); + expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); + element(by.css('input[value=clear]')).click(); + expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); });
    @@ -23285,368 +30720,308 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { /** * @ngdoc directive - * @name ng.directive:ngSwitch + * @name ngSwitch * @restrict EA * * @description - * Conditionally change the DOM structure. + * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. + * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location + * as specified in the template. + * + * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it + * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element + * matches the value obtained from the evaluated expression. In other words, you define a container element + * (where you place the directive), place an expression on the **`on="..."` attribute** + * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place + * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on + * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default + * attribute is displayed. + * + *
    + * Be aware that the attribute values to match against cannot be expressions. They are interpreted + * as literal string values to match against. + * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the + * value of the expression `$scope.someVal`. + *
    + + * @animations + * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container + * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage + * + * ``` * * ... * ... - * ... * ... * + * ``` + * * * @scope + * @priority 800 * @param {*} ngSwitch|on expression to match against ng-switch-when. - * @paramDescription - * On child elments add: + * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this - * case will be displayed. - * * `ngSwitchDefault`: the default case when no other casses match. + * case will be displayed. If the same match appears multiple times, all the + * elements will be displayed. + * * `ngSwitchDefault`: the default case when no other case match. If there + * are multiple default cases, all of them will be displayed when no other + * case match. + * * * @example - - - -
    - - selection={{selection}} -
    -
    -
    Settings Div
    - Home Span - default -
    + + +
    + + selection={{selection}} +
    +
    +
    Settings Div
    +
    Home Span
    +
    default
    - - - it('should start in settings', function() { - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); - }); - it('should change to home', function() { - select('selection').option('home'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); - }); - it('should select deafault', function() { - select('selection').option('other'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); - }); - - - */ -var NG_SWITCH = 'ng-switch'; -var ngSwitchDirective = valueFn({ - restrict: 'EA', - require: 'ngSwitch', - // asks for $scope to fool the BC controller module - controller: ['$scope', function ngSwitchController() { - this.cases = {}; - }], - link: function(scope, element, attr, ctrl) { - var watchExpr = attr.ngSwitch || attr.on, - selectedTransclude, - selectedElement, - selectedScope; - - scope.$watch(watchExpr, function ngSwitchWatchAction(value) { - if (selectedElement) { - selectedScope.$destroy(); - selectedElement.remove(); - selectedElement = selectedScope = null; +
    +
    + + angular.module('switchExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.items = ['settings', 'home', 'other']; + $scope.selection = $scope.items[0]; + }]); + + + .animate-switch-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; } - if ((selectedTransclude = ctrl.cases['!' + value] || ctrl.cases['?'])) { - scope.$eval(attr.change); - selectedScope = scope.$new(); - selectedTransclude(selectedScope, function(caseElement) { - selectedElement = caseElement; - element.append(caseElement); - }); + + .animate-switch { + padding:10px; } - }); - } -}); + + .animate-switch.ng-animate { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + } + + .animate-switch.ng-leave.ng-leave-active, + .animate-switch.ng-enter { + top:-50px; + } + .animate-switch.ng-leave, + .animate-switch.ng-enter.ng-enter-active { + top:0; + } + + + var switchElem = element(by.css('[ng-switch]')); + var select = element(by.model('selection')); + + it('should start in settings', function() { + expect(switchElem.getText()).toMatch(/Settings Div/); + }); + it('should change to home', function() { + select.all(by.css('option')).get(1).click(); + expect(switchElem.getText()).toMatch(/Home Span/); + }); + it('should select default', function() { + select.all(by.css('option')).get(2).click(); + expect(switchElem.getText()).toMatch(/default/); + }); + +
    + */ +var ngSwitchDirective = ['$animate', function($animate) { + return { + restrict: 'EA', + require: 'ngSwitch', + + // asks for $scope to fool the BC controller module + controller: ['$scope', function ngSwitchController() { + this.cases = {}; + }], + link: function(scope, element, attr, ngSwitchController) { + var watchExpr = attr.ngSwitch || attr.on, + selectedTranscludes = [], + selectedElements = [], + previousElements = [], + selectedScopes = []; + + scope.$watch(watchExpr, function ngSwitchWatchAction(value) { + var i, ii; + for (i = 0, ii = previousElements.length; i < ii; ++i) { + previousElements[i].remove(); + } + previousElements.length = 0; + + for (i = 0, ii = selectedScopes.length; i < ii; ++i) { + var selected = selectedElements[i]; + selectedScopes[i].$destroy(); + previousElements[i] = selected; + $animate.leave(selected, function() { + previousElements.splice(i, 1); + }); + } + + selectedElements.length = 0; + selectedScopes.length = 0; + + if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { + scope.$eval(attr.change); + forEach(selectedTranscludes, function(selectedTransclude) { + var selectedScope = scope.$new(); + selectedScopes.push(selectedScope); + selectedTransclude.transclude(selectedScope, function(caseElement) { + var anchor = selectedTransclude.element; + + selectedElements.push(caseElement); + $animate.enter(caseElement, anchor.parent(), anchor); + }); + }); + } + }); + } + }; +}]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', - priority: 500, + priority: 800, require: '^ngSwitch', - compile: function(element, attrs, transclude) { - return function(scope, element, attr, ctrl) { - ctrl.cases['!' + attrs.ngSwitchWhen] = transclude; - }; + link: function(scope, element, attrs, ctrl, $transclude) { + ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); + ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', - priority: 500, + priority: 800, require: '^ngSwitch', - compile: function(element, attrs, transclude) { - return function(scope, element, attr, ctrl) { - ctrl.cases['?'] = transclude; - }; - } + link: function(scope, element, attr, ctrl, $transclude) { + ctrl.cases['?'] = (ctrl.cases['?'] || []); + ctrl.cases['?'].push({ transclude: $transclude, element: element }); + } }); /** * @ngdoc directive - * @name ng.directive:ngTransclude + * @name ngTransclude + * @restrict AC * * @description - * Insert the transcluded DOM here. + * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. + * + * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. * * @element ANY * * @example - - + + -
    +

    -
    - {{text}} -
    - - - it('should have transcluded', function() { - input('title').enter('TITLE'); - input('text').enter('TEXT'); - expect(binding('title')).toEqual('TITLE'); - expect(binding('text')).toEqual('TEXT'); - }); - - - * - */ -var ngTranscludeDirective = ngDirective({ - controller: ['$transclude', '$element', function($transclude, $element) { - $transclude(function(clone) { - $element.append(clone); - }); - }] -}); - -/** - * @ngdoc directive - * @name ng.directive:ngView - * @restrict ECA - * - * @description - * # Overview - * `ngView` is a directive that complements the {@link ng.$route $route} service by - * including the rendered template of the current route into the main layout (`index.html`) file. - * Every time the current route changes, the included view changes with it according to the - * configuration of the `$route` service. - * - * @scope - * @example - - -
    - Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
    - -
    -
    - -
    $location.path() = {{$location.path()}}
    -
    $route.current.templateUrl = {{$route.current.templateUrl}}
    -
    $route.current.params = {{$route.current.params}}
    -
    $route.current.scope.name = {{$route.current.scope.name}}
    -
    $routeParams = {{$routeParams}}
    -
    -
    - - - controller: {{name}}
    - Book Id: {{params.bookId}}
    -
    - - - controller: {{name}}
    - Book Id: {{params.bookId}}
    - Chapter Id: {{params.chapterId}} -
    - - - angular.module('ngView', [], function($routeProvider, $locationProvider) { - $routeProvider.when('/Book/:bookId', { - templateUrl: 'book.html', - controller: BookCntl - }); - $routeProvider.when('/Book/:bookId/ch/:chapterId', { - templateUrl: 'chapter.html', - controller: ChapterCntl - }); - - // configure html5 to get links working on jsfiddle - $locationProvider.html5Mode(true); - }); - - function MainCntl($scope, $route, $routeParams, $location) { - $scope.$route = $route; - $scope.$location = $location; - $scope.$routeParams = $routeParams; - } - - function BookCntl($scope, $routeParams) { - $scope.name = "BookCntl"; - $scope.params = $routeParams; - } - - function ChapterCntl($scope, $routeParams) { - $scope.name = "ChapterCntl"; - $scope.params = $routeParams; - } - - - - it('should load and compile correct template', function() { - element('a:contains("Moby: Ch1")').click(); - var content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: ChapterCntl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); - - element('a:contains("Scarlet")').click(); - content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: BookCntl/); - expect(content).toMatch(/Book Id\: Scarlet/); - }); - -
    - */ - - -/** - * @ngdoc event - * @name ng.directive:ngView#$viewContentLoaded - * @eventOf ng.directive:ngView - * @eventType emit on the current ngView scope - * @description - * Emitted every time the ngView content is reloaded. +
    + {{text}} +
    +
    + + it('should have transcluded', function() { + var titleElement = element(by.model('title')); + titleElement.clear(); + titleElement.sendKeys('TITLE'); + var textElement = element(by.model('text')); + textElement.clear(); + textElement.sendKeys('TEXT'); + expect(element(by.binding('title')).getText()).toEqual('TITLE'); + expect(element(by.binding('text')).getText()).toEqual('TEXT'); + }); + +
    + * */ -var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', - '$controller', - function($http, $templateCache, $route, $anchorScroll, $compile, - $controller) { - return { - restrict: 'ECA', - terminal: true, - link: function(scope, element, attr) { - var lastScope, - onloadExp = attr.onload || ''; - - scope.$on('$routeChangeSuccess', update); - update(); - - - function destroyLastScope() { - if (lastScope) { - lastScope.$destroy(); - lastScope = null; - } - } - - function clearContent() { - element.html(''); - destroyLastScope(); - } - - function update() { - var locals = $route.current && $route.current.locals, - template = locals && locals.$template; - - if (template) { - element.html(template); - destroyLastScope(); - - var link = $compile(element.contents()), - current = $route.current, - controller; - - lastScope = current.scope = scope.$new(); - if (current.controller) { - locals.$scope = lastScope; - controller = $controller(current.controller, locals); - element.children().data('$ngControllerController', controller); - } - - link(lastScope); - lastScope.$emit('$viewContentLoaded'); - lastScope.$eval(onloadExp); - - // $anchorScroll might listen on event... - $anchorScroll(); - } else { - clearContent(); - } - } +var ngTranscludeDirective = ngDirective({ + link: function($scope, $element, $attrs, controller, $transclude) { + if (!$transclude) { + throw minErr('ngTransclude')('orphan', + 'Illegal use of ngTransclude directive in the template! ' + + 'No parent directive that requires a transclusion found. ' + + 'Element: {0}', + startingTag($element)); } - }; -}]; + + $transclude(function(clone) { + $element.empty(); + $element.append(clone); + }); + } +}); /** * @ngdoc directive - * @name ng.directive:script + * @name script + * @restrict E * * @description - * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the - * template can be used by `ngInclude`, `ngView` or directive templates. + * Load the content of a ` Load inlined template
    -
    - + + it('should load template defined inside script tag', function() { - element('#tpl-link').click(); - expect(element('#tpl-content').text()).toMatch(/Content of the template/); + element(by.css('#tpl-link')).click(); + expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); - -
    + + */ var scriptDirective = ['$templateCache', function($templateCache) { return { @@ -23664,9 +31039,10 @@ var scriptDirective = ['$templateCache', function($templateCache) { }; }]; +var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive - * @name ng.directive:select + * @name select * @restrict E * * @description @@ -23674,22 +31050,29 @@ var scriptDirective = ['$templateCache', function($templateCache) { * * # `ngOptions` * - * Optionally `ngOptions` attribute can be used to dynamically generate a list of `
    -
    - + + it('should check ng-options', function() { - expect(binding('{selected_color:color}')).toMatch('red'); - select('color').option('0'); - expect(binding('{selected_color:color}')).toMatch('black'); - using('.nullable').select('color').option(''); - expect(binding('{selected_color:color}')).toMatch('null'); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); + element.all(by.model('myColor')).first().click(); + element.all(by.css('select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); + element(by.css('.nullable select[ng-model="myColor"]')).click(); + element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); }); - -
    + + */ var ngOptionsDirective = valueFn({ terminal: true }); +// jshint maxlen: false var selectDirective = ['$compile', '$parse', function($compile, $parse) { - //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000077770 - var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, + //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 + var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, nullModelCtrl = {$setViewValue: noop}; +// jshint maxlen: 100 return { restrict: 'E', @@ -23809,10 +31200,11 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; - } + }; self.addOption = function(value) { + assertNotHasOwnProperty(value, '"option value"'); optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { @@ -23838,12 +31230,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE - } + }; self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); - } + }; $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed @@ -23869,7 +31261,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { - if (children[i].value == '') { + if (children[i].value === '') { emptyOption = nullOption = children.eq(i); break; } @@ -23878,30 +31270,22 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator - if (multiple && (attr.required || attr.ngRequired)) { - var requiredValidator = function(value) { - ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); - return value; + if (multiple) { + ngModelCtrl.$isEmpty = function(value) { + return !value || value.length === 0; }; - - ngModelCtrl.$parsers.push(requiredValidator); - ngModelCtrl.$formatters.unshift(requiredValidator); - - attr.$observe('required', function() { - requiredValidator(ngModelCtrl.$viewValue); - }); } - if (optionsExp) Options(scope, element, ngModelCtrl); - else if (multiple) Multiple(scope, element, ngModelCtrl); - else Single(scope, element, ngModelCtrl, selectCtrl); + if (optionsExp) setupAsOptions(scope, element, ngModelCtrl); + else if (multiple) setupAsMultiple(scope, element, ngModelCtrl); + else setupAsSingle(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// - function Single(scope, selectElement, ngModelCtrl, selectCtrl) { + function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; @@ -23918,7 +31302,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { } }; - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); @@ -23926,7 +31310,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { }); } - function Multiple(scope, selectElement, ctrl) { + function setupAsMultiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); @@ -23939,12 +31323,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { - lastView = copy(ctrl.$viewValue); + lastView = shallowCopy(ctrl.$viewValue); ctrl.$render(); } }); - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { @@ -23957,13 +31341,15 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { }); } - function Options(scope, selectElement, ctrl) { + function setupAsOptions(scope, selectElement, ctrl) { var match; - if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { - throw Error( - "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + - " but got '" + optionsExp + "'."); + if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) { + throw ngOptionsMinErr('iexp', + "Expected expression in form of " + + "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + + " but got '{0}'. Element: {1}", + optionsExp, startingTag(selectElement)); } var displayFn = $parse(match[2] || match[1]), @@ -23972,9 +31358,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), - // This is an array of array of existing option groups in DOM. We try to reuse these if possible - // optionGroupsCache[0] is the options with no option group - // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element + track = match[8], + trackFn = track ? $parse(match[8]) : null, + // This is an array of array of existing option groups in DOM. + // We try to reuse these if possible + // - optionGroupsCache[0] is the options with no option group + // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { @@ -23985,20 +31374,20 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // becomes the compilation root nullOption.removeClass('ng-scope'); - // we need to remove it before calling selectElement.html('') because otherwise IE will + // we need to remove it before calling selectElement.empty() because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model - selectElement.html(''); + selectElement.empty(); - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, - key, value, optionElement, index, groupIndex, length, groupLength; + key, value, optionElement, index, groupIndex, length, groupLength, trackIndex; if (multiple) { value = []; @@ -24012,7 +31401,14 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; - locals[valueName] = collection[key]; + if (trackFn) { + for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { + locals[valueName] = collection[trackIndex]; + if (trackFn(scope, locals) == key) break; + } + } else { + locals[valueName] = collection[key]; + } value.push(valueFn(scope, locals)); } } @@ -24021,25 +31417,58 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { key = selectElement.val(); if (key == '?') { value = undefined; - } else if (key == ''){ + } else if (key === ''){ value = null; } else { - locals[valueName] = collection[key]; - if (keyName) locals[keyName] = key; - value = valueFn(scope, locals); + if (trackFn) { + for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { + locals[valueName] = collection[trackIndex]; + if (trackFn(scope, locals) == key) { + value = valueFn(scope, locals); + break; + } + } + } else { + locals[valueName] = collection[key]; + if (keyName) locals[keyName] = key; + value = valueFn(scope, locals); + } } } ctrl.$setViewValue(value); + render(); }); }); ctrl.$render = render; - // TODO(vojta): can't we optimize this ? - scope.$watch(render); + scope.$watchCollection(valuesFn, render); + if ( multiple ) { + scope.$watchCollection(function() { return ctrl.$modelValue; }, render); + } + + function getSelectedSet() { + var selectedSet = false; + if (multiple) { + var modelValue = ctrl.$modelValue; + if (trackFn && isArray(modelValue)) { + selectedSet = new HashMap([]); + var locals = {}; + for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { + locals[valueName] = modelValue[trackIndex]; + selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); + } + } else { + selectedSet = new HashMap(modelValue); + } + } + return selectedSet; + } + function render() { - var optionGroups = {'':[]}, // Temporary location for the option groups before we render them + // Temporary location for the option groups before we render them + var optionGroups = {'':[]}, optionGroupNames = [''], optionGroupName, optionGroup, @@ -24048,37 +31477,55 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, + key, groupLength, length, groupIndex, index, locals = {}, selected, - selectedSet = false, // nothing is selected yet + selectedSet = getSelectedSet(), lastElement, element, label; - if (multiple) { - selectedSet = new HashMap(modelValue); - } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { - locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; - optionGroupName = groupByFn(scope, locals) || ''; + + key = index; + if (keyName) { + key = keys[index]; + if ( key.charAt(0) === '$' ) continue; + locals[keyName] = key; + } + + locals[valueName] = values[key]; + + optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { - selected = selectedSet.remove(valueFn(scope, locals)) != undefined; + selected = isDefined( + selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) + ); } else { - selected = modelValue === valueFn(scope, locals); + if (trackFn) { + var modelCast = {}; + modelCast[valueName] = modelValue; + selected = trackFn(scope, modelCast) === trackFn(scope, locals); + } else { + selected = modelValue === valueFn(scope, locals); + } selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user - label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values + + // doing displayFn(scope, locals) || '' overwrites zero values + label = isDefined(label) ? label : ''; optionGroup.push({ - id: keyName ? keys[index] : index, // either the index into array or key from object + // either the index into array or key from object + id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), label: label, selected: selected // determine if we should be selected }); @@ -24137,6 +31584,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // lastElement.prop('selected') provided by jQuery has side-effects if (lastElement[0].selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); + if (msie) { + // See #7692 + // The selected item wouldn't visually update on IE without this. + // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well + lastElement.prop('selected', existingOption.selected); + } } } else { // grow elements @@ -24151,6 +31604,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // rather then the element. (element = optionTemplate.clone()) .val(option.id) + .prop('selected', option.selected) .attr('selected', option.selected) .text(option.label); } @@ -24182,7 +31636,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { } } } - } + }; }]; var optionDirective = ['$interpolate', function($interpolate) { @@ -24226,12 +31680,12 @@ var optionDirective = ['$interpolate', function($interpolate) { selectCtrl.addOption(attr.value); } - element.bind('$destroy', function() { + element.on('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } - } + }; }]; var styleDirective = valueFn({ @@ -24247,6 +31701,11 @@ var styleDirective = valueFn({ // Public namespace angular.scenario = angular.scenario || {}; +/** + * Expose jQuery (e.g. for custom dsl extensions). + */ +angular.scenario.jQuery = _jQuery; + /** * Defines a new output format. * @@ -24272,6 +31731,7 @@ angular.scenario.output = angular.scenario.output || function(name, fn) { */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { + /* jshint -W040 *//* The dsl binds `this` for us when calling chained functions */ function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) @@ -24307,18 +31767,17 @@ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { - var prefix = 'expect ' + this.future.name + ' '; - if (this.inverse) { - prefix += 'not '; - } + var description = this.future.name + + (this.inverse ? ' not ' : ' ') + name + + ' ' + angular.toJson(expected); var self = this; - this.addFuture(prefix + name + ' ' + angular.toJson(expected), + this.addFuture('expect ' + description, function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { - error = 'expected ' + angular.toJson(expected) + + error = 'expected ' + description + ' but was ' + angular.toJson(self.actual); } done(error); @@ -24383,7 +31842,7 @@ angular.scenario.setUpAndRun = function(config) { /** * Iterates through list with iterator function that must call the - * continueFunction to continute iterating. + * continueFunction to continue iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) @@ -24461,98 +31920,6 @@ function callerFile(offset) { }; } -/** - * Triggers a browser event. Attempts to choose the right event if one is - * not specified. - * - * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement - * @param {string} type Optional event type. - * @param {Array.=} keys Optional list of pressed keys - * (valid values: 'alt', 'meta', 'shift', 'ctrl') - */ -function browserTrigger(element, type, keys) { - if (element && !element.nodeName) element = element[0]; - if (!element) return; - if (!type) { - type = { - 'text': 'change', - 'textarea': 'change', - 'hidden': 'change', - 'password': 'change', - 'button': 'click', - 'submit': 'click', - 'reset': 'click', - 'image': 'click', - 'checkbox': 'click', - 'radio': 'click', - 'select-one': 'change', - 'select-multiple': 'change' - }[lowercase(element.type)] || 'click'; - } - if (lowercase(nodeName_(element)) == 'option') { - element.parentNode.value = element.value; - element = element.parentNode; - type = 'change'; - } - - keys = keys || []; - function pressed(key) { - return indexOf(keys, key) !== -1; - } - - if (msie < 9) { - switch(element.type) { - case 'radio': - case 'checkbox': - element.checked = !element.checked; - break; - } - // WTF!!! Error: Unspecified error. - // Don't know why, but some elements when detached seem to be in inconsistent state and - // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) - // forcing the browser to compute the element position (by reading its CSS) - // puts the element in consistent state. - element.style.posLeft; - - // TODO(vojta): create event objects with pressed keys to get it working on IE<9 - var ret = element.fireEvent('on' + type); - if (lowercase(element.type) == 'submit') { - while(element) { - if (lowercase(element.nodeName) == 'form') { - element.fireEvent('onsubmit'); - break; - } - element = element.parentNode; - } - } - return ret; - } else { - var evnt = document.createEvent('MouseEvents'), - originalPreventDefault = evnt.preventDefault, - iframe = _jQuery('#application iframe')[0], - appWindow = iframe ? iframe.contentWindow : window, - fakeProcessDefault = true, - finalProcessDefault, - angular = appWindow.angular || {}; - - // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 - angular['ff-684208-preventDefault'] = false; - evnt.preventDefault = function() { - fakeProcessDefault = false; - return originalPreventDefault.apply(evnt, arguments); - }; - - evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), - pressed('shift'), pressed('meta'), 0, element); - - element.dispatchEvent(evnt); - finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); - - delete angular['ff-684208-preventDefault']; - - return finalProcessDefault; - } -} /** * Don't use the jQuery trigger method since it works incorrectly. @@ -24564,9 +31931,10 @@ function browserTrigger(element, type, keys) { * To work around this we instead use our own handler that fires a real event. */ (function(fn){ - var parentTrigger = fn.trigger; + // We need a handle to the original trigger function for input tests. + var parentTrigger = fn._originalTrigger = fn.trigger; fn.trigger = function(type) { - if (/(click|change|keydown|blur|input)/.test(type)) { + if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); @@ -24596,15 +31964,15 @@ _jQuery.fn.bindings = function(windowJquery, bindExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; - if (actualExp.indexOf(bindExp) == 0) { + if (actualExp.indexOf(bindExp) === 0) { return actualExp.charAt(bindExp.length) == '|'; } } - } + }; } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); - } + }; } else { match = function(actualExp) { return !!actualExp; @@ -24616,9 +31984,9 @@ _jQuery.fn.bindings = function(windowJquery, bindExp) { } function push(value) { - if (value == undefined) { + if (value === undefined) { value = ''; - } else if (typeof value != 'string') { + } else if (typeof value !== 'string') { value = angular.toJson(value); } result.push('' + value); @@ -24655,6 +32023,164 @@ _jQuery.fn.bindings = function(windowJquery, bindExp) { return result; }; +(function() { + var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10); + + function indexOf(array, obj) { + if (array.indexOf) return array.indexOf(obj); + + for ( var i = 0; i < array.length; i++) { + if (obj === array[i]) return i; + } + return -1; + } + + + + /** + * Triggers a browser event. Attempts to choose the right event if one is + * not specified. + * + * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement + * @param {string} eventType Optional event type + * @param {Object=} eventData An optional object which contains additional event data (such as x,y + * coordinates, keys, etc...) that are passed into the event when triggered + */ + window.browserTrigger = function browserTrigger(element, eventType, eventData) { + if (element && !element.nodeName) element = element[0]; + if (!element) return; + + eventData = eventData || {}; + var keys = eventData.keys; + var x = eventData.x; + var y = eventData.y; + + var inputType = (element.type) ? element.type.toLowerCase() : null, + nodeName = element.nodeName.toLowerCase(); + + if (!eventType) { + eventType = { + 'text': 'change', + 'textarea': 'change', + 'hidden': 'change', + 'password': 'change', + 'button': 'click', + 'submit': 'click', + 'reset': 'click', + 'image': 'click', + 'checkbox': 'click', + 'radio': 'click', + 'select-one': 'change', + 'select-multiple': 'change', + '_default_': 'click' + }[inputType || '_default_']; + } + + if (nodeName == 'option') { + element.parentNode.value = element.value; + element = element.parentNode; + eventType = 'change'; + } + + keys = keys || []; + function pressed(key) { + return indexOf(keys, key) !== -1; + } + + if (msie < 9) { + if (inputType == 'radio' || inputType == 'checkbox') { + element.checked = !element.checked; + } + + // WTF!!! Error: Unspecified error. + // Don't know why, but some elements when detached seem to be in inconsistent state and + // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) + // forcing the browser to compute the element position (by reading its CSS) + // puts the element in consistent state. + element.style.posLeft; + + // TODO(vojta): create event objects with pressed keys to get it working on IE<9 + var ret = element.fireEvent('on' + eventType); + if (inputType == 'submit') { + while(element) { + if (element.nodeName.toLowerCase() == 'form') { + element.fireEvent('onsubmit'); + break; + } + element = element.parentNode; + } + } + return ret; + } else { + var evnt; + if(/transitionend/.test(eventType)) { + if(window.WebKitTransitionEvent) { + evnt = new WebKitTransitionEvent(eventType, eventData); + evnt.initEvent(eventType, false, true); + } + else { + try { + evnt = new TransitionEvent(eventType, eventData); + } + catch(e) { + evnt = document.createEvent('TransitionEvent'); + evnt.initTransitionEvent(eventType, null, null, null, eventData.elapsedTime || 0); + } + } + } + else if(/animationend/.test(eventType)) { + if(window.WebKitAnimationEvent) { + evnt = new WebKitAnimationEvent(eventType, eventData); + evnt.initEvent(eventType, false, true); + } + else { + try { + evnt = new AnimationEvent(eventType, eventData); + } + catch(e) { + evnt = document.createEvent('AnimationEvent'); + evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0); + } + } + } + else { + evnt = document.createEvent('MouseEvents'); + x = x || 0; + y = y || 0; + evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'), + pressed('alt'), pressed('shift'), pressed('meta'), 0, element); + } + + /* we're unable to change the timeStamp value directly so this + * is only here to allow for testing where the timeStamp value is + * read */ + evnt.$manualTimeStamp = eventData.timeStamp; + + if(!evnt) return; + + var originalPreventDefault = evnt.preventDefault, + appWindow = element.ownerDocument.defaultView, + fakeProcessDefault = true, + finalProcessDefault, + angular = appWindow.angular || {}; + + // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 + angular['ff-684208-preventDefault'] = false; + evnt.preventDefault = function() { + fakeProcessDefault = false; + return originalPreventDefault.apply(evnt, arguments); + }; + + element.dispatchEvent(evnt); + finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); + + delete angular['ff-684208-preventDefault']; + + return finalProcessDefault; + } + }; +}()); + /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. @@ -24704,7 +32230,7 @@ angular.scenario.Application.prototype.getWindow_ = function() { */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; - var frame = this.getFrame_(); + var frame = self.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { @@ -24712,21 +32238,36 @@ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorF } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); - this.executeAction(loadFn); + self.executeAction(loadFn); } else { frame.remove(); - this.context.find('#test-frames').append('