Browse Source

增加beacat作为IOC容器

Sand 8 years ago
parent
commit
111670c8fb
100 changed files with 21075 additions and 94 deletions
  1. 3 1
      .gitignore
  2. 8 0
      readme.md
  3. 88 86
      src/server/app.js
  4. 4 0
      src/server/context.json
  5. 23 7
      src/server/models/user/users.js
  6. 15 0
      src/server/node_modules/.bin/bearcat
  7. 7 0
      src/server/node_modules/.bin/bearcat.cmd
  8. 21 0
      src/server/node_modules/bluebird/LICENSE
  9. 51 0
      src/server/node_modules/bluebird/README.md
  10. 1 0
      src/server/node_modules/bluebird/changelog.md
  11. 3756 0
      src/server/node_modules/bluebird/js/browser/bluebird.core.js
  12. 31 0
      src/server/node_modules/bluebird/js/browser/bluebird.core.min.js
  13. 5598 0
      src/server/node_modules/bluebird/js/browser/bluebird.js
  14. 31 0
      src/server/node_modules/bluebird/js/browser/bluebird.min.js
  15. 21 0
      src/server/node_modules/bluebird/js/release/any.js
  16. 55 0
      src/server/node_modules/bluebird/js/release/assert.js
  17. 166 0
      src/server/node_modules/bluebird/js/release/async.js
  18. 67 0
      src/server/node_modules/bluebird/js/release/bind.js
  19. 11 0
      src/server/node_modules/bluebird/js/release/bluebird.js
  20. 123 0
      src/server/node_modules/bluebird/js/release/call_get.js
  21. 129 0
      src/server/node_modules/bluebird/js/release/cancel.js
  22. 42 0
      src/server/node_modules/bluebird/js/release/catch_filter.js
  23. 69 0
      src/server/node_modules/bluebird/js/release/context.js
  24. 915 0
      src/server/node_modules/bluebird/js/release/debuggability.js
  25. 46 0
      src/server/node_modules/bluebird/js/release/direct_resolve.js
  26. 30 0
      src/server/node_modules/bluebird/js/release/each.js
  27. 116 0
      src/server/node_modules/bluebird/js/release/errors.js
  28. 80 0
      src/server/node_modules/bluebird/js/release/es5.js
  29. 12 0
      src/server/node_modules/bluebird/js/release/filter.js
  30. 111 0
      src/server/node_modules/bluebird/js/release/finally.js
  31. 223 0
      src/server/node_modules/bluebird/js/release/generators.js
  32. 168 0
      src/server/node_modules/bluebird/js/release/join.js
  33. 168 0
      src/server/node_modules/bluebird/js/release/map.js
  34. 55 0
      src/server/node_modules/bluebird/js/release/method.js
  35. 51 0
      src/server/node_modules/bluebird/js/release/nodeback.js
  36. 58 0
      src/server/node_modules/bluebird/js/release/nodeify.js
  37. 773 0
      src/server/node_modules/bluebird/js/release/promise.js
  38. 184 0
      src/server/node_modules/bluebird/js/release/promise_array.js
  39. 314 0
      src/server/node_modules/bluebird/js/release/promisify.js
  40. 118 0
      src/server/node_modules/bluebird/js/release/props.js
  41. 90 0
      src/server/node_modules/bluebird/js/release/queue.js
  42. 49 0
      src/server/node_modules/bluebird/js/release/race.js
  43. 172 0
      src/server/node_modules/bluebird/js/release/reduce.js
  44. 61 0
      src/server/node_modules/bluebird/js/release/schedule.js
  45. 43 0
      src/server/node_modules/bluebird/js/release/settle.js
  46. 148 0
      src/server/node_modules/bluebird/js/release/some.js
  47. 103 0
      src/server/node_modules/bluebird/js/release/synchronous_inspection.js
  48. 86 0
      src/server/node_modules/bluebird/js/release/thenables.js
  49. 93 0
      src/server/node_modules/bluebird/js/release/timers.js
  50. 226 0
      src/server/node_modules/bluebird/js/release/using.js
  51. 375 0
      src/server/node_modules/bluebird/js/release/util.js
  52. 102 0
      src/server/node_modules/bluebird/package.json
  53. 3 0
      src/server/node_modules/mongoose/.eslintignore
  54. 31 0
      src/server/node_modules/mongoose/.eslintrc.yml
  55. 16 0
      src/server/node_modules/mongoose/.npmignore
  56. 15 0
      src/server/node_modules/mongoose/.travis.yml
  57. 56 0
      src/server/node_modules/mongoose/CONTRIBUTING.md
  58. 3339 0
      src/server/node_modules/mongoose/History.md
  59. 322 0
      src/server/node_modules/mongoose/README.md
  60. 41 0
      src/server/node_modules/mongoose/examples/README.md
  61. 103 0
      src/server/node_modules/mongoose/examples/aggregate/aggregate.js
  62. 14 0
      src/server/node_modules/mongoose/examples/aggregate/package.json
  63. 17 0
      src/server/node_modules/mongoose/examples/aggregate/person.js
  64. 77 0
      src/server/node_modules/mongoose/examples/doc-methods.js
  65. 1 0
      src/server/node_modules/mongoose/examples/express/README.md
  66. 6 0
      src/server/node_modules/mongoose/examples/express/connection-sharing/README.md
  67. 17 0
      src/server/node_modules/mongoose/examples/express/connection-sharing/app.js
  68. 5 0
      src/server/node_modules/mongoose/examples/express/connection-sharing/modelA.js
  69. 14 0
      src/server/node_modules/mongoose/examples/express/connection-sharing/package.json
  70. 20 0
      src/server/node_modules/mongoose/examples/express/connection-sharing/routes.js
  71. 22 0
      src/server/node_modules/mongoose/examples/geospatial/geoJSONSchema.js
  72. 56 0
      src/server/node_modules/mongoose/examples/geospatial/geoJSONexample.js
  73. 100 0
      src/server/node_modules/mongoose/examples/geospatial/geospatial.js
  74. 14 0
      src/server/node_modules/mongoose/examples/geospatial/package.json
  75. 27 0
      src/server/node_modules/mongoose/examples/geospatial/person.js
  76. 47 0
      src/server/node_modules/mongoose/examples/globalschemas/gs_example.js
  77. 14 0
      src/server/node_modules/mongoose/examples/globalschemas/person.js
  78. 84 0
      src/server/node_modules/mongoose/examples/lean/lean.js
  79. 14 0
      src/server/node_modules/mongoose/examples/lean/package.json
  80. 16 0
      src/server/node_modules/mongoose/examples/lean/person.js
  81. 100 0
      src/server/node_modules/mongoose/examples/mapreduce/mapreduce.js
  82. 14 0
      src/server/node_modules/mongoose/examples/mapreduce/package.json
  83. 16 0
      src/server/node_modules/mongoose/examples/mapreduce/person.js
  84. 134 0
      src/server/node_modules/mongoose/examples/population/population-across-three-collections.js
  85. 103 0
      src/server/node_modules/mongoose/examples/population/population-basic.js
  86. 109 0
      src/server/node_modules/mongoose/examples/population/population-of-existing-doc.js
  87. 124 0
      src/server/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js
  88. 138 0
      src/server/node_modules/mongoose/examples/population/population-options.js
  89. 106 0
      src/server/node_modules/mongoose/examples/population/population-plain-objects.js
  90. 14 0
      src/server/node_modules/mongoose/examples/promises/package.json
  91. 15 0
      src/server/node_modules/mongoose/examples/promises/person.js
  92. 94 0
      src/server/node_modules/mongoose/examples/promises/promise.js
  93. 14 0
      src/server/node_modules/mongoose/examples/querybuilder/package.json
  94. 15 0
      src/server/node_modules/mongoose/examples/querybuilder/person.js
  95. 79 0
      src/server/node_modules/mongoose/examples/querybuilder/querybuilder.js
  96. 14 0
      src/server/node_modules/mongoose/examples/replicasets/package.json
  97. 15 0
      src/server/node_modules/mongoose/examples/replicasets/person.js
  98. 71 0
      src/server/node_modules/mongoose/examples/replicasets/replica-sets.js
  99. 119 0
      src/server/node_modules/mongoose/examples/schema/schema.js
  100. 0 0
      src/server/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js

+ 3 - 1
.gitignore

@ -1,2 +1,4 @@
.idea/*
npm-debug.log
npm-debug.log
src/server/node_modules/bearcat/*
test/server/node_modules/*

+ 8 - 0
readme.md

@ -60,6 +60,14 @@ IM_PROFILE值将决定应用加载的配置文件,配置文件位于src/resour
未完工
### 依赖注入
使用bearcat库。
### Promise库
使用bluebird库。
## 开发SDK
IM提供了开发SDK,一个JS脚本。客户端可以通过引用此脚本或将此脚本打包到资源中。此外,脚本使用jQuery作为基础环境,因此客户端需要预先引用jQuery脚本。客户端通过以下链接引用SDK文件

+ 88 - 86
src/server/app.js

@ -12,6 +12,12 @@ let bodyParser = require('body-parser');
let log = require('./util/log');
let redis = require('redis');
// IoC
var bearcat = require('bearcat');
var contextPath = require.resolve('./context.json');
global.bearcat = bearcat; // make bearcat global, for `bearcat.module()`
bearcat.createApp([contextPath]);
// server configurations
let APIv1 = require('./include/endpoints').APIv1;
let PAGES = require('./include/endpoints').PAGES;
@ -32,101 +38,97 @@ let management = require('./endpoints/management.endpoint');
// handlers
let SocketHandler = require('./handlers/socket.handler');
// schedule
let PushJobLoader = require('./models/schedule/push.job.loader')
// initialize express application
let app = express();
app.set('port', config.serverPort);
bearcat.start(function () {
    // initialize express application
    let app = express();
    app.set('port', config.serverPort);
    // view engine
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    // logger, body parser, cookie parser and view path
    app.use(favicon(__dirname + '/public/favicon.ico', null));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    // pages
    app.use(PAGES.Home.Index, index);
    app.use(PAGES.Socket.Index, socket);
    // setup rest endpoints
    app.use(APIv1.Application.Base, application);
    app.use(APIv1.Chats.Base, chats);
    app.use(APIv1.Users.Base, users);
    app.use(APIv1.Groups.Base, groups);
    app.use(APIv1.Management.Base, management);
    // error handler, only handle the sync call exception
    app.use(function (err, req, res, next) {
        if (err) {
            res
                .status(err.httpStatus || 500)
                .send({message: err.message});
        }
// view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
        next(err);
    });
// logger, body parser, cookie parser and view path
app.use(favicon(__dirname + '/public/favicon.ico', null));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
    // In development mode, error handler will print stacktrace, only handle the sync call exception
    if (app.get('env') === 'development') {
        app.use(function (err, req, res, next) {
            log.error(err);
// pages
app.use(PAGES.Home.Index, index);
app.use(PAGES.Socket.Index, socket);
// setup rest endpoints
app.use(APIv1.Application.Base, application);
app.use(APIv1.Chats.Base, chats);
app.use(APIv1.Users.Base, users);
app.use(APIv1.Groups.Base, groups);
app.use(APIv1.Management.Base, management);
// error handler, only handle the sync call exception
app.use(function (err, req, res, next) {
    if (err) {
        res
            .status(err.httpStatus || 500)
            .send({message: err.message});
            next(err);
        });
    }
    next(err);
});
// In development mode, error handler will print stacktrace, only handle the sync call exception
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        log.error(err);
    // only handle the sync call exception
    process.on('uncaughtException', function (err) {
        console.error(err);
    });
        next(err);
    // now enable http server and socket.io
    let server = require('http').createServer(app);
    let io = require('socket.io').listen(server);
    server.listen(config.serverPort);
    // event listener for HTTP server "error" event
    server.on('error', function (error) {
        if (error.syscall !== 'listen') throw error;
        let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
        // handle specific listen errors with friendly messages
        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    });
}
// only handle the sync call exception
process.on('uncaughtException', function (err) {
    console.error(err);
});
// now enable http server and socket.io
let server = require('http').createServer(app);
let io = require('socket.io').listen(server);
server.listen(config.serverPort);
// event listener for HTTP server "error" event
server.on('error', function (error) {
    if (error.syscall !== 'listen') throw error;
    let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
});
// event listener for HTTP server "listening" event
server.on('listening', function onListening() {
    let addr = server.address();
    let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
});
    // event listener for HTTP server "listening" event
    server.on('listening', function onListening() {
        let addr = server.address();
        let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    });
let socketHandler = new SocketHandler(io);
socketHandler.start();
    let socketHandler = new SocketHandler(io);
    socketHandler.start();
log.info('Starting IM server, version ' + config.version + ', running on port ' + server.address().port + ', ' + new Date().toLocaleString());
log.info('Configuration profile: ' + configFile.split('.')[1]);
    log.info('Starting IM server, version ' + config.version + ', running on port ' + server.address().port + ', ' + new Date().toLocaleString());
    log.info('Configuration profile: ' + configFile.split('.')[1]);
var Users =  require('./models/user/users');
let abc = new Users();
abc.isPatientId('not-patient_id');
});

+ 4 - 0
src/server/context.json

@ -0,0 +1,4 @@
{
  "name": "simple_inject",
  "scan": ["models", "repository"]
}

+ 23 - 7
src/server/models/user/users.js

@ -17,12 +17,14 @@ let redisConn = RedisClient.redisClient().connection;
let log = require('../../util/log');
let async = require('async');
let bearcate = require('bearcat');
var imDb = require('../../repository/mysql/db/im.db');
class Users extends BaseModel {
    constructor() {
        super();
        this.$id = 'users';
        this._key = RedisKeys.Users;
    }
@ -30,8 +32,14 @@ class Users extends BaseModel {
    }
    isPatientId(userId) {
        return async.waterfall([
    /**
     * 用户ID是否属于患者。
     *
     * @param userId
     * @param callback
     */
    isPatientId(userId, callback) {
        async.waterfall([
                function (callback) {
                    var sql = "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?";
@ -39,25 +47,33 @@ class Users extends BaseModel {
                        "sql": sql,
                        "args": [userId],
                        "handler": function (err, res) {
                            if(err) callback(err, res);
                            if (err) callback(err, res);
                            callback(null, res);
                        }
                    });
                },
                function (res, callback) {
                    callback(null, res.is_patient);
                    if (res.length === 0) return false;
                    callback(null, res[0].is_patient);
                }
            ],
            function (err, res) {
                if (err) {
                    log.error("User id probe failed: ", err);
                    return false;
                    log.error("User id check failed: ", err);
                    callback(null, false);
                    return;
                }
                return res;
                callback(null, res !== 0);
            });
    }
}
let Promises = require('bluebird');
Promises.promisifyAll(Users.prototype);
bearcate.module(Users, typeof module !== 'undefined' ? module : {});
module.exports = Users;

+ 15 - 0
src/server/node_modules/.bin/bearcat

@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
    *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
  "$basedir/node"  "$basedir/../bearcat/bin/bearcat-bin.js" "$@"
  ret=$?
else 
  node  "$basedir/../bearcat/bin/bearcat-bin.js" "$@"
  ret=$?
fi
exit $ret

+ 7 - 0
src/server/node_modules/.bin/bearcat.cmd

@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe"  "%~dp0\..\bearcat\bin\bearcat-bin.js" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node  "%~dp0\..\bearcat\bin\bearcat-bin.js" %*
)

+ 21 - 0
src/server/node_modules/bluebird/LICENSE

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013-2015 Petka Antonov
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.

+ 51 - 0
src/server/node_modules/bluebird/README.md

@ -0,0 +1,51 @@
<a href="http://promisesaplus.com/">
    <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
         title="Promises/A+ 1.1 compliant" align="right" />
</a>
[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
# Introduction
Bluebird is a fully featured promise library with focus on innovative features and performance
See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here.
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
# Questions and issues
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
## Thanks
Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. 
# License
The MIT License (MIT)
Copyright (c) 2013-2016 Petka Antonov
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 - 0
src/server/node_modules/bluebird/changelog.md

@ -0,0 +1 @@
[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)

File diff suppressed because it is too large
+ 3756 - 0
src/server/node_modules/bluebird/js/browser/bluebird.core.js


File diff suppressed because it is too large
+ 31 - 0
src/server/node_modules/bluebird/js/browser/bluebird.core.min.js


File diff suppressed because it is too large
+ 5598 - 0
src/server/node_modules/bluebird/js/browser/bluebird.js


File diff suppressed because it is too large
+ 31 - 0
src/server/node_modules/bluebird/js/browser/bluebird.min.js


+ 21 - 0
src/server/node_modules/bluebird/js/release/any.js

@ -0,0 +1,21 @@
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
    var ret = new SomePromiseArray(promises);
    var promise = ret.promise();
    ret.setHowMany(1);
    ret.setUnwrap();
    ret.init();
    return promise;
}
Promise.any = function (promises) {
    return any(promises);
};
Promise.prototype.any = function () {
    return any(this);
};
};

+ 55 - 0
src/server/node_modules/bluebird/js/release/assert.js

@ -0,0 +1,55 @@
"use strict";
module.exports = (function(){
var AssertionError = (function() {
    function AssertionError(a) {
        this.constructor$(a);
        this.message = a;
        this.name = "AssertionError";
    }
    AssertionError.prototype = new Error();
    AssertionError.prototype.constructor = AssertionError;
    AssertionError.prototype.constructor$ = Error;
    return AssertionError;
})();
function getParams(args) {
    var params = [];
    for (var i = 0; i < args.length; ++i) params.push("arg" + i);
    return params;
}
function nativeAssert(callName, args, expect) {
    try {
        var params = getParams(args);
        var constructorArgs = params;
        constructorArgs.push("return " +
                callName + "("+ params.join(",") + ");");
        var fn = Function.apply(null, constructorArgs);
        return fn.apply(null, args);
    } catch (e) {
        if (!(e instanceof SyntaxError)) {
            throw e;
        } else {
            return expect;
        }
    }
}
return function assert(boolExpr, message) {
    if (boolExpr === true) return;
    if (typeof boolExpr === "string" &&
        boolExpr.charAt(0) === "%") {
        var nativeCallName = boolExpr;
        var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];};
        if (nativeAssert(nativeCallName, args, message) === message) return;
        message = (nativeCallName + " !== " + message);
    }
    var ret = new AssertionError(message);
    if (Error.captureStackTrace) {
        Error.captureStackTrace(ret, assert);
    }
    throw ret;
};
})();

+ 166 - 0
src/server/node_modules/bluebird/js/release/async.js

@ -0,0 +1,166 @@
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
    this._customScheduler = false;
    this._isTickUsed = false;
    this._lateQueue = new Queue(16);
    this._normalQueue = new Queue(16);
    this._haveDrainedQueues = false;
    this._trampolineEnabled = true;
    var self = this;
    this.drainQueues = function () {
        self._drainQueues();
    };
    this._schedule = schedule;
}
Async.prototype.setScheduler = function(fn) {
    var prev = this._schedule;
    this._schedule = fn;
    this._customScheduler = true;
    return prev;
};
Async.prototype.hasCustomScheduler = function() {
    return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
    this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
    if (util.hasDevTools) {
        this._trampolineEnabled = false;
    }
};
Async.prototype.haveItemsQueued = function () {
    return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
    if (isNode) {
        process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
            "\n");
        process.exit(2);
    } else {
        this.throwLater(e);
    }
};
Async.prototype.throwLater = function(fn, arg) {
    if (arguments.length === 1) {
        arg = fn;
        fn = function () { throw arg; };
    }
    if (typeof setTimeout !== "undefined") {
        setTimeout(function() {
            fn(arg);
        }, 0);
    } else try {
        this._schedule(function() {
            fn(arg);
        });
    } catch (e) {
        throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
};
function AsyncInvokeLater(fn, receiver, arg) {
    this._lateQueue.push(fn, receiver, arg);
    this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
    this._normalQueue.push(fn, receiver, arg);
    this._queueTick();
}
function AsyncSettlePromises(promise) {
    this._normalQueue._pushOne(promise);
    this._queueTick();
}
if (!util.hasDevTools) {
    Async.prototype.invokeLater = AsyncInvokeLater;
    Async.prototype.invoke = AsyncInvoke;
    Async.prototype.settlePromises = AsyncSettlePromises;
} else {
    Async.prototype.invokeLater = function (fn, receiver, arg) {
        if (this._trampolineEnabled) {
            AsyncInvokeLater.call(this, fn, receiver, arg);
        } else {
            this._schedule(function() {
                setTimeout(function() {
                    fn.call(receiver, arg);
                }, 100);
            });
        }
    };
    Async.prototype.invoke = function (fn, receiver, arg) {
        if (this._trampolineEnabled) {
            AsyncInvoke.call(this, fn, receiver, arg);
        } else {
            this._schedule(function() {
                fn.call(receiver, arg);
            });
        }
    };
    Async.prototype.settlePromises = function(promise) {
        if (this._trampolineEnabled) {
            AsyncSettlePromises.call(this, promise);
        } else {
            this._schedule(function() {
                promise._settlePromises();
            });
        }
    };
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
    this._normalQueue.unshift(fn, receiver, arg);
    this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
    while (queue.length() > 0) {
        var fn = queue.shift();
        if (typeof fn !== "function") {
            fn._settlePromises();
            continue;
        }
        var receiver = queue.shift();
        var arg = queue.shift();
        fn.call(receiver, arg);
    }
};
Async.prototype._drainQueues = function () {
    this._drainQueue(this._normalQueue);
    this._reset();
    this._haveDrainedQueues = true;
    this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
    if (!this._isTickUsed) {
        this._isTickUsed = true;
        this._schedule(this.drainQueues);
    }
};
Async.prototype._reset = function () {
    this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;

+ 67 - 0
src/server/node_modules/bluebird/js/release/bind.js

@ -0,0 +1,67 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
    this._reject(e);
};
var targetRejected = function(e, context) {
    context.promiseRejectionQueued = true;
    context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
    if (((this._bitField & 50397184) === 0)) {
        this._resolveCallback(context.target);
    }
};
var bindingRejected = function(e, context) {
    if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
    if (!calledBind) {
        calledBind = true;
        Promise.prototype._propagateFrom = debug.propagateFromFunction();
        Promise.prototype._boundValue = debug.boundValueFunction();
    }
    var maybePromise = tryConvertToPromise(thisArg);
    var ret = new Promise(INTERNAL);
    ret._propagateFrom(this, 1);
    var target = this._target();
    ret._setBoundTo(maybePromise);
    if (maybePromise instanceof Promise) {
        var context = {
            promiseRejectionQueued: false,
            promise: ret,
            target: target,
            bindingPromise: maybePromise
        };
        target._then(INTERNAL, targetRejected, undefined, ret, context);
        maybePromise._then(
            bindingResolved, bindingRejected, undefined, ret, context);
        ret._setOnCancel(maybePromise);
    } else {
        ret._resolveCallback(target);
    }
    return ret;
};
Promise.prototype._setBoundTo = function (obj) {
    if (obj !== undefined) {
        this._bitField = this._bitField | 2097152;
        this._boundTo = obj;
    } else {
        this._bitField = this._bitField & (~2097152);
    }
};
Promise.prototype._isBound = function () {
    return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
    return Promise.resolve(value).bind(thisArg);
};
};

+ 11 - 0
src/server/node_modules/bluebird/js/release/bluebird.js

@ -0,0 +1,11 @@
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
    try { if (Promise === bluebird) Promise = old; }
    catch (e) {}
    return bluebird;
}
var bluebird = require("./promise")();
bluebird.noConflict = noConflict;
module.exports = bluebird;

+ 123 - 0
src/server/node_modules/bluebird/js/release/call_get.js

@ -0,0 +1,123 @@
"use strict";
var cr = Object.create;
if (cr) {
    var callerCache = cr(null);
    var getterCache = cr(null);
    callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!false) {
var makeMethodCaller = function (methodName) {
    return new Function("ensureMethod", "                                    \n\
        return function(obj) {                                               \n\
            'use strict'                                                     \n\
            var len = this.length;                                           \n\
            ensureMethod(obj, 'methodName');                                 \n\
            switch(len) {                                                    \n\
                case 1: return obj.methodName(this[0]);                      \n\
                case 2: return obj.methodName(this[0], this[1]);             \n\
                case 3: return obj.methodName(this[0], this[1], this[2]);    \n\
                case 0: return obj.methodName();                             \n\
                default:                                                     \n\
                    return obj.methodName.apply(obj, this);                  \n\
            }                                                                \n\
        };                                                                   \n\
        ".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
    return new Function("obj", "                                             \n\
        'use strict';                                                        \n\
        return obj.propertyName;                                             \n\
        ".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
    var ret = cache[name];
    if (typeof ret !== "function") {
        if (!isIdentifier(name)) {
            return null;
        }
        ret = compiler(name);
        cache[name] = ret;
        cache[" size"]++;
        if (cache[" size"] > 512) {
            var keys = Object.keys(cache);
            for (var i = 0; i < 256; ++i) delete cache[keys[i]];
            cache[" size"] = keys.length - 256;
        }
    }
    return ret;
};
getMethodCaller = function(name) {
    return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
    return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
    var fn;
    if (obj != null) fn = obj[methodName];
    if (typeof fn !== "function") {
        var message = "Object " + util.classString(obj) + " has no method '" +
            util.toString(methodName) + "'";
        throw new Promise.TypeError(message);
    }
    return fn;
}
function caller(obj) {
    var methodName = this.pop();
    var fn = ensureMethod(obj, methodName);
    return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
    var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
    if (!false) {
        if (canEvaluate) {
            var maybeCaller = getMethodCaller(methodName);
            if (maybeCaller !== null) {
                return this._then(
                    maybeCaller, undefined, undefined, args, undefined);
            }
        }
    }
    args.push(methodName);
    return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
    return obj[this];
}
function indexedGetter(obj) {
    var index = +this;
    if (index < 0) index = Math.max(0, index + obj.length);
    return obj[index];
}
Promise.prototype.get = function (propertyName) {
    var isIndex = (typeof propertyName === "number");
    var getter;
    if (!isIndex) {
        if (canEvaluate) {
            var maybeGetter = getGetter(propertyName);
            getter = maybeGetter !== null ? maybeGetter : namedGetter;
        } else {
            getter = namedGetter;
        }
    } else {
        getter = indexedGetter;
    }
    return this._then(getter, undefined, undefined, propertyName, undefined);
};
};

+ 129 - 0
src/server/node_modules/bluebird/js/release/cancel.js

@ -0,0 +1,129 @@
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
    if (!debug.cancellation()) return this._warn("cancellation is disabled");
    var promise = this;
    var child = promise;
    while (promise._isCancellable()) {
        if (!promise._cancelBy(child)) {
            if (child._isFollowing()) {
                child._followee().cancel();
            } else {
                child._cancelBranched();
            }
            break;
        }
        var parent = promise._cancellationParent;
        if (parent == null || !parent._isCancellable()) {
            if (promise._isFollowing()) {
                promise._followee().cancel();
            } else {
                promise._cancelBranched();
            }
            break;
        } else {
            if (promise._isFollowing()) promise._followee().cancel();
            promise._setWillBeCancelled();
            child = promise;
            promise = parent;
        }
    }
};
Promise.prototype._branchHasCancelled = function() {
    this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
    return this._branchesRemainingToCancel === undefined ||
           this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
    if (canceller === this) {
        this._branchesRemainingToCancel = 0;
        this._invokeOnCancel();
        return true;
    } else {
        this._branchHasCancelled();
        if (this._enoughBranchesHaveCancelled()) {
            this._invokeOnCancel();
            return true;
        }
    }
    return false;
};
Promise.prototype._cancelBranched = function() {
    if (this._enoughBranchesHaveCancelled()) {
        this._cancel();
    }
};
Promise.prototype._cancel = function() {
    if (!this._isCancellable()) return;
    this._setCancelled();
    async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
    if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
    this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function() {
    return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function() {
    return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
    if (util.isArray(onCancelCallback)) {
        for (var i = 0; i < onCancelCallback.length; ++i) {
            this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
        }
    } else if (onCancelCallback !== undefined) {
        if (typeof onCancelCallback === "function") {
            if (!internalOnly) {
                var e = tryCatch(onCancelCallback).call(this._boundValue());
                if (e === errorObj) {
                    this._attachExtraTrace(e.e);
                    async.throwLater(e.e);
                }
            }
        } else {
            onCancelCallback._resultCancelled(this);
        }
    }
};
Promise.prototype._invokeOnCancel = function() {
    var onCancelCallback = this._onCancel();
    this._unsetOnCancel();
    async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
    if (this._isCancellable()) {
        this._doInvokeOnCancel(this._onCancel(), true);
        this._unsetOnCancel();
    }
};
Promise.prototype._resultCancelled = function() {
    this.cancel();
};
};

+ 42 - 0
src/server/node_modules/bluebird/js/release/catch_filter.js

@ -0,0 +1,42 @@
"use strict";
module.exports = function(NEXT_FILTER) {
var util = require("./util");
var getKeys = require("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
    return function(e) {
        var boundTo = promise._boundValue();
        predicateLoop: for (var i = 0; i < instances.length; ++i) {
            var item = instances[i];
            if (item === Error ||
                (item != null && item.prototype instanceof Error)) {
                if (e instanceof item) {
                    return tryCatch(cb).call(boundTo, e);
                }
            } else if (typeof item === "function") {
                var matchesPredicate = tryCatch(item).call(boundTo, e);
                if (matchesPredicate === errorObj) {
                    return matchesPredicate;
                } else if (matchesPredicate) {
                    return tryCatch(cb).call(boundTo, e);
                }
            } else if (util.isObject(e)) {
                var keys = getKeys(item);
                for (var j = 0; j < keys.length; ++j) {
                    var key = keys[j];
                    if (item[key] != e[key]) {
                        continue predicateLoop;
                    }
                }
                return tryCatch(cb).call(boundTo, e);
            }
        }
        return NEXT_FILTER;
    };
}
return catchFilter;
};

+ 69 - 0
src/server/node_modules/bluebird/js/release/context.js

@ -0,0 +1,69 @@
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
    this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
    if (this._trace !== undefined) {
        this._trace._promiseCreated = null;
        contextStack.push(this._trace);
    }
};
Context.prototype._popContext = function () {
    if (this._trace !== undefined) {
        var trace = contextStack.pop();
        var ret = trace._promiseCreated;
        trace._promiseCreated = null;
        return ret;
    }
    return null;
};
function createContext() {
    if (longStackTraces) return new Context();
}
function peekContext() {
    var lastIndex = contextStack.length - 1;
    if (lastIndex >= 0) {
        return contextStack[lastIndex];
    }
    return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
    var Promise_pushContext = Promise.prototype._pushContext;
    var Promise_popContext = Promise.prototype._popContext;
    var Promise_PeekContext = Promise._peekContext;
    var Promise_peekContext = Promise.prototype._peekContext;
    var Promise_promiseCreated = Promise.prototype._promiseCreated;
    Context.deactivateLongStackTraces = function() {
        Promise.prototype._pushContext = Promise_pushContext;
        Promise.prototype._popContext = Promise_popContext;
        Promise._peekContext = Promise_PeekContext;
        Promise.prototype._peekContext = Promise_peekContext;
        Promise.prototype._promiseCreated = Promise_promiseCreated;
        longStackTraces = false;
    };
    longStackTraces = true;
    Promise.prototype._pushContext = Context.prototype._pushContext;
    Promise.prototype._popContext = Context.prototype._popContext;
    Promise._peekContext = Promise.prototype._peekContext = peekContext;
    Promise.prototype._promiseCreated = function() {
        var ctx = this._peekContext();
        if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
    };
};
return Context;
};

+ 915 - 0
src/server/node_modules/bluebird/js/release/debuggability.js

@ -0,0 +1,915 @@
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
    /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
                        (false ||
                         util.env("BLUEBIRD_DEBUG") ||
                         util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
    (debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
    (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
    (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
    var target = this._target();
    target._bitField = ((target._bitField & (~1048576)) |
                      524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
    if ((this._bitField & 524288) !== 0) return;
    this._setRejectionIsUnhandled();
    async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
    fireRejectionEvent("rejectionHandled",
                                  unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
    this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
    return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
    if (this._isRejectionUnhandled()) {
        var reason = this._settledValue();
        this._setUnhandledRejectionIsNotified();
        fireRejectionEvent("unhandledRejection",
                                      possiblyUnhandledRejection, reason, this);
    }
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
    this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
    this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
    return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
    this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
    this._bitField = this._bitField & (~1048576);
    if (this._isUnhandledRejectionNotified()) {
        this._unsetUnhandledRejectionIsNotified();
        this._notifyUnhandledRejectionIsHandled();
    }
};
Promise.prototype._isRejectionUnhandled = function () {
    return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
    return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
    var domain = getDomain();
    possiblyUnhandledRejection =
        typeof fn === "function" ? (domain === null ?
                                            fn : util.domainBind(domain, fn))
                                 : undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
    var domain = getDomain();
    unhandledRejectionHandled =
        typeof fn === "function" ? (domain === null ?
                                            fn : util.domainBind(domain, fn))
                                 : undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
    if (async.haveItemsQueued() && !config.longStackTraces) {
        throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    if (!config.longStackTraces && longStackTracesIsSupported()) {
        var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
        var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
        config.longStackTraces = true;
        disableLongStackTraces = function() {
            if (async.haveItemsQueued() && !config.longStackTraces) {
                throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
            }
            Promise.prototype._captureStackTrace = Promise_captureStackTrace;
            Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
            Context.deactivateLongStackTraces();
            async.enableTrampoline();
            config.longStackTraces = false;
        };
        Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
        Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
        Context.activateLongStackTraces();
        async.disableTrampolineIfNecessary();
    }
};
Promise.hasLongStackTraces = function () {
    return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
    try {
        if (typeof CustomEvent === "function") {
            var event = new CustomEvent("CustomEvent");
            util.global.dispatchEvent(event);
            return function(name, event) {
                var domEvent = new CustomEvent(name.toLowerCase(), {
                    detail: event,
                    cancelable: true
                });
                return !util.global.dispatchEvent(domEvent);
            };
        } else if (typeof Event === "function") {
            var event = new Event("CustomEvent");
            util.global.dispatchEvent(event);
            return function(name, event) {
                var domEvent = new Event(name.toLowerCase(), {
                    cancelable: true
                });
                domEvent.detail = event;
                return !util.global.dispatchEvent(domEvent);
            };
        } else {
            var event = document.createEvent("CustomEvent");
            event.initCustomEvent("testingtheevent", false, true, {});
            util.global.dispatchEvent(event);
            return function(name, event) {
                var domEvent = document.createEvent("CustomEvent");
                domEvent.initCustomEvent(name.toLowerCase(), false, true,
                    event);
                return !util.global.dispatchEvent(domEvent);
            };
        }
    } catch (e) {}
    return function() {
        return false;
    };
})();
var fireGlobalEvent = (function() {
    if (util.isNode) {
        return function() {
            return process.emit.apply(process, arguments);
        };
    } else {
        if (!util.global) {
            return function() {
                return false;
            };
        }
        return function(name) {
            var methodName = "on" + name.toLowerCase();
            var method = util.global[methodName];
            if (!method) return false;
            method.apply(util.global, [].slice.call(arguments, 1));
            return true;
        };
    }
})();
function generatePromiseLifecycleEventObject(name, promise) {
    return {promise: promise};
}
var eventToObjectGenerator = {
    promiseCreated: generatePromiseLifecycleEventObject,
    promiseFulfilled: generatePromiseLifecycleEventObject,
    promiseRejected: generatePromiseLifecycleEventObject,
    promiseResolved: generatePromiseLifecycleEventObject,
    promiseCancelled: generatePromiseLifecycleEventObject,
    promiseChained: function(name, promise, child) {
        return {promise: promise, child: child};
    },
    warning: function(name, warning) {
        return {warning: warning};
    },
    unhandledRejection: function (name, reason, promise) {
        return {reason: reason, promise: promise};
    },
    rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
    var globalEventFired = false;
    try {
        globalEventFired = fireGlobalEvent.apply(null, arguments);
    } catch (e) {
        async.throwLater(e);
        globalEventFired = true;
    }
    var domEventFired = false;
    try {
        domEventFired = fireDomEvent(name,
                    eventToObjectGenerator[name].apply(null, arguments));
    } catch (e) {
        async.throwLater(e);
        domEventFired = true;
    }
    return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
    opts = Object(opts);
    if ("longStackTraces" in opts) {
        if (opts.longStackTraces) {
            Promise.longStackTraces();
        } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
            disableLongStackTraces();
        }
    }
    if ("warnings" in opts) {
        var warningsOption = opts.warnings;
        config.warnings = !!warningsOption;
        wForgottenReturn = config.warnings;
        if (util.isObject(warningsOption)) {
            if ("wForgottenReturn" in warningsOption) {
                wForgottenReturn = !!warningsOption.wForgottenReturn;
            }
        }
    }
    if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
        if (async.haveItemsQueued()) {
            throw new Error(
                "cannot enable cancellation after promises are in use");
        }
        Promise.prototype._clearCancellationData =
            cancellationClearCancellationData;
        Promise.prototype._propagateFrom = cancellationPropagateFrom;
        Promise.prototype._onCancel = cancellationOnCancel;
        Promise.prototype._setOnCancel = cancellationSetOnCancel;
        Promise.prototype._attachCancellationCallback =
            cancellationAttachCancellationCallback;
        Promise.prototype._execute = cancellationExecute;
        propagateFromFunction = cancellationPropagateFrom;
        config.cancellation = true;
    }
    if ("monitoring" in opts) {
        if (opts.monitoring && !config.monitoring) {
            config.monitoring = true;
            Promise.prototype._fireEvent = activeFireEvent;
        } else if (!opts.monitoring && config.monitoring) {
            config.monitoring = false;
            Promise.prototype._fireEvent = defaultFireEvent;
        }
    }
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
    try {
        executor(resolve, reject);
    } catch (e) {
        return e;
    }
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
    ;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
    ;
    ;
};
function cancellationExecute(executor, resolve, reject) {
    var promise = this;
    try {
        executor(resolve, reject, function(onCancel) {
            if (typeof onCancel !== "function") {
                throw new TypeError("onCancel must be a function, got: " +
                                    util.toString(onCancel));
            }
            promise._attachCancellationCallback(onCancel);
        });
    } catch (e) {
        return e;
    }
}
function cancellationAttachCancellationCallback(onCancel) {
    if (!this._isCancellable()) return this;
    var previousOnCancel = this._onCancel();
    if (previousOnCancel !== undefined) {
        if (util.isArray(previousOnCancel)) {
            previousOnCancel.push(onCancel);
        } else {
            this._setOnCancel([previousOnCancel, onCancel]);
        }
    } else {
        this._setOnCancel(onCancel);
    }
}
function cancellationOnCancel() {
    return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
    this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
    this._cancellationParent = undefined;
    this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
    if ((flags & 1) !== 0) {
        this._cancellationParent = parent;
        var branchesRemainingToCancel = parent._branchesRemainingToCancel;
        if (branchesRemainingToCancel === undefined) {
            branchesRemainingToCancel = 0;
        }
        parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
    }
    if ((flags & 2) !== 0 && parent._isBound()) {
        this._setBoundTo(parent._boundTo);
    }
}
function bindingPropagateFrom(parent, flags) {
    if ((flags & 2) !== 0 && parent._isBound()) {
        this._setBoundTo(parent._boundTo);
    }
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
    var ret = this._boundTo;
    if (ret !== undefined) {
        if (ret instanceof Promise) {
            if (ret.isFulfilled()) {
                return ret.value();
            } else {
                return undefined;
            }
        }
    }
    return ret;
}
function longStackTracesCaptureStackTrace() {
    this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
    if (canAttachTrace(error)) {
        var trace = this._trace;
        if (trace !== undefined) {
            if (ignoreSelf) trace = trace._parent;
        }
        if (trace !== undefined) {
            trace.attachExtraTrace(error);
        } else if (!error.__stackCleaned__) {
            var parsed = parseStackAndMessage(error);
            util.notEnumerableProp(error, "stack",
                parsed.message + "\n" + parsed.stack.join("\n"));
            util.notEnumerableProp(error, "__stackCleaned__", true);
        }
    }
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
                               parent) {
    if (returnValue === undefined && promiseCreated !== null &&
        wForgottenReturn) {
        if (parent !== undefined && parent._returnedNonUndefined()) return;
        if ((promise._bitField & 65535) === 0) return;
        if (name) name = name + " ";
        var handlerLine = "";
        var creatorLine = "";
        if (promiseCreated._trace) {
            var traceLines = promiseCreated._trace.stack.split("\n");
            var stack = cleanStack(traceLines);
            for (var i = stack.length - 1; i >= 0; --i) {
                var line = stack[i];
                if (!nodeFramePattern.test(line)) {
                    var lineMatches = line.match(parseLinePattern);
                    if (lineMatches) {
                        handlerLine  = "at " + lineMatches[1] +
                            ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
                    }
                    break;
                }
            }
            if (stack.length > 0) {
                var firstUserLine = stack[0];
                for (var i = 0; i < traceLines.length; ++i) {
                    if (traceLines[i] === firstUserLine) {
                        if (i > 0) {
                            creatorLine = "\n" + traceLines[i - 1];
                        }
                        break;
                    }
                }
            }
        }
        var msg = "a promise was created in a " + name +
            "handler " + handlerLine + "but was not returned from it, " +
            "see http://goo.gl/rRqMUw" +
            creatorLine;
        promise._warn(msg, true, promiseCreated);
    }
}
function deprecated(name, replacement) {
    var message = name +
        " is deprecated and will be removed in a future version.";
    if (replacement) message += " Use " + replacement + " instead.";
    return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
    if (!config.warnings) return;
    var warning = new Warning(message);
    var ctx;
    if (shouldUseOwnTrace) {
        promise._attachExtraTrace(warning);
    } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
        ctx.attachExtraTrace(warning);
    } else {
        var parsed = parseStackAndMessage(warning);
        warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
    }
    if (!activeFireEvent("warning", warning)) {
        formatAndLogError(warning, "", true);
    }
}
function reconstructStack(message, stacks) {
    for (var i = 0; i < stacks.length - 1; ++i) {
        stacks[i].push("From previous event:");
        stacks[i] = stacks[i].join("\n");
    }
    if (i < stacks.length) {
        stacks[i] = stacks[i].join("\n");
    }
    return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
    for (var i = 0; i < stacks.length; ++i) {
        if (stacks[i].length === 0 ||
            ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
            stacks.splice(i, 1);
            i--;
        }
    }
}
function removeCommonRoots(stacks) {
    var current = stacks[0];
    for (var i = 1; i < stacks.length; ++i) {
        var prev = stacks[i];
        var currentLastIndex = current.length - 1;
        var currentLastLine = current[currentLastIndex];
        var commonRootMeetPoint = -1;
        for (var j = prev.length - 1; j >= 0; --j) {
            if (prev[j] === currentLastLine) {
                commonRootMeetPoint = j;
                break;
            }
        }
        for (var j = commonRootMeetPoint; j >= 0; --j) {
            var line = prev[j];
            if (current[currentLastIndex] === line) {
                current.pop();
                currentLastIndex--;
            } else {
                break;
            }
        }
        current = prev;
    }
}
function cleanStack(stack) {
    var ret = [];
    for (var i = 0; i < stack.length; ++i) {
        var line = stack[i];
        var isTraceLine = "    (No stack trace)" === line ||
            stackFramePattern.test(line);
        var isInternalFrame = isTraceLine && shouldIgnore(line);
        if (isTraceLine && !isInternalFrame) {
            if (indentStackFrames && line.charAt(0) !== " ") {
                line = "    " + line;
            }
            ret.push(line);
        }
    }
    return ret;
}
function stackFramesAsArray(error) {
    var stack = error.stack.replace(/\s+$/g, "").split("\n");
    for (var i = 0; i < stack.length; ++i) {
        var line = stack[i];
        if ("    (No stack trace)" === line || stackFramePattern.test(line)) {
            break;
        }
    }
    if (i > 0) {
        stack = stack.slice(i);
    }
    return stack;
}
function parseStackAndMessage(error) {
    var stack = error.stack;
    var message = error.toString();
    stack = typeof stack === "string" && stack.length > 0
                ? stackFramesAsArray(error) : ["    (No stack trace)"];
    return {
        message: message,
        stack: cleanStack(stack)
    };
}
function formatAndLogError(error, title, isSoft) {
    if (typeof console !== "undefined") {
        var message;
        if (util.isObject(error)) {
            var stack = error.stack;
            message = title + formatStack(stack, error);
        } else {
            message = title + String(error);
        }
        if (typeof printWarning === "function") {
            printWarning(message, isSoft);
        } else if (typeof console.log === "function" ||
            typeof console.log === "object") {
            console.log(message);
        }
    }
}
function fireRejectionEvent(name, localHandler, reason, promise) {
    var localEventFired = false;
    try {
        if (typeof localHandler === "function") {
            localEventFired = true;
            if (name === "rejectionHandled") {
                localHandler(promise);
            } else {
                localHandler(reason, promise);
            }
        }
    } catch (e) {
        async.throwLater(e);
    }
    if (name === "unhandledRejection") {
        if (!activeFireEvent(name, reason, promise) && !localEventFired) {
            formatAndLogError(reason, "Unhandled rejection ");
        }
    } else {
        activeFireEvent(name, promise);
    }
}
function formatNonError(obj) {
    var str;
    if (typeof obj === "function") {
        str = "[function " +
            (obj.name || "anonymous") +
            "]";
    } else {
        str = obj && typeof obj.toString === "function"
            ? obj.toString() : util.toString(obj);
        var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
        if (ruselessToString.test(str)) {
            try {
                var newStr = JSON.stringify(obj);
                str = newStr;
            }
            catch(e) {
            }
        }
        if (str.length === 0) {
            str = "(empty array)";
        }
    }
    return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
    var maxChars = 41;
    if (str.length < maxChars) {
        return str;
    }
    return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
    return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
    var matches = line.match(parseLineInfoRegex);
    if (matches) {
        return {
            fileName: matches[1],
            line: parseInt(matches[2], 10)
        };
    }
}
function setBounds(firstLineError, lastLineError) {
    if (!longStackTracesIsSupported()) return;
    var firstStackLines = firstLineError.stack.split("\n");
    var lastStackLines = lastLineError.stack.split("\n");
    var firstIndex = -1;
    var lastIndex = -1;
    var firstFileName;
    var lastFileName;
    for (var i = 0; i < firstStackLines.length; ++i) {
        var result = parseLineInfo(firstStackLines[i]);
        if (result) {
            firstFileName = result.fileName;
            firstIndex = result.line;
            break;
        }
    }
    for (var i = 0; i < lastStackLines.length; ++i) {
        var result = parseLineInfo(lastStackLines[i]);
        if (result) {
            lastFileName = result.fileName;
            lastIndex = result.line;
            break;
        }
    }
    if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
        firstFileName !== lastFileName || firstIndex >= lastIndex) {
        return;
    }
    shouldIgnore = function(line) {
        if (bluebirdFramePattern.test(line)) return true;
        var info = parseLineInfo(line);
        if (info) {
            if (info.fileName === firstFileName &&
                (firstIndex <= info.line && info.line <= lastIndex)) {
                return true;
            }
        }
        return false;
    };
}
function CapturedTrace(parent) {
    this._parent = parent;
    this._promisesCreated = 0;
    var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
    captureStackTrace(this, CapturedTrace);
    if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
    var length = this._length;
    if (length < 2) return;
    var nodes = [];
    var stackToIndex = {};
    for (var i = 0, node = this; node !== undefined; ++i) {
        nodes.push(node);
        node = node._parent;
    }
    length = this._length = i;
    for (var i = length - 1; i >= 0; --i) {
        var stack = nodes[i].stack;
        if (stackToIndex[stack] === undefined) {
            stackToIndex[stack] = i;
        }
    }
    for (var i = 0; i < length; ++i) {
        var currentStack = nodes[i].stack;
        var index = stackToIndex[currentStack];
        if (index !== undefined && index !== i) {
            if (index > 0) {
                nodes[index - 1]._parent = undefined;
                nodes[index - 1]._length = 1;
            }
            nodes[i]._parent = undefined;
            nodes[i]._length = 1;
            var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
            if (index < length - 1) {
                cycleEdgeNode._parent = nodes[index + 1];
                cycleEdgeNode._parent.uncycle();
                cycleEdgeNode._length =
                    cycleEdgeNode._parent._length + 1;
            } else {
                cycleEdgeNode._parent = undefined;
                cycleEdgeNode._length = 1;
            }
            var currentChildLength = cycleEdgeNode._length + 1;
            for (var j = i - 2; j >= 0; --j) {
                nodes[j]._length = currentChildLength;
                currentChildLength++;
            }
            return;
        }
    }
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
    if (error.__stackCleaned__) return;
    this.uncycle();
    var parsed = parseStackAndMessage(error);
    var message = parsed.message;
    var stacks = [parsed.stack];
    var trace = this;
    while (trace !== undefined) {
        stacks.push(cleanStack(trace.stack.split("\n")));
        trace = trace._parent;
    }
    removeCommonRoots(stacks);
    removeDuplicateOrEmptyJumps(stacks);
    util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
    util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
    var v8stackFramePattern = /^\s*at\s*/;
    var v8stackFormatter = function(stack, error) {
        if (typeof stack === "string") return stack;
        if (error.name !== undefined &&
            error.message !== undefined) {
            return error.toString();
        }
        return formatNonError(error);
    };
    if (typeof Error.stackTraceLimit === "number" &&
        typeof Error.captureStackTrace === "function") {
        Error.stackTraceLimit += 6;
        stackFramePattern = v8stackFramePattern;
        formatStack = v8stackFormatter;
        var captureStackTrace = Error.captureStackTrace;
        shouldIgnore = function(line) {
            return bluebirdFramePattern.test(line);
        };
        return function(receiver, ignoreUntil) {
            Error.stackTraceLimit += 6;
            captureStackTrace(receiver, ignoreUntil);
            Error.stackTraceLimit -= 6;
        };
    }
    var err = new Error();
    if (typeof err.stack === "string" &&
        err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
        stackFramePattern = /@/;
        formatStack = v8stackFormatter;
        indentStackFrames = true;
        return function captureStackTrace(o) {
            o.stack = new Error().stack;
        };
    }
    var hasStackAfterThrow;
    try { throw new Error(); }
    catch(e) {
        hasStackAfterThrow = ("stack" in e);
    }
    if (!("stack" in err) && hasStackAfterThrow &&
        typeof Error.stackTraceLimit === "number") {
        stackFramePattern = v8stackFramePattern;
        formatStack = v8stackFormatter;
        return function captureStackTrace(o) {
            Error.stackTraceLimit += 6;
            try { throw new Error(); }
            catch(e) { o.stack = e.stack; }
            Error.stackTraceLimit -= 6;
        };
    }
    formatStack = function(stack, error) {
        if (typeof stack === "string") return stack;
        if ((typeof error === "object" ||
            typeof error === "function") &&
            error.name !== undefined &&
            error.message !== undefined) {
            return error.toString();
        }
        return formatNonError(error);
    };
    return null;
})([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
    printWarning = function (message) {
        console.warn(message);
    };
    if (util.isNode && process.stderr.isTTY) {
        printWarning = function(message, isSoft) {
            var color = isSoft ? "\u001b[33m" : "\u001b[31m";
            console.warn(color + message + "\u001b[0m\n");
        };
    } else if (!util.isNode && typeof (new Error().stack) === "string") {
        printWarning = function(message, isSoft) {
            console.warn("%c" + message,
                        isSoft ? "color: darkorange" : "color: red");
        };
    }
}
var config = {
    warnings: warnings,
    longStackTraces: false,
    cancellation: false,
    monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
    longStackTraces: function() {
        return config.longStackTraces;
    },
    warnings: function() {
        return config.warnings;
    },
    cancellation: function() {
        return config.cancellation;
    },
    monitoring: function() {
        return config.monitoring;
    },
    propagateFromFunction: function() {
        return propagateFromFunction;
    },
    boundValueFunction: function() {
        return boundValueFunction;
    },
    checkForgottenReturns: checkForgottenReturns,
    setBounds: setBounds,
    warn: warn,
    deprecated: deprecated,
    CapturedTrace: CapturedTrace,
    fireDomEvent: fireDomEvent,
    fireGlobalEvent: fireGlobalEvent
};
};

+ 46 - 0
src/server/node_modules/bluebird/js/release/direct_resolve.js

@ -0,0 +1,46 @@
"use strict";
module.exports = function(Promise) {
function returner() {
    return this.value;
}
function thrower() {
    throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
    if (value instanceof Promise) value.suppressUnhandledRejections();
    return this._then(
        returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
    return this._then(
        thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
    if (arguments.length <= 1) {
        return this._then(
            undefined, thrower, undefined, {reason: reason}, undefined);
    } else {
        var _reason = arguments[1];
        var handler = function() {throw _reason;};
        return this.caught(reason, handler);
    }
};
Promise.prototype.catchReturn = function (value) {
    if (arguments.length <= 1) {
        if (value instanceof Promise) value.suppressUnhandledRejections();
        return this._then(
            undefined, returner, undefined, {value: value}, undefined);
    } else {
        var _value = arguments[1];
        if (_value instanceof Promise) _value.suppressUnhandledRejections();
        var handler = function() {return _value;};
        return this.caught(value, handler);
    }
};
};

+ 30 - 0
src/server/node_modules/bluebird/js/release/each.js

@ -0,0 +1,30 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
    return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
    return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
    return PromiseReduce(this, fn, INTERNAL, 0)
              ._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
    return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
    return PromiseReduce(promises, fn, INTERNAL, 0)
              ._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};

+ 116 - 0
src/server/node_modules/bluebird/js/release/errors.js

@ -0,0 +1,116 @@
"use strict";
var es5 = require("./es5");
var Objectfreeze = es5.freeze;
var util = require("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
    function SubError(message) {
        if (!(this instanceof SubError)) return new SubError(message);
        notEnumerableProp(this, "message",
            typeof message === "string" ? message : defaultMessage);
        notEnumerableProp(this, "name", nameProperty);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        } else {
            Error.call(this);
        }
    }
    inherits(SubError, Error);
    return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
    _TypeError = TypeError;
    _RangeError = RangeError;
} catch(e) {
    _TypeError = subError("TypeError", "type error");
    _RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
    "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
    if (typeof Array.prototype[methods[i]] === "function") {
        AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
    }
}
es5.defineProperty(AggregateError.prototype, "length", {
    value: 0,
    configurable: false,
    writable: true,
    enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
    var indent = Array(level * 4 + 1).join(" ");
    var ret = "\n" + indent + "AggregateError of:" + "\n";
    level++;
    indent = Array(level * 4 + 1).join(" ");
    for (var i = 0; i < this.length; ++i) {
        var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
        var lines = str.split("\n");
        for (var j = 0; j < lines.length; ++j) {
            lines[j] = indent + lines[j];
        }
        str = lines.join("\n");
        ret += str + "\n";
    }
    level--;
    return ret;
};
function OperationalError(message) {
    if (!(this instanceof OperationalError))
        return new OperationalError(message);
    notEnumerableProp(this, "name", "OperationalError");
    notEnumerableProp(this, "message", message);
    this.cause = message;
    this["isOperational"] = true;
    if (message instanceof Error) {
        notEnumerableProp(this, "message", message.message);
        notEnumerableProp(this, "stack", message.stack);
    } else if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
    }
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
    errorTypes = Objectfreeze({
        CancellationError: CancellationError,
        TimeoutError: TimeoutError,
        OperationalError: OperationalError,
        RejectionError: OperationalError,
        AggregateError: AggregateError
    });
    es5.defineProperty(Error, "__BluebirdErrorTypes__", {
        value: errorTypes,
        writable: false,
        enumerable: false,
        configurable: false
    });
}
module.exports = {
    Error: Error,
    TypeError: _TypeError,
    RangeError: _RangeError,
    CancellationError: errorTypes.CancellationError,
    OperationalError: errorTypes.OperationalError,
    TimeoutError: errorTypes.TimeoutError,
    AggregateError: errorTypes.AggregateError,
    Warning: Warning
};

+ 80 - 0
src/server/node_modules/bluebird/js/release/es5.js

@ -0,0 +1,80 @@
var isES5 = (function(){
    "use strict";
    return this === undefined;
})();
if (isES5) {
    module.exports = {
        freeze: Object.freeze,
        defineProperty: Object.defineProperty,
        getDescriptor: Object.getOwnPropertyDescriptor,
        keys: Object.keys,
        names: Object.getOwnPropertyNames,
        getPrototypeOf: Object.getPrototypeOf,
        isArray: Array.isArray,
        isES5: isES5,
        propertyIsWritable: function(obj, prop) {
            var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
            return !!(!descriptor || descriptor.writable || descriptor.set);
        }
    };
} else {
    var has = {}.hasOwnProperty;
    var str = {}.toString;
    var proto = {}.constructor.prototype;
    var ObjectKeys = function (o) {
        var ret = [];
        for (var key in o) {
            if (has.call(o, key)) {
                ret.push(key);
            }
        }
        return ret;
    };
    var ObjectGetDescriptor = function(o, key) {
        return {value: o[key]};
    };
    var ObjectDefineProperty = function (o, key, desc) {
        o[key] = desc.value;
        return o;
    };
    var ObjectFreeze = function (obj) {
        return obj;
    };
    var ObjectGetPrototypeOf = function (obj) {
        try {
            return Object(obj).constructor.prototype;
        }
        catch (e) {
            return proto;
        }
    };
    var ArrayIsArray = function (obj) {
        try {
            return str.call(obj) === "[object Array]";
        }
        catch(e) {
            return false;
        }
    };
    module.exports = {
        isArray: ArrayIsArray,
        keys: ObjectKeys,
        names: ObjectKeys,
        defineProperty: ObjectDefineProperty,
        getDescriptor: ObjectGetDescriptor,
        freeze: ObjectFreeze,
        getPrototypeOf: ObjectGetPrototypeOf,
        isES5: isES5,
        propertyIsWritable: function() {
            return true;
        }
    };
}

+ 12 - 0
src/server/node_modules/bluebird/js/release/filter.js

@ -0,0 +1,12 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
    return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
    return PromiseMap(promises, fn, options, INTERNAL);
};
};

+ 111 - 0
src/server/node_modules/bluebird/js/release/finally.js

@ -0,0 +1,111 @@
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
function PassThroughHandlerContext(promise, type, handler) {
    this.promise = promise;
    this.type = type;
    this.handler = handler;
    this.called = false;
    this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
    return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
    this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
    checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
    if (ctx.cancelPromise != null) {
        if (arguments.length > 1) {
            ctx.cancelPromise._reject(reason);
        } else {
            ctx.cancelPromise._cancel();
        }
        ctx.cancelPromise = null;
        return true;
    }
    return false;
}
function succeed() {
    return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
    if (checkCancel(this, reason)) return;
    errorObj.e = reason;
    return errorObj;
}
function finallyHandler(reasonOrValue) {
    var promise = this.promise;
    var handler = this.handler;
    if (!this.called) {
        this.called = true;
        var ret = this.isFinallyHandler()
            ? handler.call(promise._boundValue())
            : handler.call(promise._boundValue(), reasonOrValue);
        if (ret !== undefined) {
            promise._setReturnedNonUndefined();
            var maybePromise = tryConvertToPromise(ret, promise);
            if (maybePromise instanceof Promise) {
                if (this.cancelPromise != null) {
                    if (maybePromise._isCancelled()) {
                        var reason =
                            new CancellationError("late cancellation observer");
                        promise._attachExtraTrace(reason);
                        errorObj.e = reason;
                        return errorObj;
                    } else if (maybePromise.isPending()) {
                        maybePromise._attachCancellationCallback(
                            new FinallyHandlerCancelReaction(this));
                    }
                }
                return maybePromise._then(
                    succeed, fail, undefined, this, undefined);
            }
        }
    }
    if (promise.isRejected()) {
        checkCancel(this);
        errorObj.e = reasonOrValue;
        return errorObj;
    } else {
        checkCancel(this);
        return reasonOrValue;
    }
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
    if (typeof handler !== "function") return this.then();
    return this._then(success,
                      fail,
                      undefined,
                      new PassThroughHandlerContext(this, type, handler),
                      undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
    return this._passThrough(handler,
                             0,
                             finallyHandler,
                             finallyHandler);
};
Promise.prototype.tap = function (handler) {
    return this._passThrough(handler, 1, finallyHandler);
};
return PassThroughHandlerContext;
};

+ 223 - 0
src/server/node_modules/bluebird/js/release/generators.js

@ -0,0 +1,223 @@
"use strict";
module.exports = function(Promise,
                          apiRejection,
                          INTERNAL,
                          tryConvertToPromise,
                          Proxyable,
                          debug) {
var errors = require("./errors");
var TypeError = errors.TypeError;
var util = require("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
    for (var i = 0; i < yieldHandlers.length; ++i) {
        traceParent._pushContext();
        var result = tryCatch(yieldHandlers[i])(value);
        traceParent._popContext();
        if (result === errorObj) {
            traceParent._pushContext();
            var ret = Promise.reject(errorObj.e);
            traceParent._popContext();
            return ret;
        }
        var maybePromise = tryConvertToPromise(result, traceParent);
        if (maybePromise instanceof Promise) return maybePromise;
    }
    return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
    if (debug.cancellation()) {
        var internal = new Promise(INTERNAL);
        var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
        this._promise = internal.lastly(function() {
            return _finallyPromise;
        });
        internal._captureStackTrace();
        internal._setOnCancel(this);
    } else {
        var promise = this._promise = new Promise(INTERNAL);
        promise._captureStackTrace();
    }
    this._stack = stack;
    this._generatorFunction = generatorFunction;
    this._receiver = receiver;
    this._generator = undefined;
    this._yieldHandlers = typeof yieldHandler === "function"
        ? [yieldHandler].concat(yieldHandlers)
        : yieldHandlers;
    this._yieldedPromise = null;
    this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
    return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
    this._promise = this._generator = null;
    if (debug.cancellation() && this._finallyPromise !== null) {
        this._finallyPromise._fulfill();
        this._finallyPromise = null;
    }
};
PromiseSpawn.prototype._promiseCancelled = function() {
    if (this._isResolved()) return;
    var implementsReturn = typeof this._generator["return"] !== "undefined";
    var result;
    if (!implementsReturn) {
        var reason = new Promise.CancellationError(
            "generator .return() sentinel");
        Promise.coroutine.returnSentinel = reason;
        this._promise._attachExtraTrace(reason);
        this._promise._pushContext();
        result = tryCatch(this._generator["throw"]).call(this._generator,
                                                         reason);
        this._promise._popContext();
    } else {
        this._promise._pushContext();
        result = tryCatch(this._generator["return"]).call(this._generator,
                                                          undefined);
        this._promise._popContext();
    }
    this._cancellationPhase = true;
    this._yieldedPromise = null;
    this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
    this._yieldedPromise = null;
    this._promise._pushContext();
    var result = tryCatch(this._generator.next).call(this._generator, value);
    this._promise._popContext();
    this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
    this._yieldedPromise = null;
    this._promise._attachExtraTrace(reason);
    this._promise._pushContext();
    var result = tryCatch(this._generator["throw"])
        .call(this._generator, reason);
    this._promise._popContext();
    this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
    if (this._yieldedPromise instanceof Promise) {
        var promise = this._yieldedPromise;
        this._yieldedPromise = null;
        promise.cancel();
    }
};
PromiseSpawn.prototype.promise = function () {
    return this._promise;
};
PromiseSpawn.prototype._run = function () {
    this._generator = this._generatorFunction.call(this._receiver);
    this._receiver =
        this._generatorFunction = undefined;
    this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
    var promise = this._promise;
    if (result === errorObj) {
        this._cleanup();
        if (this._cancellationPhase) {
            return promise.cancel();
        } else {
            return promise._rejectCallback(result.e, false);
        }
    }
    var value = result.value;
    if (result.done === true) {
        this._cleanup();
        if (this._cancellationPhase) {
            return promise.cancel();
        } else {
            return promise._resolveCallback(value);
        }
    } else {
        var maybePromise = tryConvertToPromise(value, this._promise);
        if (!(maybePromise instanceof Promise)) {
            maybePromise =
                promiseFromYieldHandler(maybePromise,
                                        this._yieldHandlers,
                                        this._promise);
            if (maybePromise === null) {
                this._promiseRejected(
                    new TypeError(
                        "A value %s was yielded that could not be treated as a promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
                        "From coroutine:\u000a" +
                        this._stack.split("\n").slice(1, -7).join("\n")
                    )
                );
                return;
            }
        }
        maybePromise = maybePromise._target();
        var bitField = maybePromise._bitField;
        ;
        if (((bitField & 50397184) === 0)) {
            this._yieldedPromise = maybePromise;
            maybePromise._proxy(this, null);
        } else if (((bitField & 33554432) !== 0)) {
            Promise._async.invoke(
                this._promiseFulfilled, this, maybePromise._value()
            );
        } else if (((bitField & 16777216) !== 0)) {
            Promise._async.invoke(
                this._promiseRejected, this, maybePromise._reason()
            );
        } else {
            this._promiseCancelled();
        }
    }
};
Promise.coroutine = function (generatorFunction, options) {
    if (typeof generatorFunction !== "function") {
        throw new TypeError("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    var yieldHandler = Object(options).yieldHandler;
    var PromiseSpawn$ = PromiseSpawn;
    var stack = new Error().stack;
    return function () {
        var generator = generatorFunction.apply(this, arguments);
        var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
                                      stack);
        var ret = spawn.promise();
        spawn._generator = generator;
        spawn._promiseFulfilled(undefined);
        return ret;
    };
};
Promise.coroutine.addYieldHandler = function(fn) {
    if (typeof fn !== "function") {
        throw new TypeError("expecting a function but got " + util.classString(fn));
    }
    yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
    debug.deprecated("Promise.spawn()", "Promise.coroutine()");
    if (typeof generatorFunction !== "function") {
        return apiRejection("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    var spawn = new PromiseSpawn(generatorFunction, this);
    var ret = spawn.promise();
    spawn._run(Promise.spawn);
    return ret;
};
};

+ 168 - 0
src/server/node_modules/bluebird/js/release/join.js

@ -0,0 +1,168 @@
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
         getDomain) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!false) {
if (canEvaluate) {
    var thenCallback = function(i) {
        return new Function("value", "holder", "                             \n\
            'use strict';                                                    \n\
            holder.pIndex = value;                                           \n\
            holder.checkFulfillment(this);                                   \n\
            ".replace(/Index/g, i));
    };
    var promiseSetter = function(i) {
        return new Function("promise", "holder", "                           \n\
            'use strict';                                                    \n\
            holder.pIndex = promise;                                         \n\
            ".replace(/Index/g, i));
    };
    var generateHolderClass = function(total) {
        var props = new Array(total);
        for (var i = 0; i < props.length; ++i) {
            props[i] = "this.p" + (i+1);
        }
        var assignment = props.join(" = ") + " = null;";
        var cancellationCode= "var promise;\n" + props.map(function(prop) {
            return "                                                         \n\
                promise = " + prop + ";                                      \n\
                if (promise instanceof Promise) {                            \n\
                    promise.cancel();                                        \n\
                }                                                            \n\
            ";
        }).join("\n");
        var passedArguments = props.join(", ");
        var name = "Holder$" + total;
        var code = "return function(tryCatch, errorObj, Promise, async) {    \n\
            'use strict';                                                    \n\
            function [TheName](fn) {                                         \n\
                [TheProperties]                                              \n\
                this.fn = fn;                                                \n\
                this.asyncNeeded = true;                                     \n\
                this.now = 0;                                                \n\
            }                                                                \n\
                                                                             \n\
            [TheName].prototype._callFunction = function(promise) {          \n\
                promise._pushContext();                                      \n\
                var ret = tryCatch(this.fn)([ThePassedArguments]);           \n\
                promise._popContext();                                       \n\
                if (ret === errorObj) {                                      \n\
                    promise._rejectCallback(ret.e, false);                   \n\
                } else {                                                     \n\
                    promise._resolveCallback(ret);                           \n\
                }                                                            \n\
            };                                                               \n\
                                                                             \n\
            [TheName].prototype.checkFulfillment = function(promise) {       \n\
                var now = ++this.now;                                        \n\
                if (now === [TheTotal]) {                                    \n\
                    if (this.asyncNeeded) {                                  \n\
                        async.invoke(this._callFunction, this, promise);     \n\
                    } else {                                                 \n\
                        this._callFunction(promise);                         \n\
                    }                                                        \n\
                                                                             \n\
                }                                                            \n\
            };                                                               \n\
                                                                             \n\
            [TheName].prototype._resultCancelled = function() {              \n\
                [CancellationCode]                                           \n\
            };                                                               \n\
                                                                             \n\
            return [TheName];                                                \n\
        }(tryCatch, errorObj, Promise, async);                               \n\
        ";
        code = code.replace(/\[TheName\]/g, name)
            .replace(/\[TheTotal\]/g, total)
            .replace(/\[ThePassedArguments\]/g, passedArguments)
            .replace(/\[TheProperties\]/g, assignment)
            .replace(/\[CancellationCode\]/g, cancellationCode);
        return new Function("tryCatch", "errorObj", "Promise", "async", code)
                           (tryCatch, errorObj, Promise, async);
    };
    var holderClasses = [];
    var thenCallbacks = [];
    var promiseSetters = [];
    for (var i = 0; i < 8; ++i) {
        holderClasses.push(generateHolderClass(i + 1));
        thenCallbacks.push(thenCallback(i + 1));
        promiseSetters.push(promiseSetter(i + 1));
    }
    reject = function (reason) {
        this._reject(reason);
    };
}}
Promise.join = function () {
    var last = arguments.length - 1;
    var fn;
    if (last > 0 && typeof arguments[last] === "function") {
        fn = arguments[last];
        if (!false) {
            if (last <= 8 && canEvaluate) {
                var ret = new Promise(INTERNAL);
                ret._captureStackTrace();
                var HolderClass = holderClasses[last - 1];
                var holder = new HolderClass(fn);
                var callbacks = thenCallbacks;
                for (var i = 0; i < last; ++i) {
                    var maybePromise = tryConvertToPromise(arguments[i], ret);
                    if (maybePromise instanceof Promise) {
                        maybePromise = maybePromise._target();
                        var bitField = maybePromise._bitField;
                        ;
                        if (((bitField & 50397184) === 0)) {
                            maybePromise._then(callbacks[i], reject,
                                               undefined, ret, holder);
                            promiseSetters[i](maybePromise, holder);
                            holder.asyncNeeded = false;
                        } else if (((bitField & 33554432) !== 0)) {
                            callbacks[i].call(ret,
                                              maybePromise._value(), holder);
                        } else if (((bitField & 16777216) !== 0)) {
                            ret._reject(maybePromise._reason());
                        } else {
                            ret._cancel();
                        }
                    } else {
                        callbacks[i].call(ret, maybePromise, holder);
                    }
                }
                if (!ret._isFateSealed()) {
                    if (holder.asyncNeeded) {
                        var domain = getDomain();
                        if (domain !== null) {
                            holder.fn = util.domainBind(domain, holder.fn);
                        }
                    }
                    ret._setAsyncGuaranteed();
                    ret._setOnCancel(holder);
                }
                return ret;
            }
        }
    }
    var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
    if (fn) args.pop();
    var ret = new PromiseArray(args).promise();
    return fn !== undefined ? ret.spread(fn) : ret;
};
};

+ 168 - 0
src/server/node_modules/bluebird/js/release/map.js

@ -0,0 +1,168 @@
"use strict";
module.exports = function(Promise,
                          PromiseArray,
                          apiRejection,
                          tryConvertToPromise,
                          INTERNAL,
                          debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
    this.constructor$(promises);
    this._promise._captureStackTrace();
    var domain = getDomain();
    this._callback = domain === null ? fn : util.domainBind(domain, fn);
    this._preservedValues = _filter === INTERNAL
        ? new Array(this.length())
        : null;
    this._limit = limit;
    this._inFlight = 0;
    this._queue = [];
    async.invoke(this._asyncInit, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function() {
    this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
    var values = this._values;
    var length = this.length();
    var preservedValues = this._preservedValues;
    var limit = this._limit;
    if (index < 0) {
        index = (index * -1) - 1;
        values[index] = value;
        if (limit >= 1) {
            this._inFlight--;
            this._drainQueue();
            if (this._isResolved()) return true;
        }
    } else {
        if (limit >= 1 && this._inFlight >= limit) {
            values[index] = value;
            this._queue.push(index);
            return false;
        }
        if (preservedValues !== null) preservedValues[index] = value;
        var promise = this._promise;
        var callback = this._callback;
        var receiver = promise._boundValue();
        promise._pushContext();
        var ret = tryCatch(callback).call(receiver, value, index, length);
        var promiseCreated = promise._popContext();
        debug.checkForgottenReturns(
            ret,
            promiseCreated,
            preservedValues !== null ? "Promise.filter" : "Promise.map",
            promise
        );
        if (ret === errorObj) {
            this._reject(ret.e);
            return true;
        }
        var maybePromise = tryConvertToPromise(ret, this._promise);
        if (maybePromise instanceof Promise) {
            maybePromise = maybePromise._target();
            var bitField = maybePromise._bitField;
            ;
            if (((bitField & 50397184) === 0)) {
                if (limit >= 1) this._inFlight++;
                values[index] = maybePromise;
                maybePromise._proxy(this, (index + 1) * -1);
                return false;
            } else if (((bitField & 33554432) !== 0)) {
                ret = maybePromise._value();
            } else if (((bitField & 16777216) !== 0)) {
                this._reject(maybePromise._reason());
                return true;
            } else {
                this._cancel();
                return true;
            }
        }
        values[index] = ret;
    }
    var totalResolved = ++this._totalResolved;
    if (totalResolved >= length) {
        if (preservedValues !== null) {
            this._filter(values, preservedValues);
        } else {
            this._resolve(values);
        }
        return true;
    }
    return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
    var queue = this._queue;
    var limit = this._limit;
    var values = this._values;
    while (queue.length > 0 && this._inFlight < limit) {
        if (this._isResolved()) return;
        var index = queue.pop();
        this._promiseFulfilled(values[index], index);
    }
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
    var len = values.length;
    var ret = new Array(len);
    var j = 0;
    for (var i = 0; i < len; ++i) {
        if (booleans[i]) ret[j++] = values[i];
    }
    ret.length = j;
    this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
    return this._preservedValues;
};
function map(promises, fn, options, _filter) {
    if (typeof fn !== "function") {
        return apiRejection("expecting a function but got " + util.classString(fn));
    }
    var limit = 0;
    if (options !== undefined) {
        if (typeof options === "object" && options !== null) {
            if (typeof options.concurrency !== "number") {
                return Promise.reject(
                    new TypeError("'concurrency' must be a number but it is " +
                                    util.classString(options.concurrency)));
            }
            limit = options.concurrency;
        } else {
            return Promise.reject(new TypeError(
                            "options argument must be an object but it is " +
                             util.classString(options)));
        }
    }
    limit = typeof limit === "number" &&
        isFinite(limit) && limit >= 1 ? limit : 0;
    return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
    return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
    return map(promises, fn, options, _filter);
};
};

+ 55 - 0
src/server/node_modules/bluebird/js/release/method.js

@ -0,0 +1,55 @@
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
    if (typeof fn !== "function") {
        throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
    }
    return function () {
        var ret = new Promise(INTERNAL);
        ret._captureStackTrace();
        ret._pushContext();
        var value = tryCatch(fn).apply(this, arguments);
        var promiseCreated = ret._popContext();
        debug.checkForgottenReturns(
            value, promiseCreated, "Promise.method", ret);
        ret._resolveFromSyncValue(value);
        return ret;
    };
};
Promise.attempt = Promise["try"] = function (fn) {
    if (typeof fn !== "function") {
        return apiRejection("expecting a function but got " + util.classString(fn));
    }
    var ret = new Promise(INTERNAL);
    ret._captureStackTrace();
    ret._pushContext();
    var value;
    if (arguments.length > 1) {
        debug.deprecated("calling Promise.try with more than 1 argument");
        var arg = arguments[1];
        var ctx = arguments[2];
        value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
                                  : tryCatch(fn).call(ctx, arg);
    } else {
        value = tryCatch(fn)();
    }
    var promiseCreated = ret._popContext();
    debug.checkForgottenReturns(
        value, promiseCreated, "Promise.try", ret);
    ret._resolveFromSyncValue(value);
    return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
    if (value === util.errorObj) {
        this._rejectCallback(value.e, false);
    } else {
        this._resolveCallback(value, true);
    }
};
};

+ 51 - 0
src/server/node_modules/bluebird/js/release/nodeback.js

@ -0,0 +1,51 @@
"use strict";
var util = require("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = require("./errors");
var OperationalError = errors.OperationalError;
var es5 = require("./es5");
function isUntypedError(obj) {
    return obj instanceof Error &&
        es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
    var ret;
    if (isUntypedError(obj)) {
        ret = new OperationalError(obj);
        ret.name = obj.name;
        ret.message = obj.message;
        ret.stack = obj.stack;
        var keys = es5.keys(obj);
        for (var i = 0; i < keys.length; ++i) {
            var key = keys[i];
            if (!rErrorKey.test(key)) {
                ret[key] = obj[key];
            }
        }
        return ret;
    }
    util.markAsOriginatingFromRejection(obj);
    return obj;
}
function nodebackForPromise(promise, multiArgs) {
    return function(err, value) {
        if (promise === null) return;
        if (err) {
            var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
            promise._attachExtraTrace(wrapped);
            promise._reject(wrapped);
        } else if (!multiArgs) {
            promise._fulfill(value);
        } else {
            var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
            promise._fulfill(args);
        }
        promise = null;
    };
}
module.exports = nodebackForPromise;

+ 58 - 0
src/server/node_modules/bluebird/js/release/nodeify.js

@ -0,0 +1,58 @@
"use strict";
module.exports = function(Promise) {
var util = require("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
    var promise = this;
    if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
    var ret =
        tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
    if (ret === errorObj) {
        async.throwLater(ret.e);
    }
}
function successAdapter(val, nodeback) {
    var promise = this;
    var receiver = promise._boundValue();
    var ret = val === undefined
        ? tryCatch(nodeback).call(receiver, null)
        : tryCatch(nodeback).call(receiver, null, val);
    if (ret === errorObj) {
        async.throwLater(ret.e);
    }
}
function errorAdapter(reason, nodeback) {
    var promise = this;
    if (!reason) {
        var newReason = new Error(reason + "");
        newReason.cause = reason;
        reason = newReason;
    }
    var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
    if (ret === errorObj) {
        async.throwLater(ret.e);
    }
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
                                                                     options) {
    if (typeof nodeback == "function") {
        var adapter = successAdapter;
        if (options !== undefined && Object(options).spread) {
            adapter = spreadAdapter;
        }
        this._then(
            adapter,
            errorAdapter,
            undefined,
            this,
            nodeback
        );
    }
    return this;
};
};

+ 773 - 0
src/server/node_modules/bluebird/js/release/promise.js

@ -0,0 +1,773 @@
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
    return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
    return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
    return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
if (util.isNode) {
    getDomain = function() {
        var ret = process.domain;
        if (ret === undefined) ret = null;
        return ret;
    };
} else {
    getDomain = function() {
        return null;
    };
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
    require("./promise_array")(Promise, INTERNAL,
                               tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
 /*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
    require("./finally")(Promise, tryConvertToPromise);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
    if (typeof executor !== "function") {
        throw new TypeError("expecting a function but got " + util.classString(executor));
    }
    if (self.constructor !== Promise) {
        throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
}
function Promise(executor) {
    this._bitField = 0;
    this._fulfillmentHandler0 = undefined;
    this._rejectionHandler0 = undefined;
    this._promise0 = undefined;
    this._receiver0 = undefined;
    if (executor !== INTERNAL) {
        check(this, executor);
        this._resolveFromExecutor(executor);
    }
    this._promiseCreated();
    this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
    return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
    var len = arguments.length;
    if (len > 1) {
        var catchInstances = new Array(len - 1),
            j = 0, i;
        for (i = 0; i < len - 1; ++i) {
            var item = arguments[i];
            if (util.isObject(item)) {
                catchInstances[j++] = item;
            } else {
                return apiRejection("expecting an object but got " +
                    "A catch statement predicate " + util.classString(item));
            }
        }
        catchInstances.length = j;
        fn = arguments[i];
        return this.then(undefined, catchFilter(catchInstances, fn, this));
    }
    return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
    return this._then(reflectHandler,
        reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
    if (debug.warnings() && arguments.length > 0 &&
        typeof didFulfill !== "function" &&
        typeof didReject !== "function") {
        var msg = ".then() only accepts functions but was passed: " +
                util.classString(didFulfill);
        if (arguments.length > 1) {
            msg += ", " + util.classString(didReject);
        }
        this._warn(msg);
    }
    return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
    var promise =
        this._then(didFulfill, didReject, undefined, undefined, undefined);
    promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
    if (typeof fn !== "function") {
        return apiRejection("expecting a function but got " + util.classString(fn));
    }
    return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
    var ret = {
        isFulfilled: false,
        isRejected: false,
        fulfillmentValue: undefined,
        rejectionReason: undefined
    };
    if (this.isFulfilled()) {
        ret.fulfillmentValue = this.value();
        ret.isFulfilled = true;
    } else if (this.isRejected()) {
        ret.rejectionReason = this.reason();
        ret.isRejected = true;
    }
    return ret;
};
Promise.prototype.all = function () {
    if (arguments.length > 0) {
        this._warn(".all() was passed arguments but it does not take any");
    }
    return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
    return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
    return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
    var ret = new Promise(INTERNAL);
    ret._captureStackTrace();
    var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
                                         : false;
    var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
    if (result === errorObj) {
        ret._rejectCallback(result.e, true);
    }
    if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
    return ret;
};
Promise.all = function (promises) {
    return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
    var ret = tryConvertToPromise(obj);
    if (!(ret instanceof Promise)) {
        ret = new Promise(INTERNAL);
        ret._captureStackTrace();
        ret._setFulfilled();
        ret._rejectionHandler0 = obj;
    }
    return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
    var ret = new Promise(INTERNAL);
    ret._captureStackTrace();
    ret._rejectCallback(reason, true);
    return ret;
};
Promise.setScheduler = function(fn) {
    if (typeof fn !== "function") {
        throw new TypeError("expecting a function but got " + util.classString(fn));
    }
    return async.setScheduler(fn);
};
Promise.prototype._then = function (
    didFulfill,
    didReject,
    _,    receiver,
    internalData
) {
    var haveInternalData = internalData !== undefined;
    var promise = haveInternalData ? internalData : new Promise(INTERNAL);
    var target = this._target();
    var bitField = target._bitField;
    if (!haveInternalData) {
        promise._propagateFrom(this, 3);
        promise._captureStackTrace();
        if (receiver === undefined &&
            ((this._bitField & 2097152) !== 0)) {
            if (!((bitField & 50397184) === 0)) {
                receiver = this._boundValue();
            } else {
                receiver = target === this ? undefined : this._boundTo;
            }
        }
        this._fireEvent("promiseChained", this, promise);
    }
    var domain = getDomain();
    if (!((bitField & 50397184) === 0)) {
        var handler, value, settler = target._settlePromiseCtx;
        if (((bitField & 33554432) !== 0)) {
            value = target._rejectionHandler0;
            handler = didFulfill;
        } else if (((bitField & 16777216) !== 0)) {
            value = target._fulfillmentHandler0;
            handler = didReject;
            target._unsetRejectionIsUnhandled();
        } else {
            settler = target._settlePromiseLateCancellationObserver;
            value = new CancellationError("late cancellation observer");
            target._attachExtraTrace(value);
            handler = didReject;
        }
        async.invoke(settler, target, {
            handler: domain === null ? handler
                : (typeof handler === "function" &&
                    util.domainBind(domain, handler)),
            promise: promise,
            receiver: receiver,
            value: value
        });
    } else {
        target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
    }
    return promise;
};
Promise.prototype._length = function () {
    return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
    return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
    return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
    this._bitField = (this._bitField & -65536) |
        (len & 65535);
};
Promise.prototype._setFulfilled = function () {
    this._bitField = this._bitField | 33554432;
    this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
    this._bitField = this._bitField | 16777216;
    this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
    this._bitField = this._bitField | 67108864;
    this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
    this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
    return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
    this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
    this._bitField = this._bitField | 65536;
    this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function() {
    this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function() {
    if (async.hasCustomScheduler()) return;
    this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
    var ret = index === 0 ? this._receiver0 : this[
            index * 4 - 4 + 3];
    if (ret === UNDEFINED_BINDING) {
        return undefined;
    } else if (ret === undefined && this._isBound()) {
        return this._boundValue();
    }
    return ret;
};
Promise.prototype._promiseAt = function (index) {
    return this[
            index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
    return this[
            index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
    return this[
            index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
    var bitField = follower._bitField;
    var fulfill = follower._fulfillmentHandler0;
    var reject = follower._rejectionHandler0;
    var promise = follower._promise0;
    var receiver = follower._receiverAt(0);
    if (receiver === undefined) receiver = UNDEFINED_BINDING;
    this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
    var fulfill = follower._fulfillmentHandlerAt(index);
    var reject = follower._rejectionHandlerAt(index);
    var promise = follower._promiseAt(index);
    var receiver = follower._receiverAt(index);
    if (receiver === undefined) receiver = UNDEFINED_BINDING;
    this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
    fulfill,
    reject,
    promise,
    receiver,
    domain
) {
    var index = this._length();
    if (index >= 65535 - 4) {
        index = 0;
        this._setLength(0);
    }
    if (index === 0) {
        this._promise0 = promise;
        this._receiver0 = receiver;
        if (typeof fulfill === "function") {
            this._fulfillmentHandler0 =
                domain === null ? fulfill : util.domainBind(domain, fulfill);
        }
        if (typeof reject === "function") {
            this._rejectionHandler0 =
                domain === null ? reject : util.domainBind(domain, reject);
        }
    } else {
        var base = index * 4 - 4;
        this[base + 2] = promise;
        this[base + 3] = receiver;
        if (typeof fulfill === "function") {
            this[base + 0] =
                domain === null ? fulfill : util.domainBind(domain, fulfill);
        }
        if (typeof reject === "function") {
            this[base + 1] =
                domain === null ? reject : util.domainBind(domain, reject);
        }
    }
    this._setLength(index + 1);
    return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
    this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
    if (((this._bitField & 117506048) !== 0)) return;
    if (value === this)
        return this._rejectCallback(makeSelfResolutionError(), false);
    var maybePromise = tryConvertToPromise(value, this);
    if (!(maybePromise instanceof Promise)) return this._fulfill(value);
    if (shouldBind) this._propagateFrom(maybePromise, 2);
    var promise = maybePromise._target();
    if (promise === this) {
        this._reject(makeSelfResolutionError());
        return;
    }
    var bitField = promise._bitField;
    if (((bitField & 50397184) === 0)) {
        var len = this._length();
        if (len > 0) promise._migrateCallback0(this);
        for (var i = 1; i < len; ++i) {
            promise._migrateCallbackAt(this, i);
        }
        this._setFollowing();
        this._setLength(0);
        this._setFollowee(promise);
    } else if (((bitField & 33554432) !== 0)) {
        this._fulfill(promise._value());
    } else if (((bitField & 16777216) !== 0)) {
        this._reject(promise._reason());
    } else {
        var reason = new CancellationError("late cancellation observer");
        promise._attachExtraTrace(reason);
        this._reject(reason);
    }
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
    var trace = util.ensureErrorObject(reason);
    var hasStack = trace === reason;
    if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
        var message = "a promise was rejected with a non-error: " +
            util.classString(reason);
        this._warn(message, true);
    }
    this._attachExtraTrace(trace, synchronous ? hasStack : false);
    this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
    var promise = this;
    this._captureStackTrace();
    this._pushContext();
    var synchronous = true;
    var r = this._execute(executor, function(value) {
        promise._resolveCallback(value);
    }, function (reason) {
        promise._rejectCallback(reason, synchronous);
    });
    synchronous = false;
    this._popContext();
    if (r !== undefined) {
        promise._rejectCallback(r, true);
    }
};
Promise.prototype._settlePromiseFromHandler = function (
    handler, receiver, value, promise
) {
    var bitField = promise._bitField;
    if (((bitField & 65536) !== 0)) return;
    promise._pushContext();
    var x;
    if (receiver === APPLY) {
        if (!value || typeof value.length !== "number") {
            x = errorObj;
            x.e = new TypeError("cannot .spread() a non-array: " +
                                    util.classString(value));
        } else {
            x = tryCatch(handler).apply(this._boundValue(), value);
        }
    } else {
        x = tryCatch(handler).call(receiver, value);
    }
    var promiseCreated = promise._popContext();
    bitField = promise._bitField;
    if (((bitField & 65536) !== 0)) return;
    if (x === NEXT_FILTER) {
        promise._reject(value);
    } else if (x === errorObj) {
        promise._rejectCallback(x.e, false);
    } else {
        debug.checkForgottenReturns(x, promiseCreated, "",  promise, this);
        promise._resolveCallback(x);
    }
};
Promise.prototype._target = function() {
    var ret = this;
    while (ret._isFollowing()) ret = ret._followee();
    return ret;
};
Promise.prototype._followee = function() {
    return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
    this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
    var isPromise = promise instanceof Promise;
    var bitField = this._bitField;
    var asyncGuaranteed = ((bitField & 134217728) !== 0);
    if (((bitField & 65536) !== 0)) {
        if (isPromise) promise._invokeInternalOnCancel();
        if (receiver instanceof PassThroughHandlerContext &&
            receiver.isFinallyHandler()) {
            receiver.cancelPromise = promise;
            if (tryCatch(handler).call(receiver, value) === errorObj) {
                promise._reject(errorObj.e);
            }
        } else if (handler === reflectHandler) {
            promise._fulfill(reflectHandler.call(receiver));
        } else if (receiver instanceof Proxyable) {
            receiver._promiseCancelled(promise);
        } else if (isPromise || promise instanceof PromiseArray) {
            promise._cancel();
        } else {
            receiver.cancel();
        }
    } else if (typeof handler === "function") {
        if (!isPromise) {
            handler.call(receiver, value, promise);
        } else {
            if (asyncGuaranteed) promise._setAsyncGuaranteed();
            this._settlePromiseFromHandler(handler, receiver, value, promise);
        }
    } else if (receiver instanceof Proxyable) {
        if (!receiver._isResolved()) {
            if (((bitField & 33554432) !== 0)) {
                receiver._promiseFulfilled(value, promise);
            } else {
                receiver._promiseRejected(value, promise);
            }
        }
    } else if (isPromise) {
        if (asyncGuaranteed) promise._setAsyncGuaranteed();
        if (((bitField & 33554432) !== 0)) {
            promise._fulfill(value);
        } else {
            promise._reject(value);
        }
    }
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
    var handler = ctx.handler;
    var promise = ctx.promise;
    var receiver = ctx.receiver;
    var value = ctx.value;
    if (typeof handler === "function") {
        if (!(promise instanceof Promise)) {
            handler.call(receiver, value, promise);
        } else {
            this._settlePromiseFromHandler(handler, receiver, value, promise);
        }
    } else if (promise instanceof Promise) {
        promise._reject(value);
    }
};
Promise.prototype._settlePromiseCtx = function(ctx) {
    this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
    var promise = this._promise0;
    var receiver = this._receiverAt(0);
    this._promise0 = undefined;
    this._receiver0 = undefined;
    this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
    var base = index * 4 - 4;
    this[base + 2] =
    this[base + 3] =
    this[base + 0] =
    this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
    var bitField = this._bitField;
    if (((bitField & 117506048) >>> 16)) return;
    if (value === this) {
        var err = makeSelfResolutionError();
        this._attachExtraTrace(err);
        return this._reject(err);
    }
    this._setFulfilled();
    this._rejectionHandler0 = value;
    if ((bitField & 65535) > 0) {
        if (((bitField & 134217728) !== 0)) {
            this._settlePromises();
        } else {
            async.settlePromises(this);
        }
    }
};
Promise.prototype._reject = function (reason) {
    var bitField = this._bitField;
    if (((bitField & 117506048) >>> 16)) return;
    this._setRejected();
    this._fulfillmentHandler0 = reason;
    if (this._isFinal()) {
        return async.fatalError(reason, util.isNode);
    }
    if ((bitField & 65535) > 0) {
        async.settlePromises(this);
    } else {
        this._ensurePossibleRejectionHandled();
    }
};
Promise.prototype._fulfillPromises = function (len, value) {
    for (var i = 1; i < len; i++) {
        var handler = this._fulfillmentHandlerAt(i);
        var promise = this._promiseAt(i);
        var receiver = this._receiverAt(i);
        this._clearCallbackDataAtIndex(i);
        this._settlePromise(promise, handler, receiver, value);
    }
};
Promise.prototype._rejectPromises = function (len, reason) {
    for (var i = 1; i < len; i++) {
        var handler = this._rejectionHandlerAt(i);
        var promise = this._promiseAt(i);
        var receiver = this._receiverAt(i);
        this._clearCallbackDataAtIndex(i);
        this._settlePromise(promise, handler, receiver, reason);
    }
};
Promise.prototype._settlePromises = function () {
    var bitField = this._bitField;
    var len = (bitField & 65535);
    if (len > 0) {
        if (((bitField & 16842752) !== 0)) {
            var reason = this._fulfillmentHandler0;
            this._settlePromise0(this._rejectionHandler0, reason, bitField);
            this._rejectPromises(len, reason);
        } else {
            var value = this._rejectionHandler0;
            this._settlePromise0(this._fulfillmentHandler0, value, bitField);
            this._fulfillPromises(len, value);
        }
        this._setLength(0);
    }
    this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
    var bitField = this._bitField;
    if (((bitField & 33554432) !== 0)) {
        return this._rejectionHandler0;
    } else if (((bitField & 16777216) !== 0)) {
        return this._fulfillmentHandler0;
    }
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
    debug.deprecated("Promise.defer", "new Promise");
    var promise = new Promise(INTERNAL);
    return {
        promise: promise,
        resolve: deferResolve,
        reject: deferReject
    };
};
util.notEnumerableProp(Promise,
                       "_makeSelfResolutionError",
                       makeSelfResolutionError);
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
    debug);
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
    Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.4.6";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./any.js')(Promise);
                                                         
    util.toFastProperties(Promise);                                          
    util.toFastProperties(Promise.prototype);                                
    function fillTypes(value) {                                              
        var p = new Promise(INTERNAL);                                       
        p._fulfillmentHandler0 = value;                                      
        p._rejectionHandler0 = value;                                        
        p._promise0 = value;                                                 
        p._receiver0 = value;                                                
    }                                                                        
    // Complete slack tracking, opt out of field-type tracking and           
    // stabilize map                                                         
    fillTypes({a: 1});                                                       
    fillTypes({b: 2});                                                       
    fillTypes({c: 3});                                                       
    fillTypes(1);                                                            
    fillTypes(function(){});                                                 
    fillTypes(undefined);                                                    
    fillTypes(false);                                                        
    fillTypes(new Promise(INTERNAL));                                        
    debug.setBounds(Async.firstLineError, util.lastLineError);               
    return Promise;                                                          
};

+ 184 - 0
src/server/node_modules/bluebird/js/release/promise_array.js

@ -0,0 +1,184 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
    apiRejection, Proxyable) {
var util = require("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
    switch(val) {
    case -2: return [];
    case -3: return {};
    }
}
function PromiseArray(values) {
    var promise = this._promise = new Promise(INTERNAL);
    if (values instanceof Promise) {
        promise._propagateFrom(values, 3);
    }
    promise._setOnCancel(this);
    this._values = values;
    this._length = 0;
    this._totalResolved = 0;
    this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
    return this._length;
};
PromiseArray.prototype.promise = function () {
    return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
    var values = tryConvertToPromise(this._values, this._promise);
    if (values instanceof Promise) {
        values = values._target();
        var bitField = values._bitField;
        ;
        this._values = values;
        if (((bitField & 50397184) === 0)) {
            this._promise._setAsyncGuaranteed();
            return values._then(
                init,
                this._reject,
                undefined,
                this,
                resolveValueIfEmpty
           );
        } else if (((bitField & 33554432) !== 0)) {
            values = values._value();
        } else if (((bitField & 16777216) !== 0)) {
            return this._reject(values._reason());
        } else {
            return this._cancel();
        }
    }
    values = util.asArray(values);
    if (values === null) {
        var err = apiRejection(
            "expecting an array or an iterable object but got " + util.classString(values)).reason();
        this._promise._rejectCallback(err, false);
        return;
    }
    if (values.length === 0) {
        if (resolveValueIfEmpty === -5) {
            this._resolveEmptyArray();
        }
        else {
            this._resolve(toResolutionValue(resolveValueIfEmpty));
        }
        return;
    }
    this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
    var len = this.getActualLength(values.length);
    this._length = len;
    this._values = this.shouldCopyValues() ? new Array(len) : this._values;
    var result = this._promise;
    var isResolved = false;
    var bitField = null;
    for (var i = 0; i < len; ++i) {
        var maybePromise = tryConvertToPromise(values[i], result);
        if (maybePromise instanceof Promise) {
            maybePromise = maybePromise._target();
            bitField = maybePromise._bitField;
        } else {
            bitField = null;
        }
        if (isResolved) {
            if (bitField !== null) {
                maybePromise.suppressUnhandledRejections();
            }
        } else if (bitField !== null) {
            if (((bitField & 50397184) === 0)) {
                maybePromise._proxy(this, i);
                this._values[i] = maybePromise;
            } else if (((bitField & 33554432) !== 0)) {
                isResolved = this._promiseFulfilled(maybePromise._value(), i);
            } else if (((bitField & 16777216) !== 0)) {
                isResolved = this._promiseRejected(maybePromise._reason(), i);
            } else {
                isResolved = this._promiseCancelled(i);
            }
        } else {
            isResolved = this._promiseFulfilled(maybePromise, i);
        }
    }
    if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
    return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
    this._values = null;
    this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
    if (this._isResolved() || !this._promise._isCancellable()) return;
    this._values = null;
    this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
    this._values = null;
    this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
    this._values[index] = value;
    var totalResolved = ++this._totalResolved;
    if (totalResolved >= this._length) {
        this._resolve(this._values);
        return true;
    }
    return false;
};
PromiseArray.prototype._promiseCancelled = function() {
    this._cancel();
    return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
    this._totalResolved++;
    this._reject(reason);
    return true;
};
PromiseArray.prototype._resultCancelled = function() {
    if (this._isResolved()) return;
    var values = this._values;
    this._cancel();
    if (values instanceof Promise) {
        values.cancel();
    } else {
        for (var i = 0; i < values.length; ++i) {
            if (values[i] instanceof Promise) {
                values[i].cancel();
            }
        }
    }
};
PromiseArray.prototype.shouldCopyValues = function () {
    return true;
};
PromiseArray.prototype.getActualLength = function (len) {
    return len;
};
return PromiseArray;
};

+ 314 - 0
src/server/node_modules/bluebird/js/release/promisify.js

@ -0,0 +1,314 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = require("./util");
var nodebackForPromise = require("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = require("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
    "arity",    "length",
    "name",
    "arguments",
    "caller",
    "callee",
    "prototype",
    "__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
    return util.isIdentifier(name) &&
        name.charAt(0) !== "_" &&
        name !== "constructor";
};
function propsFilter(key) {
    return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
    try {
        return fn.__isPromisified__ === true;
    }
    catch (e) {
        return false;
    }
}
function hasPromisified(obj, key, suffix) {
    var val = util.getDataPropertyOrDefault(obj, key + suffix,
                                            defaultPromisified);
    return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
    for (var i = 0; i < ret.length; i += 2) {
        var key = ret[i];
        if (suffixRegexp.test(key)) {
            var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
            for (var j = 0; j < ret.length; j += 2) {
                if (ret[j] === keyWithoutAsyncSuffix) {
                    throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a    See http://goo.gl/MqrFmX\u000a"
                        .replace("%s", suffix));
                }
            }
        }
    }
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
    var keys = util.inheritedDataKeys(obj);
    var ret = [];
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var value = obj[key];
        var passesDefaultFilter = filter === defaultFilter
            ? true : defaultFilter(key, value, obj);
        if (typeof value === "function" &&
            !isPromisified(value) &&
            !hasPromisified(obj, key, suffix) &&
            filter(key, value, obj, passesDefaultFilter)) {
            ret.push(key, value);
        }
    }
    checkValid(ret, suffix, suffixRegexp);
    return ret;
}
var escapeIdentRegex = function(str) {
    return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!false) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
    var ret = [likelyArgumentCount];
    var min = Math.max(0, likelyArgumentCount - 1 - 3);
    for(var i = likelyArgumentCount - 1; i >= min; --i) {
        ret.push(i);
    }
    for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
        ret.push(i);
    }
    return ret;
};
var argumentSequence = function(argumentCount) {
    return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
    return util.filledRange(
        Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
    if (typeof fn.length === "number") {
        return Math.max(Math.min(fn.length, 1023 + 1), 0);
    }
    return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
    var newParameterCount = Math.max(0, parameterCount(fn) - 1);
    var argumentOrder = switchCaseArgumentOrder(newParameterCount);
    var shouldProxyThis = typeof callback === "string" || receiver === THIS;
    function generateCallForArgumentCount(count) {
        var args = argumentSequence(count).join(", ");
        var comma = count > 0 ? ", " : "";
        var ret;
        if (shouldProxyThis) {
            ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
        } else {
            ret = receiver === undefined
                ? "ret = callback({{args}}, nodeback); break;\n"
                : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
        }
        return ret.replace("{{args}}", args).replace(", ", comma);
    }
    function generateArgumentSwitchCase() {
        var ret = "";
        for (var i = 0; i < argumentOrder.length; ++i) {
            ret += "case " + argumentOrder[i] +":" +
                generateCallForArgumentCount(argumentOrder[i]);
        }
        ret += "                                                             \n\
        default:                                                             \n\
            var args = new Array(len + 1);                                   \n\
            var i = 0;                                                       \n\
            for (var i = 0; i < len; ++i) {                                  \n\
               args[i] = arguments[i];                                       \n\
            }                                                                \n\
            args[i] = nodeback;                                              \n\
            [CodeForCall]                                                    \n\
            break;                                                           \n\
        ".replace("[CodeForCall]", (shouldProxyThis
                                ? "ret = callback.apply(this, args);\n"
                                : "ret = callback.apply(receiver, args);\n"));
        return ret;
    }
    var getFunctionCode = typeof callback === "string"
                                ? ("this != null ? this['"+callback+"'] : fn")
                                : "fn";
    var body = "'use strict';                                                \n\
        var ret = function (Parameters) {                                    \n\
            'use strict';                                                    \n\
            var len = arguments.length;                                      \n\
            var promise = new Promise(INTERNAL);                             \n\
            promise._captureStackTrace();                                    \n\
            var nodeback = nodebackForPromise(promise, " + multiArgs + ");   \n\
            var ret;                                                         \n\
            var callback = tryCatch([GetFunctionCode]);                      \n\
            switch(len) {                                                    \n\
                [CodeForSwitchCase]                                          \n\
            }                                                                \n\
            if (ret === errorObj) {                                          \n\
                promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
            }                                                                \n\
            if (!promise._isFateSealed()) promise._setAsyncGuaranteed();     \n\
            return promise;                                                  \n\
        };                                                                   \n\
        notEnumerableProp(ret, '__isPromisified__', true);                   \n\
        return ret;                                                          \n\
    ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
        .replace("[GetFunctionCode]", getFunctionCode);
    body = body.replace("Parameters", parameterDeclaration(newParameterCount));
    return new Function("Promise",
                        "fn",
                        "receiver",
                        "withAppended",
                        "maybeWrapAsError",
                        "nodebackForPromise",
                        "tryCatch",
                        "errorObj",
                        "notEnumerableProp",
                        "INTERNAL",
                        body)(
                    Promise,
                    fn,
                    receiver,
                    withAppended,
                    maybeWrapAsError,
                    nodebackForPromise,
                    util.tryCatch,
                    util.errorObj,
                    util.notEnumerableProp,
                    INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
    var defaultThis = (function() {return this;})();
    var method = callback;
    if (typeof method === "string") {
        callback = fn;
    }
    function promisified() {
        var _receiver = receiver;
        if (receiver === THIS) _receiver = this;
        var promise = new Promise(INTERNAL);
        promise._captureStackTrace();
        var cb = typeof method === "string" && this !== defaultThis
            ? this[method] : callback;
        var fn = nodebackForPromise(promise, multiArgs);
        try {
            cb.apply(_receiver, withAppended(arguments, fn));
        } catch(e) {
            promise._rejectCallback(maybeWrapAsError(e), true, true);
        }
        if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
        return promise;
    }
    util.notEnumerableProp(promisified, "__isPromisified__", true);
    return promisified;
}
var makeNodePromisified = canEvaluate
    ? makeNodePromisifiedEval
    : makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
    var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
    var methods =
        promisifiableMethods(obj, suffix, suffixRegexp, filter);
    for (var i = 0, len = methods.length; i < len; i+= 2) {
        var key = methods[i];
        var fn = methods[i+1];
        var promisifiedKey = key + suffix;
        if (promisifier === makeNodePromisified) {
            obj[promisifiedKey] =
                makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
        } else {
            var promisified = promisifier(fn, function() {
                return makeNodePromisified(key, THIS, key,
                                           fn, suffix, multiArgs);
            });
            util.notEnumerableProp(promisified, "__isPromisified__", true);
            obj[promisifiedKey] = promisified;
        }
    }
    util.toFastProperties(obj);
    return obj;
}
function promisify(callback, receiver, multiArgs) {
    return makeNodePromisified(callback, receiver, undefined,
                                callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
    if (typeof fn !== "function") {
        throw new TypeError("expecting a function but got " + util.classString(fn));
    }
    if (isPromisified(fn)) {
        return fn;
    }
    options = Object(options);
    var receiver = options.context === undefined ? THIS : options.context;
    var multiArgs = !!options.multiArgs;
    var ret = promisify(fn, receiver, multiArgs);
    util.copyDescriptors(fn, ret, propsFilter);
    return ret;
};
Promise.promisifyAll = function (target, options) {
    if (typeof target !== "function" && typeof target !== "object") {
        throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    options = Object(options);
    var multiArgs = !!options.multiArgs;
    var suffix = options.suffix;
    if (typeof suffix !== "string") suffix = defaultSuffix;
    var filter = options.filter;
    if (typeof filter !== "function") filter = defaultFilter;
    var promisifier = options.promisifier;
    if (typeof promisifier !== "function") promisifier = makeNodePromisified;
    if (!util.isIdentifier(suffix)) {
        throw new RangeError("suffix must be a valid identifier\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    var keys = util.inheritedDataKeys(target);
    for (var i = 0; i < keys.length; ++i) {
        var value = target[keys[i]];
        if (keys[i] !== "constructor" &&
            util.isClass(value)) {
            promisifyAll(value.prototype, suffix, filter, promisifier,
                multiArgs);
            promisifyAll(value, suffix, filter, promisifier, multiArgs);
        }
    }
    return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};

+ 118 - 0
src/server/node_modules/bluebird/js/release/props.js

@ -0,0 +1,118 @@
"use strict";
module.exports = function(
    Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = require("./util");
var isObject = util.isObject;
var es5 = require("./es5");
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
    var index = 0;
    var size = 0;
    function extractEntry(value, key) {
        this[index] = value;
        this[index + size] = key;
        index++;
    }
    return function mapToEntries(map) {
        size = map.size;
        index = 0;
        var ret = new Array(map.size * 2);
        map.forEach(extractEntry, ret);
        return ret;
    };
})();
var entriesToMap = function(entries) {
    var ret = new Es6Map();
    var length = entries.length / 2 | 0;
    for (var i = 0; i < length; ++i) {
        var key = entries[length + i];
        var value = entries[i];
        ret.set(key, value);
    }
    return ret;
};
function PropertiesPromiseArray(obj) {
    var isMap = false;
    var entries;
    if (Es6Map !== undefined && obj instanceof Es6Map) {
        entries = mapToEntries(obj);
        isMap = true;
    } else {
        var keys = es5.keys(obj);
        var len = keys.length;
        entries = new Array(len * 2);
        for (var i = 0; i < len; ++i) {
            var key = keys[i];
            entries[i] = obj[key];
            entries[i + len] = key;
        }
    }
    this.constructor$(entries);
    this._isMap = isMap;
    this._init$(undefined, -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
    this._values[index] = value;
    var totalResolved = ++this._totalResolved;
    if (totalResolved >= this._length) {
        var val;
        if (this._isMap) {
            val = entriesToMap(this._values);
        } else {
            val = {};
            var keyOffset = this.length();
            for (var i = 0, len = this.length(); i < len; ++i) {
                val[this._values[i + keyOffset]] = this._values[i];
            }
        }
        this._resolve(val);
        return true;
    }
    return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
    return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
    return len >> 1;
};
function props(promises) {
    var ret;
    var castValue = tryConvertToPromise(promises);
    if (!isObject(castValue)) {
        return apiRejection("cannot await properties of a non-object\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    } else if (castValue instanceof Promise) {
        ret = castValue._then(
            Promise.props, undefined, undefined, undefined, undefined);
    } else {
        ret = new PropertiesPromiseArray(castValue).promise();
    }
    if (castValue instanceof Promise) {
        ret._propagateFrom(castValue, 2);
    }
    return ret;
}
Promise.prototype.props = function () {
    return props(this);
};
Promise.props = function (promises) {
    return props(promises);
};
};

+ 90 - 0
src/server/node_modules/bluebird/js/release/queue.js

@ -0,0 +1,90 @@
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
    for (var j = 0; j < len; ++j) {
        dst[j + dstIndex] = src[j + srcIndex];
        src[j + srcIndex] = void 0;
    }
}
function Queue(capacity) {
    this._capacity = capacity;
    this._length = 0;
    this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
    return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
    var length = this.length();
    this._checkCapacity(length + 1);
    var i = (this._front + length) & (this._capacity - 1);
    this[i] = arg;
    this._length = length + 1;
};
Queue.prototype._unshiftOne = function(value) {
    var capacity = this._capacity;
    this._checkCapacity(this.length() + 1);
    var front = this._front;
    var i = (((( front - 1 ) &
                    ( capacity - 1) ) ^ capacity ) - capacity );
    this[i] = value;
    this._front = i;
    this._length = this.length() + 1;
};
Queue.prototype.unshift = function(fn, receiver, arg) {
    this._unshiftOne(arg);
    this._unshiftOne(receiver);
    this._unshiftOne(fn);
};
Queue.prototype.push = function (fn, receiver, arg) {
    var length = this.length() + 3;
    if (this._willBeOverCapacity(length)) {
        this._pushOne(fn);
        this._pushOne(receiver);
        this._pushOne(arg);
        return;
    }
    var j = this._front + length - 3;
    this._checkCapacity(length);
    var wrapMask = this._capacity - 1;
    this[(j + 0) & wrapMask] = fn;
    this[(j + 1) & wrapMask] = receiver;
    this[(j + 2) & wrapMask] = arg;
    this._length = length;
};
Queue.prototype.shift = function () {
    var front = this._front,
        ret = this[front];
    this[front] = undefined;
    this._front = (front + 1) & (this._capacity - 1);
    this._length--;
    return ret;
};
Queue.prototype.length = function () {
    return this._length;
};
Queue.prototype._checkCapacity = function (size) {
    if (this._capacity < size) {
        this._resizeTo(this._capacity << 1);
    }
};
Queue.prototype._resizeTo = function (capacity) {
    var oldCapacity = this._capacity;
    this._capacity = capacity;
    var front = this._front;
    var length = this._length;
    var moveItemsCount = (front + length) & (oldCapacity - 1);
    arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;

+ 49 - 0
src/server/node_modules/bluebird/js/release/race.js

@ -0,0 +1,49 @@
"use strict";
module.exports = function(
    Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util");
var raceLater = function (promise) {
    return promise.then(function(array) {
        return race(array, promise);
    });
};
function race(promises, parent) {
    var maybePromise = tryConvertToPromise(promises);
    if (maybePromise instanceof Promise) {
        return raceLater(maybePromise);
    } else {
        promises = util.asArray(promises);
        if (promises === null)
            return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
    }
    var ret = new Promise(INTERNAL);
    if (parent !== undefined) {
        ret._propagateFrom(parent, 3);
    }
    var fulfill = ret._fulfill;
    var reject = ret._reject;
    for (var i = 0, len = promises.length; i < len; ++i) {
        var val = promises[i];
        if (val === undefined && !(i in promises)) {
            continue;
        }
        Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
    }
    return ret;
}
Promise.race = function (promises) {
    return race(promises, undefined);
};
Promise.prototype.race = function () {
    return race(this, undefined);
};
};

+ 172 - 0
src/server/node_modules/bluebird/js/release/reduce.js

@ -0,0 +1,172 @@
"use strict";
module.exports = function(Promise,
                          PromiseArray,
                          apiRejection,
                          tryConvertToPromise,
                          INTERNAL,
                          debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
    this.constructor$(promises);
    var domain = getDomain();
    this._fn = domain === null ? fn : util.domainBind(domain, fn);
    if (initialValue !== undefined) {
        initialValue = Promise.resolve(initialValue);
        initialValue._attachCancellationCallback(this);
    }
    this._initialValue = initialValue;
    this._currentCancellable = null;
    if(_each === INTERNAL) {
        this._eachValues = Array(this._length);
    } else if (_each === 0) {
        this._eachValues = null;
    } else {
        this._eachValues = undefined;
    }
    this._promise._captureStackTrace();
    this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
    if (this._eachValues !== undefined && 
        this._eachValues !== null && 
        accum !== INTERNAL) {
        this._eachValues.push(accum);
    }
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
    if (this._eachValues !== null) {
        this._eachValues.push(value);
    }
    return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
    this._resolve(this._eachValues !== undefined ? this._eachValues
                                                 : this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
    return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
    this._promise._resolveCallback(value);
    this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
    if (sender === this._initialValue) return this._cancel();
    if (this._isResolved()) return;
    this._resultCancelled$();
    if (this._currentCancellable instanceof Promise) {
        this._currentCancellable.cancel();
    }
    if (this._initialValue instanceof Promise) {
        this._initialValue.cancel();
    }
};
ReductionPromiseArray.prototype._iterate = function (values) {
    this._values = values;
    var value;
    var i;
    var length = values.length;
    if (this._initialValue !== undefined) {
        value = this._initialValue;
        i = 0;
    } else {
        value = Promise.resolve(values[0]);
        i = 1;
    }
    this._currentCancellable = value;
    if (!value.isRejected()) {
        for (; i < length; ++i) {
            var ctx = {
                accum: null,
                value: values[i],
                index: i,
                length: length,
                array: this
            };
            value = value._then(gotAccum, undefined, undefined, ctx, undefined);
        }
    }
    if (this._eachValues !== undefined) {
        value = value
            ._then(this._eachComplete, undefined, undefined, this, undefined);
    }
    value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
    return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
    return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
    if (this.isFulfilled()) {
        array._resolve(valueOrReason);
    } else {
        array._reject(valueOrReason);
    }
}
function reduce(promises, fn, initialValue, _each) {
    if (typeof fn !== "function") {
        return apiRejection("expecting a function but got " + util.classString(fn));
    }
    var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
    return array.promise();
}
function gotAccum(accum) {
    this.accum = accum;
    this.array._gotAccum(accum);
    var value = tryConvertToPromise(this.value, this.array._promise);
    if (value instanceof Promise) {
        this.array._currentCancellable = value;
        return value._then(gotValue, undefined, undefined, this, undefined);
    } else {
        return gotValue.call(this, value);
    }
}
function gotValue(value) {
    var array = this.array;
    var promise = array._promise;
    var fn = tryCatch(array._fn);
    promise._pushContext();
    var ret;
    if (array._eachValues !== undefined) {
        ret = fn.call(promise._boundValue(), value, this.index, this.length);
    } else {
        ret = fn.call(promise._boundValue(),
                              this.accum, value, this.index, this.length);
    }
    if (ret instanceof Promise) {
        array._currentCancellable = ret;
    }
    var promiseCreated = promise._popContext();
    debug.checkForgottenReturns(
        ret,
        promiseCreated,
        array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
        promise
    );
    return ret;
}
};

+ 61 - 0
src/server/node_modules/bluebird/js/release/schedule.js

@ -0,0 +1,61 @@
"use strict";
var util = require("./util");
var schedule;
var noAsyncScheduler = function() {
    throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
    var GlobalSetImmediate = global.setImmediate;
    var ProcessNextTick = process.nextTick;
    schedule = util.isRecentNode
                ? function(fn) { GlobalSetImmediate.call(global, fn); }
                : function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function" &&
           typeof NativePromise.resolve === "function") {
    var nativePromise = NativePromise.resolve();
    schedule = function(fn) {
        nativePromise.then(fn);
    };
} else if ((typeof MutationObserver !== "undefined") &&
          !(typeof window !== "undefined" &&
            window.navigator &&
            (window.navigator.standalone || window.cordova))) {
    schedule = (function() {
        var div = document.createElement("div");
        var opts = {attributes: true};
        var toggleScheduled = false;
        var div2 = document.createElement("div");
        var o2 = new MutationObserver(function() {
            div.classList.toggle("foo");
            toggleScheduled = false;
        });
        o2.observe(div2, opts);
        var scheduleToggle = function() {
            if (toggleScheduled) return;
                toggleScheduled = true;
                div2.classList.toggle("foo");
            };
            return function schedule(fn) {
            var o = new MutationObserver(function() {
                o.disconnect();
                fn();
            });
            o.observe(div, opts);
            scheduleToggle();
        };
    })();
} else if (typeof setImmediate !== "undefined") {
    schedule = function (fn) {
        setImmediate(fn);
    };
} else if (typeof setTimeout !== "undefined") {
    schedule = function (fn) {
        setTimeout(fn, 0);
    };
} else {
    schedule = noAsyncScheduler;
}
module.exports = schedule;

+ 43 - 0
src/server/node_modules/bluebird/js/release/settle.js

@ -0,0 +1,43 @@
"use strict";
module.exports =
    function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = require("./util");
function SettledPromiseArray(values) {
    this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
    this._values[index] = inspection;
    var totalResolved = ++this._totalResolved;
    if (totalResolved >= this._length) {
        this._resolve(this._values);
        return true;
    }
    return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
    var ret = new PromiseInspection();
    ret._bitField = 33554432;
    ret._settledValueField = value;
    return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
    var ret = new PromiseInspection();
    ret._bitField = 16777216;
    ret._settledValueField = reason;
    return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
    debug.deprecated(".settle()", ".reflect()");
    return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
    return Promise.settle(this);
};
};

+ 148 - 0
src/server/node_modules/bluebird/js/release/some.js

@ -0,0 +1,148 @@
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = require("./util");
var RangeError = require("./errors").RangeError;
var AggregateError = require("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
    this.constructor$(values);
    this._howMany = 0;
    this._unwrap = false;
    this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
    if (!this._initialized) {
        return;
    }
    if (this._howMany === 0) {
        this._resolve([]);
        return;
    }
    this._init$(undefined, -5);
    var isArrayResolved = isArray(this._values);
    if (!this._isResolved() &&
        isArrayResolved &&
        this._howMany > this._canPossiblyFulfill()) {
        this._reject(this._getRangeError(this.length()));
    }
};
SomePromiseArray.prototype.init = function () {
    this._initialized = true;
    this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
    this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
    return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
    this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
    this._addFulfilled(value);
    if (this._fulfilled() === this.howMany()) {
        this._values.length = this.howMany();
        if (this.howMany() === 1 && this._unwrap) {
            this._resolve(this._values[0]);
        } else {
            this._resolve(this._values);
        }
        return true;
    }
    return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
    this._addRejected(reason);
    return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
    if (this._values instanceof Promise || this._values == null) {
        return this._cancel();
    }
    this._addRejected(CANCELLATION);
    return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
    if (this.howMany() > this._canPossiblyFulfill()) {
        var e = new AggregateError();
        for (var i = this.length(); i < this._values.length; ++i) {
            if (this._values[i] !== CANCELLATION) {
                e.push(this._values[i]);
            }
        }
        if (e.length > 0) {
            this._reject(e);
        } else {
            this._cancel();
        }
        return true;
    }
    return false;
};
SomePromiseArray.prototype._fulfilled = function () {
    return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
    return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
    this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
    this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
    return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
    var message = "Input array must contain at least " +
            this._howMany + " items but contains only " + count + " items";
    return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
    this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
    if ((howMany | 0) !== howMany || howMany < 0) {
        return apiRejection("expecting a positive integer\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    var ret = new SomePromiseArray(promises);
    var promise = ret.promise();
    ret.setHowMany(howMany);
    ret.init();
    return promise;
}
Promise.some = function (promises, howMany) {
    return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
    return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};

+ 103 - 0
src/server/node_modules/bluebird/js/release/synchronous_inspection.js

@ -0,0 +1,103 @@
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
    if (promise !== undefined) {
        promise = promise._target();
        this._bitField = promise._bitField;
        this._settledValueField = promise._isFateSealed()
            ? promise._settledValue() : undefined;
    }
    else {
        this._bitField = 0;
        this._settledValueField = undefined;
    }
}
PromiseInspection.prototype._settledValue = function() {
    return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
    if (!this.isFulfilled()) {
        throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
    if (!this.isRejected()) {
        throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
    }
    return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
    return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
    return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
    return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
    return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function() {
    return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function() {
    return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function() {
    return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function() {
    return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function() {
    return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
    return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
    return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
    return isResolved.call(this._target());
};
Promise.prototype.value = function() {
    return value.call(this._target());
};
Promise.prototype.reason = function() {
    var target = this._target();
    target._unsetRejectionIsUnhandled();
    return reason.call(target);
};
Promise.prototype._value = function() {
    return this._settledValue();
};
Promise.prototype._reason = function() {
    this._unsetRejectionIsUnhandled();
    return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};

+ 86 - 0
src/server/node_modules/bluebird/js/release/thenables.js

@ -0,0 +1,86 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
    if (isObject(obj)) {
        if (obj instanceof Promise) return obj;
        var then = getThen(obj);
        if (then === errorObj) {
            if (context) context._pushContext();
            var ret = Promise.reject(then.e);
            if (context) context._popContext();
            return ret;
        } else if (typeof then === "function") {
            if (isAnyBluebirdPromise(obj)) {
                var ret = new Promise(INTERNAL);
                obj._then(
                    ret._fulfill,
                    ret._reject,
                    undefined,
                    ret,
                    null
                );
                return ret;
            }
            return doThenable(obj, then, context);
        }
    }
    return obj;
}
function doGetThen(obj) {
    return obj.then;
}
function getThen(obj) {
    try {
        return doGetThen(obj);
    } catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
    try {
        return hasProp.call(obj, "_promise0");
    } catch (e) {
        return false;
    }
}
function doThenable(x, then, context) {
    var promise = new Promise(INTERNAL);
    var ret = promise;
    if (context) context._pushContext();
    promise._captureStackTrace();
    if (context) context._popContext();
    var synchronous = true;
    var result = util.tryCatch(then).call(x, resolve, reject);
    synchronous = false;
    if (promise && result === errorObj) {
        promise._rejectCallback(result.e, true, true);
        promise = null;
    }
    function resolve(value) {
        if (!promise) return;
        promise._resolveCallback(value);
        promise = null;
    }
    function reject(reason) {
        if (!promise) return;
        promise._rejectCallback(reason, synchronous, true);
        promise = null;
    }
    return ret;
}
return tryConvertToPromise;
};

+ 93 - 0
src/server/node_modules/bluebird/js/release/timers.js

@ -0,0 +1,93 @@
"use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle)  {
    this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function() {
    clearTimeout(this.handle);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
    var ret;
    var handle;
    if (value !== undefined) {
        ret = Promise.resolve(value)
                ._then(afterValue, null, null, ms, undefined);
        if (debug.cancellation() && value instanceof Promise) {
            ret._setOnCancel(value);
        }
    } else {
        ret = new Promise(INTERNAL);
        handle = setTimeout(function() { ret._fulfill(); }, +ms);
        if (debug.cancellation()) {
            ret._setOnCancel(new HandleWrapper(handle));
        }
        ret._captureStackTrace();
    }
    ret._setAsyncGuaranteed();
    return ret;
};
Promise.prototype.delay = function (ms) {
    return delay(ms, this);
};
var afterTimeout = function (promise, message, parent) {
    var err;
    if (typeof message !== "string") {
        if (message instanceof Error) {
            err = message;
        } else {
            err = new TimeoutError("operation timed out");
        }
    } else {
        err = new TimeoutError(message);
    }
    util.markAsOriginatingFromRejection(err);
    promise._attachExtraTrace(err);
    promise._reject(err);
    if (parent != null) {
        parent.cancel();
    }
};
function successClear(value) {
    clearTimeout(this.handle);
    return value;
}
function failureClear(reason) {
    clearTimeout(this.handle);
    throw reason;
}
Promise.prototype.timeout = function (ms, message) {
    ms = +ms;
    var ret, parent;
    var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
        if (ret.isPending()) {
            afterTimeout(ret, message, parent);
        }
    }, ms));
    if (debug.cancellation()) {
        parent = this.then();
        ret = parent._then(successClear, failureClear,
                            undefined, handleWrapper, undefined);
        ret._setOnCancel(handleWrapper);
    } else {
        ret = this._then(successClear, failureClear,
                            undefined, handleWrapper, undefined);
    }
    return ret;
};
};

+ 226 - 0
src/server/node_modules/bluebird/js/release/using.js

@ -0,0 +1,226 @@
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
    createContext, INTERNAL, debug) {
    var util = require("./util");
    var TypeError = require("./errors").TypeError;
    var inherits = require("./util").inherits;
    var errorObj = util.errorObj;
    var tryCatch = util.tryCatch;
    var NULL = {};
    function thrower(e) {
        setTimeout(function(){throw e;}, 0);
    }
    function castPreservingDisposable(thenable) {
        var maybePromise = tryConvertToPromise(thenable);
        if (maybePromise !== thenable &&
            typeof thenable._isDisposable === "function" &&
            typeof thenable._getDisposer === "function" &&
            thenable._isDisposable()) {
            maybePromise._setDisposable(thenable._getDisposer());
        }
        return maybePromise;
    }
    function dispose(resources, inspection) {
        var i = 0;
        var len = resources.length;
        var ret = new Promise(INTERNAL);
        function iterator() {
            if (i >= len) return ret._fulfill();
            var maybePromise = castPreservingDisposable(resources[i++]);
            if (maybePromise instanceof Promise &&
                maybePromise._isDisposable()) {
                try {
                    maybePromise = tryConvertToPromise(
                        maybePromise._getDisposer().tryDispose(inspection),
                        resources.promise);
                } catch (e) {
                    return thrower(e);
                }
                if (maybePromise instanceof Promise) {
                    return maybePromise._then(iterator, thrower,
                                              null, null, null);
                }
            }
            iterator();
        }
        iterator();
        return ret;
    }
    function Disposer(data, promise, context) {
        this._data = data;
        this._promise = promise;
        this._context = context;
    }
    Disposer.prototype.data = function () {
        return this._data;
    };
    Disposer.prototype.promise = function () {
        return this._promise;
    };
    Disposer.prototype.resource = function () {
        if (this.promise().isFulfilled()) {
            return this.promise().value();
        }
        return NULL;
    };
    Disposer.prototype.tryDispose = function(inspection) {
        var resource = this.resource();
        var context = this._context;
        if (context !== undefined) context._pushContext();
        var ret = resource !== NULL
            ? this.doDispose(resource, inspection) : null;
        if (context !== undefined) context._popContext();
        this._promise._unsetDisposable();
        this._data = null;
        return ret;
    };
    Disposer.isDisposer = function (d) {
        return (d != null &&
                typeof d.resource === "function" &&
                typeof d.tryDispose === "function");
    };
    function FunctionDisposer(fn, promise, context) {
        this.constructor$(fn, promise, context);
    }
    inherits(FunctionDisposer, Disposer);
    FunctionDisposer.prototype.doDispose = function (resource, inspection) {
        var fn = this.data();
        return fn.call(resource, resource, inspection);
    };
    function maybeUnwrapDisposer(value) {
        if (Disposer.isDisposer(value)) {
            this.resources[this.index]._setDisposable(value);
            return value.promise();
        }
        return value;
    }
    function ResourceList(length) {
        this.length = length;
        this.promise = null;
        this[length-1] = null;
    }
    ResourceList.prototype._resultCancelled = function() {
        var len = this.length;
        for (var i = 0; i < len; ++i) {
            var item = this[i];
            if (item instanceof Promise) {
                item.cancel();
            }
        }
    };
    Promise.using = function () {
        var len = arguments.length;
        if (len < 2) return apiRejection(
                        "you must pass at least 2 arguments to Promise.using");
        var fn = arguments[len - 1];
        if (typeof fn !== "function") {
            return apiRejection("expecting a function but got " + util.classString(fn));
        }
        var input;
        var spreadArgs = true;
        if (len === 2 && Array.isArray(arguments[0])) {
            input = arguments[0];
            len = input.length;
            spreadArgs = false;
        } else {
            input = arguments;
            len--;
        }
        var resources = new ResourceList(len);
        for (var i = 0; i < len; ++i) {
            var resource = input[i];
            if (Disposer.isDisposer(resource)) {
                var disposer = resource;
                resource = resource.promise();
                resource._setDisposable(disposer);
            } else {
                var maybePromise = tryConvertToPromise(resource);
                if (maybePromise instanceof Promise) {
                    resource =
                        maybePromise._then(maybeUnwrapDisposer, null, null, {
                            resources: resources,
                            index: i
                    }, undefined);
                }
            }
            resources[i] = resource;
        }
        var reflectedResources = new Array(resources.length);
        for (var i = 0; i < reflectedResources.length; ++i) {
            reflectedResources[i] = Promise.resolve(resources[i]).reflect();
        }
        var resultPromise = Promise.all(reflectedResources)
            .then(function(inspections) {
                for (var i = 0; i < inspections.length; ++i) {
                    var inspection = inspections[i];
                    if (inspection.isRejected()) {
                        errorObj.e = inspection.error();
                        return errorObj;
                    } else if (!inspection.isFulfilled()) {
                        resultPromise.cancel();
                        return;
                    }
                    inspections[i] = inspection.value();
                }
                promise._pushContext();
                fn = tryCatch(fn);
                var ret = spreadArgs
                    ? fn.apply(undefined, inspections) : fn(inspections);
                var promiseCreated = promise._popContext();
                debug.checkForgottenReturns(
                    ret, promiseCreated, "Promise.using", promise);
                return ret;
            });
        var promise = resultPromise.lastly(function() {
            var inspection = new Promise.PromiseInspection(resultPromise);
            return dispose(resources, inspection);
        });
        resources.promise = promise;
        promise._setOnCancel(resources);
        return promise;
    };
    Promise.prototype._setDisposable = function (disposer) {
        this._bitField = this._bitField | 131072;
        this._disposer = disposer;
    };
    Promise.prototype._isDisposable = function () {
        return (this._bitField & 131072) > 0;
    };
    Promise.prototype._getDisposer = function () {
        return this._disposer;
    };
    Promise.prototype._unsetDisposable = function () {
        this._bitField = this._bitField & (~131072);
        this._disposer = undefined;
    };
    Promise.prototype.disposer = function (fn) {
        if (typeof fn === "function") {
            return new FunctionDisposer(fn, this, createContext());
        }
        throw new TypeError();
    };
};

+ 375 - 0
src/server/node_modules/bluebird/js/release/util.js

@ -0,0 +1,375 @@
"use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
    typeof window !== "undefined" ? window :
    typeof global !== "undefined" ? global :
    this !== undefined ? this : null;
function tryCatcher() {
    try {
        var target = tryCatchTarget;
        tryCatchTarget = null;
        return target.apply(this, arguments);
    } catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}
function tryCatch(fn) {
    tryCatchTarget = fn;
    return tryCatcher;
}
var inherits = function(Child, Parent) {
    var hasProp = {}.hasOwnProperty;
    function T() {
        this.constructor = Child;
        this.constructor$ = Parent;
        for (var propertyName in Parent.prototype) {
            if (hasProp.call(Parent.prototype, propertyName) &&
                propertyName.charAt(propertyName.length-1) !== "$"
           ) {
                this[propertyName + "$"] = Parent.prototype[propertyName];
            }
        }
    }
    T.prototype = Parent.prototype;
    Child.prototype = new T();
    return Child.prototype;
};
function isPrimitive(val) {
    return val == null || val === true || val === false ||
        typeof val === "string" || typeof val === "number";
}
function isObject(value) {
    return typeof value === "function" ||
           typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
    if (!isPrimitive(maybeError)) return maybeError;
    return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
    var len = target.length;
    var ret = new Array(len + 1);
    var i;
    for (i = 0; i < len; ++i) {
        ret[i] = target[i];
    }
    ret[i] = appendee;
    return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
    if (es5.isES5) {
        var desc = Object.getOwnPropertyDescriptor(obj, key);
        if (desc != null) {
            return desc.get == null && desc.set == null
                    ? desc.value
                    : defaultValue;
        }
    } else {
        return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
    }
}
function notEnumerableProp(obj, name, value) {
    if (isPrimitive(obj)) return obj;
    var descriptor = {
        value: value,
        configurable: true,
        enumerable: false,
        writable: true
    };
    es5.defineProperty(obj, name, descriptor);
    return obj;
}
function thrower(r) {
    throw r;
}
var inheritedDataKeys = (function() {
    var excludedPrototypes = [
        Array.prototype,
        Object.prototype,
        Function.prototype
    ];
    var isExcludedProto = function(val) {
        for (var i = 0; i < excludedPrototypes.length; ++i) {
            if (excludedPrototypes[i] === val) {
                return true;
            }
        }
        return false;
    };
    if (es5.isES5) {
        var getKeys = Object.getOwnPropertyNames;
        return function(obj) {
            var ret = [];
            var visitedKeys = Object.create(null);
            while (obj != null && !isExcludedProto(obj)) {
                var keys;
                try {
                    keys = getKeys(obj);
                } catch (e) {
                    return ret;
                }
                for (var i = 0; i < keys.length; ++i) {
                    var key = keys[i];
                    if (visitedKeys[key]) continue;
                    visitedKeys[key] = true;
                    var desc = Object.getOwnPropertyDescriptor(obj, key);
                    if (desc != null && desc.get == null && desc.set == null) {
                        ret.push(key);
                    }
                }
                obj = es5.getPrototypeOf(obj);
            }
            return ret;
        };
    } else {
        var hasProp = {}.hasOwnProperty;
        return function(obj) {
            if (isExcludedProto(obj)) return [];
            var ret = [];
            /*jshint forin:false */
            enumeration: for (var key in obj) {
                if (hasProp.call(obj, key)) {
                    ret.push(key);
                } else {
                    for (var i = 0; i < excludedPrototypes.length; ++i) {
                        if (hasProp.call(excludedPrototypes[i], key)) {
                            continue enumeration;
                        }
                    }
                    ret.push(key);
                }
            }
            return ret;
        };
    }
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
    try {
        if (typeof fn === "function") {
            var keys = es5.names(fn.prototype);
            var hasMethods = es5.isES5 && keys.length > 1;
            var hasMethodsOtherThanConstructor = keys.length > 0 &&
                !(keys.length === 1 && keys[0] === "constructor");
            var hasThisAssignmentAndStaticMethods =
                thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
            if (hasMethods || hasMethodsOtherThanConstructor ||
                hasThisAssignmentAndStaticMethods) {
                return true;
            }
        }
        return false;
    } catch (e) {
        return false;
    }
}
function toFastProperties(obj) {
    /*jshint -W027,-W055,-W031*/
    function FakeConstructor() {}
    FakeConstructor.prototype = obj;
    var l = 8;
    while (l--) new FakeConstructor();
    return obj;
    eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
    return rident.test(str);
}
function filledRange(count, prefix, suffix) {
    var ret = new Array(count);
    for(var i = 0; i < count; ++i) {
        ret[i] = prefix + i + suffix;
    }
    return ret;
}
function safeToString(obj) {
    try {
        return obj + "";
    } catch (e) {
        return "[no string representation]";
    }
}
function isError(obj) {
    return obj !== null &&
           typeof obj === "object" &&
           typeof obj.message === "string" &&
           typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
    try {
        notEnumerableProp(e, "isOperational", true);
    }
    catch(ignore) {}
}
function originatesFromRejection(e) {
    if (e == null) return false;
    return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
        e["isOperational"] === true);
}
function canAttachTrace(obj) {
    return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
    if (!("stack" in new Error())) {
        return function(value) {
            if (canAttachTrace(value)) return value;
            try {throw new Error(safeToString(value));}
            catch(err) {return err;}
        };
    } else {
        return function(value) {
            if (canAttachTrace(value)) return value;
            return new Error(safeToString(value));
        };
    }
})();
function classString(obj) {
    return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
    var keys = es5.names(from);
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        if (filter(key)) {
            try {
                es5.defineProperty(to, key, es5.getDescriptor(from, key));
            } catch (ignore) {}
        }
    }
}
var asArray = function(v) {
    if (es5.isArray(v)) {
        return v;
    }
    return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
    var ArrayFrom = typeof Array.from === "function" ? function(v) {
        return Array.from(v);
    } : function(v) {
        var ret = [];
        var it = v[Symbol.iterator]();
        var itResult;
        while (!((itResult = it.next()).done)) {
            ret.push(itResult.value);
        }
        return ret;
    };
    asArray = function(v) {
        if (es5.isArray(v)) {
            return v;
        } else if (v != null && typeof v[Symbol.iterator] === "function") {
            return ArrayFrom(v);
        }
        return null;
    };
}
var isNode = typeof process !== "undefined" &&
        classString(process).toLowerCase() === "[object process]";
function env(key, def) {
    return isNode ? process.env[key] : def;
}
function getNativePromise() {
    if (typeof Promise === "function") {
        try {
            var promise = new Promise(function(){});
            if ({}.toString.call(promise) === "[object Promise]") {
                return Promise;
            }
        } catch (e) {}
    }
}
function domainBind(self, cb) {
    return self.bind(cb);
}
var ret = {
    isClass: isClass,
    isIdentifier: isIdentifier,
    inheritedDataKeys: inheritedDataKeys,
    getDataPropertyOrDefault: getDataPropertyOrDefault,
    thrower: thrower,
    isArray: es5.isArray,
    asArray: asArray,
    notEnumerableProp: notEnumerableProp,
    isPrimitive: isPrimitive,
    isObject: isObject,
    isError: isError,
    canEvaluate: canEvaluate,
    errorObj: errorObj,
    tryCatch: tryCatch,
    inherits: inherits,
    withAppended: withAppended,
    maybeWrapAsError: maybeWrapAsError,
    toFastProperties: toFastProperties,
    filledRange: filledRange,
    toString: safeToString,
    canAttachTrace: canAttachTrace,
    ensureErrorObject: ensureErrorObject,
    originatesFromRejection: originatesFromRejection,
    markAsOriginatingFromRejection: markAsOriginatingFromRejection,
    classString: classString,
    copyDescriptors: copyDescriptors,
    hasDevTools: typeof chrome !== "undefined" && chrome &&
                 typeof chrome.loadTimes === "function",
    isNode: isNode,
    env: env,
    global: globalObject,
    getNativePromise: getNativePromise,
    domainBind: domainBind
};
ret.isRecentNode = ret.isNode && (function() {
    var version = process.versions.node.split(".").map(Number);
    return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;

+ 102 - 0
src/server/node_modules/bluebird/package.json

@ -0,0 +1,102 @@
{
  "name": "bluebird",
  "description": "Full featured Promises/A+ implementation with exceptionally good performance",
  "version": "3.4.6",
  "keywords": [
    "promise",
    "performance",
    "promises",
    "promises-a",
    "promises-aplus",
    "async",
    "await",
    "deferred",
    "deferreds",
    "future",
    "flow control",
    "dsl",
    "fluent interface"
  ],
  "scripts": {
    "lint": "node scripts/jshint.js",
    "test": "node tools/test.js",
    "istanbul": "istanbul",
    "prepublish": "npm run generate-browser-core && npm run generate-browser-full",
    "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify",
    "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js"
  },
  "homepage": "https://github.com/petkaantonov/bluebird",
  "repository": {
    "type": "git",
    "url": "git://github.com/petkaantonov/bluebird.git"
  },
  "bugs": {
    "url": "http://github.com/petkaantonov/bluebird/issues"
  },
  "license": "MIT",
  "author": {
    "name": "Petka Antonov",
    "email": "petka_antonov@hotmail.com",
    "url": "http://github.com/petkaantonov/"
  },
  "devDependencies": {
    "acorn": "~0.6.0",
    "baconjs": "^0.7.43",
    "bluebird": "^2.9.2",
    "body-parser": "^1.10.2",
    "browserify": "^8.1.1",
    "cli-table": "~0.3.1",
    "co": "^4.2.0",
    "cross-spawn": "^0.2.3",
    "glob": "^4.3.2",
    "grunt-saucelabs": "~8.4.1",
    "highland": "^2.3.0",
    "istanbul": "^0.3.5",
    "jshint": "^2.6.0",
    "jshint-stylish": "~0.2.0",
    "mkdirp": "~0.5.0",
    "mocha": "~2.1",
    "open": "~0.0.5",
    "optimist": "~0.6.1",
    "rimraf": "~2.2.6",
    "rx": "^2.3.25",
    "serve-static": "^1.7.1",
    "sinon": "~1.7.3",
    "uglify-js": "~2.4.16",
    "kefir": "^2.4.1"
  },
  "main": "./js/release/bluebird.js",
  "browser": "./js/browser/bluebird.js",
  "files": [
    "js/browser",
    "js/release",
    "LICENSE"
  ],
  "gitHead": "b466418e1d8cafd93c807f84b4dceee715c70b35",
  "_id": "bluebird@3.4.6",
  "_shasum": "01da8d821d87813d158967e743d5fe6c62cf8c0f",
  "_from": "bluebird@latest",
  "_npmVersion": "3.6.0",
  "_nodeVersion": "5.6.0",
  "_npmUser": {
    "name": "esailija",
    "email": "petka_antonov@hotmail.com"
  },
  "dist": {
    "shasum": "01da8d821d87813d158967e743d5fe6c62cf8c0f",
    "tarball": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.6.tgz"
  },
  "maintainers": [
    {
      "name": "esailija",
      "email": "petka_antonov@hotmail.com"
    }
  ],
  "_npmOperationalInternal": {
    "host": "packages-12-west.internal.npmjs.com",
    "tmp": "tmp/bluebird-3.4.6.tgz_1472763137386_0.698919479502365"
  },
  "directories": {},
  "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.6.tgz",
  "readme": "ERROR: No README data found!"
}

+ 3 - 0
src/server/node_modules/mongoose/.eslintignore

@ -0,0 +1,3 @@
docs/
bin/
test/triage/

+ 31 - 0
src/server/node_modules/mongoose/.eslintrc.yml

@ -0,0 +1,31 @@
extends: 'eslint:recommended'
env:
  node: true
  mocha: true
rules:
  comma-style: error
  consistent-this:
    - error
    - _this
  indent:
    - error
    - 2
    - SwitchCase: 1
      VariableDeclarator: 2
  keyword-spacing: error
  no-console: off
  no-multi-spaces: error
  no-spaced-func: error
  no-trailing-spaces: error
  quotes:
    - error
    - single
  semi: error
  space-before-blocks: error
  space-before-function-paren:
    - error
    - never
  space-infix-ops: error
  space-unary-ops: error

+ 16 - 0
src/server/node_modules/mongoose/.npmignore

@ -0,0 +1,16 @@
lib-cov
**.swp
*.sw*
*.orig
.DS_Store
node_modules/
benchmarks/
docs/
test/
Makefile
CNAME
index.html
index.jade
bin/
karma.*.js
format_deps.js

+ 15 - 0
src/server/node_modules/mongoose/.travis.yml

@ -0,0 +1,15 @@
language: node_js
sudo: false
node_js:
  - "7"
  - "6"
  - "5"
  - "4"
  - "0.12"
  - "0.10"
  - "iojs"
before_script:
  - wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz
  - tar -zxvf mongodb-linux-x86_64-2.6.11.tgz
  - mkdir -p ./data/db
  - ./mongodb-linux-x86_64-2.6.11/bin/mongod --fork --nopreallocj --dbpath ./data/db --syslog --port 27017

File diff suppressed because it is too large
+ 56 - 0
src/server/node_modules/mongoose/CONTRIBUTING.md


+ 3339 - 0
src/server/node_modules/mongoose/History.md

@ -0,0 +1,3339 @@
4.7.2 / 2016-12-07
==================
 * test(populate): fix justOne test #4772 [cblanc](https://github.com/cblanc)
 * chore: fix benchmarks #4769 [billouboq](https://github.com/billouboq)
 * fix(document): handle setting subdoc to null after setting parent doc #4766
 * fix(query): support passRawResult with lean #4762 #4761 [mhfrantz](https://github.com/mhfrantz)
 * fix(query): throw StrictModeError if upsert with nonexisting field in condition #4757
 * test: fix a couple of sort tests #4756 [japod](https://github.com/japod)
 * chore: upgrade mongodb driver -> 2.2.12 #4753 [mdlavin](https://github.com/mdlavin)
 * fix(query): handle update with upsert and overwrite correctly #4749
4.7.1 / 2016-11-30
==================
 * fix(schema): throw error if you use prototype as a schema path #4746
 * fix(schema): throw helpful error if you define a virtual with the same path as a real path #4744
 * fix(connection): make createConnection not throw rejected promises #4742
 * fix(populate): allow specifiying options in model schema #4741
 * fix(document): handle selected nested elements with defaults #4739
 * fix(query): add model to cast error if possible #4729
 * fix(query): handle timestamps with overwrite #4054
4.7.0 / 2016-11-23
==================
 * docs: clean up schematypes #4732 [kidlj](https://github.com/kidlj)
 * perf: only get stack when necessary with VersionError #4726 [Sebmaster](https://github.com/Sebmaster)
 * fix(query): ensure correct casting when setting array element #4724
 * fix(connection): ensure db name gets set when you pass 4 params #4721
 * fix: prevent TypeError in node v7 #4719 #4706
 * feat(document): support .set() on virtual subpaths #4716
 * feat(populate): support populate virtuals on nested schemas #4715
 * feat(querycursor): support transform option and .map() #4714 #4705 [cblanc](https://github.com/cblanc)
 * fix(document): dont set defaults on not-selected nested paths #4707
 * fix(populate): don't throw if empty string passed to populate #4702
 * feat(model): add `loadClass()` function for importing schema from ES6 class #4668 [rockmacaca](https://github.com/rockmacaca)
4.6.8 / 2016-11-14
==================
 * fix(querycursor): clear stack when iterating onto next doc #4697
 * fix: handle null keys in validation error #4693 #4689 [arciisine](https://github.com/arciisine)
 * fix(populate): handle pre init middleware correctly with populate virtuals #4683
 * fix(connection): ensure consistent return value for open and openSet #4659
 * fix(schema): handle falsy defaults for arrays #4620
4.6.7 / 2016-11-10
==================
 * fix(document): only invalidate in subdoc if using update validators #4681
 * fix(document): don't create subdocs when excluded in projection #4669
 * fix(document): ensure single embedded schema validator runs with correct context #4663
 * fix(document): make sure to depopulate top level for sharding #4658
 * fix(connection): throw more helpful error when .model() called incorrectly #4652
 * fix(populate): throw more descriptive error when trying to populate a virtual that doesn't have proper options #4602
 * fix(document): ensure subtype gets set properly when saving with a buffer id #4506
 * fix(query): handle setDefaultsOnInsert with defaults on doc arrays #4456
 * fix(drivers): make debug output better by calling toBSON() #4356
4.6.6 / 2016-11-03
==================
 * chore: upgrade deps #4674 [TrejGun](https://github.com/TrejGun)
 * chore: run tests on node v7 #4673 [TrejGun](https://github.com/TrejGun)
 * perf: make setDefaultsOnInsert more efficient if upsert is off #4672 [CamHenlin](https://github.com/CamHenlin)
 * fix(populate): ensure document array is returned #4656
 * fix(query): cast doc arrays with positionals correctly for update #4655
 * fix(document): ensure single nested doc validators run with correct context #4654
 * fix: handle reconnect failed error in new version of driver #4653 [loris](https://github.com/loris)
 * fix(populate): if setting a populated doc, take its id #4632
 *  fix(populate): handle populated virtuals in init #4618
4.6.5 / 2016-10-23
==================
 * docs: fix grammar issues #4642 #4640 #4639 [silvermanj7](https://github.com/silvermanj7)
 * fix(populate): filter out nonexistant values for dynref #4637
 * fix(query): handle $type as a schematype operator #4632
 * fix(schema): better handling for uppercase: false and lowercase: false #4622
 * fix(query): don't run transforms on updateForExec() #4621
 * fix(query): handle id = 0 in findById #4610
 * fix(query): handle buffers in mergeClone #4609
 * fix(document): handle undefined with conditional validator for validateSync #4607
 * fix: upgrade to mongodb driver 2.2.11 #4581
 * docs(schematypes): clarify schema.path() #4518
 * fix(query): ensure path is defined before checking in timestamps #4514
 * fix(model): set version key in upsert #4505
 * fix(document): never depopulate top-level doc #3057
 * refactor: ensure sync for setting non-capped collections #2690
4.6.4 / 2016-10-16
==================
 * fix(query): cast $not correctly #4616 #4592 [prssn](https://github.com/prssn)
 * fix: address issue with caching global plugins #4608 #4601 [TrejGun](https://github.com/TrejGun)
 * fix(model): make sure to depopulate in insertMany #4590
 * fix(model): buffer autoIndex if bufferCommands disabled #4589
 * fix(populate): copy ids array before modifying #4585
 * feat(schema): add retainKeyOrder prop #4542
 * fix(document): return isModified true for children of direct modified paths #4528
 * fix(connection): add dropDatabase() helper #4490
 * fix(model): add usePushEach option for schemas #4455
 * docs(connections): add some warnings about buffering #4413
 * fix: add ability to set promise implementation in browser #4395
4.6.3 / 2016-10-05
==================
 * fix(document): ensure single nested docs get initialized correctly when setting nested paths #4578
 * fix: turn off transforms when writing nested docs to db #4574
 * fix(document): don't set single nested subdocs to null when removing parent doc #4566
 * fix(model): ensure versionKey gets set in insertMany #4561
 * fix(schema): handle typeKey in arrays #4548
 * feat(schema): set $implicitlyCreated on schema if created by interpretAsType #4443
4.6.2 / 2016-09-30
==================
 * chore: upgrade to async 2.0.1 internally #4579 [billouboq](https://github.com/billouboq)
 * fix(types): ensure nested single doc schema errors reach update validators #4557 #4519
 * fix(connection): handle rs names with leading numbers (muri 1.1.1) #4556
 * fix(model): don't throw if method name conflicts with Object.prototype prop #4551
 * docs: fix broken link #4544 [VFedyk](https://github.com/VFedyk)
 * fix: allow overwriting model on mongoose singleton #4541 [Nainterceptor](https://github.com/Nainterceptor)
 * fix(document): don't use init: true when building doc defaults #4540
 * fix(connection): use replSet option if replset not specified #4535
 * fix(query): cast $not objects #4495
4.6.1 / 2016-09-20
==================
 * fix(query): improve handling of $not with $elemMatch #4531 #3719 [timbowhite](https://github.com/timbowhite)
 * fix: upgrade mongodb -> 2.2.10 #4517
 * chore: fix webpack build issue #4512 [saiichihashimoto](https://github.com/saiichihashimoto)
 * fix(query): emit error on next tick when exec callback errors #4500
 * test: improve test case #4496 [isayme](https://github.com/isayme)
 * fix(schema): use same check for array types and top-level types #4493
 * style: fix indentation in docs #4489 [dhurlburtusa](https://github.com/dhurlburtusa)
 * fix(schema): expose original object passed to constructor #4486
 * fix(query): handle findOneAndUpdate with array of arrays #4484 #4470 [fedotov](https://github.com/fedotov)
 * feat(document): add $ignore to make a path ignored #4480
 * fix(query): properly handle setting single embedded in update #4475 #4466 #4465
 * fix(updateValidators): handle single nested schema subpaths correctly #4479
 * fix(model): throw handy error when method name conflicts with property name #4475
 * fix(schema): handle .set() with array field #4472
 * fix(query): check nested path when avoiding double-validating Mixed #4441
 * fix(schema): handle calling path.trim() with no args correctly #4042
4.6.0 / 2016-09-02
==================
 * docs(document): clarify the findById and findByIdAndUpdate examples #4471 [mdcanham](https://github.com/mdcanham)
 * docs(schematypes): add details re: options #4452
 * docs(middleware): add docs for insertMany hooks #4451
 * fix(schema): create new array when copying from existing object to preserve change tracking #4449
 * docs: fix typo in index.jade #4448
 * fix(query): allow array for populate options #4446
 * fix(model): create should not cause unhandle reject promise #4439
 * fix: upgrade to mongodb driver 2.2.9 #4363 #4341 #4311 (see [comments here](https://github.com/mongodb/js-bson/commit/aa0b54597a0af28cce3530d2144af708e4b66bf0#commitcomment-18850498) if you use node 0.10)
4.5.10 / 2016-08-23
===================
 * docs: fix typo on documents.jade #4444 [Gabri3l](https://github.com/Gabri3l)
 * chore: upgrade mocha to 3.0.2 #4437 [TrejGun](https://github.com/TrejGun)
 * fix: subdocuments causing error with parent timestamp on update #4434 [dyang108](https://github.com/dyang108)
 * fix(query): don't crash if timestamps on and update doesn't have a path #4425 #4424 #4418
 * fix(query): ensure single nested subdoc is hydrated when running update validators #4420
 * fix(query): cast non-$geometry operators for $geoWithin #4419
 * docs: update contributor count #4415 [AdamZaczek](https://github.com/AdamZaczek)
 * docs: add more clarification re: the index event #4410
 * fix(document): only skip modifying subdoc path if parent is direct modified #4405
 * fix(schema): throw cast error if provided date invalid #4404
 * feat(error): use util.inspect() so CastError never prints "[object Object]" #4398
 * fix(model): dont error if the discriminator key is unchanged #4387
 * fix(query): don't throw unhandled rejection with bluebird when using cbs #4379
4.5.9 / 2016-08-14
==================
 * docs: add mixed schema doc for Object literal #4400 [Kikobeats](https://github.com/Kikobeats)
 * fix(query): cast $geoWithin and convert mongoose objects to POJOs before casting #4392
 * fix(schematype): dont cast defaults without parent doc #4390
 * fix(query): disallow passing empty string to findOne() #4378
 * fix(document): set single nested doc isNew correctly #4369
 * fix(types): checks field name correctly with nested arrays and populate #4365
 * fix(drivers): make debug output copy-pastable into mongodb shell #4352
 * fix(services): run update validators on nested paths #4332
 * fix(model): handle typeKey with discriminators #4339
 * fix(query): apply timestamps to child schemas when explicitly specified in update #4049
 * fix(schema): set prefix as nested path with add() #1730
4.5.8 / 2016-08-01
==================
 * fix(model): make changing the discriminator key cause a cast error #4374
 * fix(query): pass projection fields to cursor #4371 #4342 [Corei13](https://github.com/Corei13)
 * fix(document): support multiple paths for isModified #4370 [adambuczynski](https://github.com/adambuczynski)
 * fix(querycursor): always cast fields before returning cursor #4355
 * fix(query): support projection as alias for fields in findOneAndUpdate #4315
 * fix(schema): treat index false + unique false as no index #4304
 * fix(types): dont mark single nested subpath as modified if whole doc already modified #4224
4.5.7 / 2016-07-25
==================
 * fix(document): ensure no unhandled rejections if callback specified for save #4364
4.5.6 / 2016-07-23
==================
 * fix(schema): don't overwrite createdAt if it isn't selected #4351 [tusbar](https://github.com/tusbar)
 * docs(api): fix link to populate() and add a new one from depopulate() #4345 [Delapouite](https://github.com/Delapouite)
 * fix(types): ownerDocument() works properly with single nested docs #4344 [vichle](https://github.com/vichle)
 * fix(populate): dont use findOne when justOne option set #4329
 * fix(document): dont trigger .then() deprecated warning when calling doc.remove() #4291
 * docs(connection): add promiseLibrary option #4280
 * fix(plugins): apply global plugins to subschemas #4271
 * fix(model): ensure `ensureIndex()` never calls back in the same tick #4246
 * docs(schema): improve post hook docs on schema #4238
4.5.5 / 2016-07-18
==================
 * fix(document): handle setting root to empty obj if minimize false #4337
 * fix: downgrade to mongodb 2.1.18 #4335 #4334 #4328 #4323
 * perf(types): remove defineProperty usage in documentarray #4333
 * fix(query): correctly pass model in .toConstructor() #4318
 * fix(services): avoid double-validating mixed types with update validators #4305
 * docs(middleware): add docs describing error handling middleware #4229
 * fix(types): throw correct error when invalidating doc array #3602
4.5.4 / 2016-07-11
==================
 * fix(types): fix removing embedded documents #4309 [RoCat](https://github.com/RoCat)
 * docs: various docs improvements #4302 #4294 [simonxca](https://github.com/simonxca)
 * fix: upgrade mongodb -> 2.1.21 #4295 #4202 [RoCat](https://github.com/RoCat)
 * fix(populate): convert single result to array for virtual populate because of lean #4288
 * fix(populate): handle empty results for populate virtuals properly #4285 #4284
 * fix(query): dont cast $inc to number if type is long #4283
 * fix(types): allow setting single nested doc to null #4281
 * fix(populate): handle deeply nested virtual populate #4278
 * fix(document): allow setting empty obj if strict mode is false #4274
 * fix(aggregate): allow passing obj to .unwind() #4239
 * docs(document): add return statements to transform examples #1963
4.5.3 / 2016-06-30
==================
 * fix(query): pass correct options to QueryCursor #4277 #4266
 * fix(querycursor): handle lean option correctly #4276 [gchudnov](https://github.com/gchudnov)
 * fix(document): fix error handling when no error occurred #4275
 * fix(error): use strict mode for version error #4272
 * docs(populate): fix crashing compilation for populate.jade #4267
 * fix(populate): support `justOne` option for populate virtuals #4263
 * fix(populate): ensure model param gets used for populate virtuals #4261 #4243
 * fix(querycursor): add ability to properly close the cursor #4258
 * docs(model): correct link to Document #4250
 * docs(populate): correct path for refPath populate #4240
 * fix(document): support validator.isEmail as validator #4064
4.5.2 / 2016-06-24
==================
 * fix(connection): add checks for collection presence for `onOpen` and `onClose` #4259 [nodkz](https://github.com/nodkz)
 * fix(cast): allow strings for $type operator #4256
 * fix(querycursor): support lean() #4255 [pyramation](https://github.com/pyramation)
 * fix(aggregate): allow setting noCursorTimeout option #4241
 * fix(document): handle undefined for Array.pull #4222 [Sebmaster](https://github.com/Sebmaster)
 * fix(connection): ensure promise.catch() catches initial connection error #4135
 * fix(document): show additional context for VersionError #2633
4.5.1 / 2016-06-18
==================
 * fix(model): ensure wrapped insertMany() returns a promise #4237
 * fix(populate): dont overwrite populateVirtuals when populating multiple paths #4234
 * docs(model): clarify relationship between create() and save() #4233
 * fix(types): handle option param in subdoc remove() #4231 [tdebarochez](https://github.com/tdebarochez)
 * fix(document): dedupe modified paths #4226 #4223 [adambuczynski](https://github.com/adambuczynski)
 * fix(model): don't modify user-provided options object #4221
 * fix(document): handle setting nested path to empty object #4218 #4182
 * fix(document): clean subpaths when removing single nested #4216
 * fix(document): don't force transform on subdocs with inspect #4213
 * fix(error): allow setting .messages object #4207
4.5.0 / 2016-06-13
==================
 * feat(query): added Query.prototype.catch() #4215 #4173 [adambuczynski](https://github.com/adambuczynski)
 * feat(query): add Query.prototype.cursor() as a .stream() alternative #4117 #3637 #1907
 * feat(document): add markUnmodified() function #4092 [vincentcr](https://github.com/vincentcr)
 * feat(aggregate): convert aggregate object to a thenable #3995 #3946 [megagon](https://github.com/megagon)
 * perf(types): remove defineProperties call for array (**Note:** Because of this, a mongoose array will no longer `assert.deepEqual()` a plain old JS array) #3886
 * feat(model): add hooks for insertMany() #3846
 * feat(schema): add support for custom query methods #3740 #2372
 * feat(drivers): emit error on 'serverClosed' because that means that reconnect failed #3615
 * feat(model): emit error event when callback throws exception #3499
 * feat(model): inherit options from discriminator base schema #3414 #1818
 * feat(populate): expose mongoose-populate-virtuals inspired populate API #2562
 * feat(document): trigger remove hooks on subdocs when removing parent #2348
 * feat(schema): add support for express-style error handling middleware #2284
 * fix(model): disallow setting discriminator key #2041
 * feat(schema): add support for nested arrays #1361
4.4.20 / 2016-06-05
===================
 * docs: clarify command buffering when using driver directly #4195
 * fix(promise): correct broken mpromise .catch() #4189
 * fix(document): clean modified subpaths when set path to empty obj #4182
 * fix(query): support minDistance with query casting and `.near()` #4179
 * fix(model): remove unnecessary .save() promise #4177
 * fix(schema): cast all valid ObjectId strings to object ids #3365
 * docs: remove unclear "unsafe" term in query docs #3282
4.4.19 / 2016-05-21
===================
 * fix(model): handle insertMany if timestamps not set #4171
4.4.18 / 2016-05-21
===================
 * docs: add missing period #4170 [gitname](https://github.com/gitname)
 * docs: change build badge to svg #4158 [a0viedo](https://github.com/a0viedo)
 * fix(model): update timestamps when setting `createdAt` #4155
 * fix(utils): make sure to require in document properly #4152
 * fix(model): throw overwrite error when discriminator name conflicts #4148
4.4.17 / 2016-05-13
===================
 * docs: remove repetition in QueryStream docs #4147 [hugoabonizio](https://github.com/hugoabonizio)
 * fix(document): dont double-validate doc array elements #4145
 * fix(document): call required function with correct scope #4142 [JedWatson](https://github.com/JedWatson)
4.4.16 / 2016-05-09
===================
 * refactor(document): use function reference #4133 [dciccale](https://github.com/dciccale)
 * docs(querystream): clarify `destroy()` and close event #4126 [AnthonyCC](https://github.com/AnthonyCC)
 * test: make before hook fail fast if it can't connect #4121
 * docs: add description of CastError constructor params #4120
 * fix(schematype): ensure single embedded defaults have $parent #4115
 * fix(document): mark nested paths for validation #4111
 * fix(schema): make sure element is always a subdoc in doc array validation #3816
4.4.15 / 2016-05-06
===================
 * fix(schema): support overwriting array default #4109
 * fix(populate): assign values when resolving each populate #4104
 * fix(aggregate): dont send async option to server #4101
 * fix(model): ensure isNew set to false after insertMany #4099
 * fix(connection): emit on error if listeners and no callback #4098
 * fix(document): treat required fn that returns false as required: false #4094
4.4.14 / 2016-04-27
===================
 * fix: upgrade mongodb -> 2.1.18 #4102
 * feat(connection): allow setting mongos as a uri query param #4093 #4035 [burtonjc](https://github.com/burtonjc)
 * fix(populate): make sure to use correct assignment order for each model #4073
 * fix(schema): add complete set of geospatial operators for single embedded subdocs #4014
3.8.40 / 2016-04-24
===================
 * upgraded; mquery -> 1.10.0 #3989
4.4.13 / 2016-04-21
===================
 * docs: add docs favicons #4082 [robertjustjones](https://github.com/robertjustjones)
 * docs(model): correct Model.remove() return value #4075 [Jokero](https://github.com/Jokero)
 * fix(query): add $geoWithin query casting for single embedded docs #4044
 * fix(schema): handle setting trim option to falsy #4042
 * fix(query): handle setDefaultsOnInsert with empty update #3835
4.4.12 / 2016-04-08
===================
 * docs(query): document context option for update and findOneAndUpdate #4055
 * docs(query): correct link to $geoWithin docs #4050
 * fix(project): upgrade to mongodb driver 2.1.16 #4048 [schmalliso](https://github.com/schmalliso)
 * docs(validation): fix validation docs #4028
 * fix(types): improve .id() check for document arrays #4011
 * fix(query): remove premature return when using $rename #3171
 * docs(connection): clarify relationship between models and connections #2157
4.4.11 / 2016-04-03
===================
 * fix: upgrade to mongodb driver 2.1.14 #4036 #4030 #3945
 * fix(connection): allow connecting with { mongos: true } to handle query params #4032 [burtonjc](https://github.com/burtonjc)
 * docs(connection): add autoIndex example #4026 [tilleps](https://github.com/tilleps)
 * fix(query): handle passRawResult option when zero results #4023
 * fix(populate): clone options before modifying #4022
 * docs: add missing whitespace #4019 [chenxsan](https://github.com/chenxsan)
 * chore: upgrade to ESLint 2.4.0 #4015 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fix(types): single nested subdocs get ids by default #4008
 * chore(project): add dependency status badge #4007 [Maheshkumar-Kakade](http://github.com/Maheshkumar-Kakade)
 * fix: make sure timestamps don't trigger unnecessary updates #4005 #3991 [tommarien](https://github.com/tommarien)
 * fix(document): inspect inherits schema options #4001
 * fix(populate): don't mark populated path as modified if setting to object w/ same id #3992
 * fix(document): support kind argument to invalidate #3965
4.4.10 / 2016-03-24
===================
 * fix(document): copy isNew when copying a document #3982
 * fix(document): don't override defaults with undefined keys #3981
 * fix(populate): merge multiple deep populate options for the same path #3974
4.4.9 / 2016-03-22
==================
 * fix: upgrade mongodb -> 2.1.10 re https://jira.mongodb.org/browse/NODE-679 #4010
 * docs: add syntax highlighting for acquit examples #3975
4.4.8 / 2016-03-18
==================
 * docs(aggregate): clarify promises #3990 [megagon](https://github.com/megagon)
 * fix: upgrade mquery -> 1.10 #3988 [matskiv](https://github.com/matskiv)
 * feat(connection): 'all' event for repl sets #3986 [xizhibei](https://github.com/xizhibei)
 * docs(types): clarify Array.pull #3985 [seriousManual](https://github.com/seriousManual)
 * feat(query): support array syntax for .sort() via mquery 1.9 #3980
 * fix(populate): support > 3 level nested populate #3973
 * fix: MongooseThenable exposes connection correctly #3972
 * docs(connection): add note about reconnectTries and reconnectInterval #3969
 * feat(document): invalidate returns the new validationError #3964
 * fix(query): .eq() as shorthand for .equals #3953 [Fonger](https://github.com/Fonger)
 * docs(connection): clarify connection string vs passed options #3941
 * docs(query): select option for findOneAndUpdate #3933
 * fix(error): ValidationError.properties no longer enumerable #3925
 * docs(validation): clarify how required validators work with nested schemas #3915
 * fix: upgrade mongodb driver -> 2.1.8 to make partial index errors more sane #3864
4.4.7 / 2016-03-11
==================
 * fix(query): stop infinite recursion caused by merging a mongoose buffer #3961
 * fix(populate): handle deep populate array -> array #3954
 * fix(schema): allow setting timestamps with .set() #3952 #3951 #3907 [Fonger](https://github.com/Fonger)
 * fix: MongooseThenable doesn't overwrite constructors #3940
 * fix(schema): don't cast boolean to date #3935
 * fix(drivers): support sslValidate in connection string #3929
 * fix(types): correct markModified() for single nested subdocs #3910
 * fix(drivers): catch and report any errors that occur in driver methods #3906
 * fix(populate): get subpopulate model correctly when array under nested #3904
 * fix(document): allow fields named 'pre' and 'post' #3902
 * docs(query): clarify runValidators and setDefaultsOnInsert options #3892
 * docs(validation): show how to use custom required messages in schema #2616
4.4.6 / 2016-03-02
==================
 * fix: upgrade mongodb driver to 2.1.7 #3938
 * docs: fix plugins link #3917 #3909 [fbertone](https://github.com/fbertone)
 * fix(query): sort+select with count works #3914
 * fix(query): improve mergeUpdate's ability to handle nested docs #3890
4.4.5 / 2016-02-24
==================
 * fix(query): ability to select a length field (upgrade to mquery 1.7.0) #3903
 * fix: include nested CastError as reason for array CastError #3897 [kotarou3](https://github.com/kotarou3)
 * fix(schema): check for doc existence before taking fields #3889
 * feat(schema): useNestedStrict option to take nested strict mode for update #3883
 * docs(validation): clarify relationship between required and checkRequired #3822
 * docs(populate): dynamic reference docs #3809
 * docs: expand dropdown when clicking on file name #3807
 * docs: plugins.mongoosejs.io is up #3127
 * fix(schema): ability to add a virtual with same name as removed path #2398
4.4.4 / 2016-02-17
==================
 * fix(schema): handle field selection when casting single nested subdocs #3880
 * fix(populate): populating using base model with multiple child models in result #3878
 * fix: ability to properly use return value of `mongoose.connect()` #3874
 * fix(populate): dont hydrate populated subdoc if lean option set #3873
 * fix(connection): dont re-auth if already connected with useDb #3871
 * docs: cover how to set underlying driver's promise lib #3869
 * fix(document): handle conflicting names in validation errors with subdocs #3867
 * fix(populate): set undefined instead of null consistently when populate couldn't find results #3859
 * docs: link to `execPopulate()` in `doc.populate()` docs #3836
 * docs(plugin): link to the `mongoose.plugin()` function #3732
4.4.3 / 2016-02-09
==================
 * fix: upgrade to mongodb 2.1.6 to remove kerberos log output #3861 #3860 [cartuchogl](https://github.com/cartuchogl)
 * fix: require('mongoose') is no longer a pseudo-promise #3856
 * fix(query): update casting for single nested docs #3820
 * fix(populate): deep populating multiple paths with same options #3808
 * docs(middleware): clarify save/validate hook order #1149
4.4.2 / 2016-02-05
==================
 * fix(aggregate): handle calling .cursor() with no options #3855
 * fix: upgrade mongodb driver to 2.1.5 for GridFS memory leak fix #3854
 * docs: fix schematype.html conflict #3853 #3850 #3843
 * fix(model): bluebird unhandled rejection with ensureIndexes() on init #3837
 * docs: autoIndex option for createConnection #3805
4.4.1 / 2016-02-03
==================
 * fix: linting broke some cases where we use `== null` as shorthand #3852
 * docs: fix up schematype.html conflict #3848 #3843 [mynameiscoffey](https://github.com/mynameiscoffey)
 * fix: backwards breaking change with `.connect()` return value #3847
 * docs: downgrade dox and highlight.js to fix docs build #3845
 * docs: clean up typo #3842 [Flash-](https://github.com/Flash-)
 * fix(document): storeShard handles undefined values #3841
 * chore: more linting #3838 [TrejGun](https://github.com/TrejGun)
 * fix(schema): handle `text: true` as a way to declare a text index #3824
4.4.0 / 2016-02-02
==================
 * docs: fix expireAfterSeconds index option name #3831 [Flash-](https://github.com/Flash-)
 * chore: run lint after test #3829 [ChristianMurphy](https://github.com/ChristianMurphy)
 * chore: use power-assert instead of assert #3828 [TrejGun](https://github.com/TrejGun)
 * chore: stricter lint #3827 [TrejGun](https://github.com/TrejGun)
 * feat(types): casting moment to date #3813 [TrejGun](https://github.com/TrejGun)
 * chore: comma-last lint for test folder #3810 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fix: upgrade async mpath, mpromise, muri, and sliced #3801 [TrejGun](https://github.com/TrejGun)
 * fix(query): geo queries now return proper ES2015 promises #3800 [TrejGun](https://github.com/TrejGun)
 * perf(types): use `Object.defineProperties()` for array #3799 [TrejGun](https://github.com/TrejGun)
 * fix(model): mapReduce, ensureIndexes, remove, and save properly return ES2015 promises #3795 #3628 #3595 [TrejGun](https://github.com/TrejGun)
 * docs: fixed dates in History.md #3791 [Jokero](https://github.com/Jokero)
 * feat: connect, open, openSet, and disconnect return ES2015 promises #3790 #3622 [TrejGun](https://github.com/TrejGun)
 * feat: custom type for int32 via mongoose-int32 npm package #3652 #3102
 * feat: basic custom schema type API #995
 * feat(model): `insertMany()` for more performant bulk inserts #723
4.3.7 / 2016-01-23
==================
 * docs: grammar fix in timestamps docs #3786 [zclancy](https://github.com/zclancy)
 * fix(document): setting nested populated docs #3783 [slamuu](https://github.com/slamuu)
 * fix(document): don't call post save hooks twice for pushed docs #3780
 * fix(model): handle `_id=0` correctly #3776
 * docs(middleware): async post hooks #3770
 * docs: remove confusing sentence #3765 [marcusmellis89](https://github.com/marcusmellis89)
3.8.39 / 2016-01-15
===================
 * fixed; casting a number to a buffer #3764
 * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold)
4.3.6 / 2016-01-15
==================
 * fix(types): casting a number to a buffer #3764
 * fix: add "listener" to reserved keywords #3759
 * chore: upgrade uglify #3757 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fix: broken execPopulate() in 4.3.5 #3755 #3753
 * fix: ability to remove() a single embedded doc #3754
 * style: comma-last in test folder #3751 [ChristianMurphy](https://github.com/ChristianMurphy)
 * docs: clarify versionKey option #3747
 * fix: improve colorization for arrays #3744 [TrejGun](https://github.com/TrejGun)
 * fix: webpack build #3713
4.3.5 / 2016-01-09
==================
 * fix(query): throw when 4th parameter to update not a function #3741 [kasselTrankos](https://github.com/kasselTrankos)
 * fix(document): separate error type for setting an object to a primitive #3735
 * fix(populate): Model.populate returns ES6 promise #3734
 * fix(drivers): re-register event handlers after manual reconnect #3729
 * docs: broken links #3727
 * fix(validation): update validators run array validation #3724
 * docs: clarify the need to use markModified with in-place date ops #3722
 * fix(document): mark correct path as populated when manually populating array #3721
 * fix(aggregate): support for array pipeline argument to append #3718 [dbkup](https://github.com/dbkup)
 * docs: clarify `.connect()` callback #3705
 * fix(schema): properly validate nested single nested docs #3702
 * fix(types): handle setting documentarray of wrong type #3701
 * docs: broken links #3700
 * fix(drivers): debug output properly displays '0' #3689
3.8.38 / 2016-01-07
===================
 * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup)
4.3.4 / 2015-12-23
==================
 * fix: upgrade mongodb driver to 2.1.2 for repl set error #3712 [sansmischevia](https://github.com/sansmischevia)
 * docs: validation docs typo #3709 [ivanmaeder](https://github.com/ivanmaeder)
 * style: remove unused variables #3708 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fix(schema): duck-typing for schemas #3703 [mgcrea](https://github.com/mgcrea)
 * docs: connection sample code issue #3697
 * fix(schema): duck-typing for schemas #3693 [mgcrea](https://github.com/mgcrea)
 * docs: clarify id schema option #3638
4.3.3 / 2015-12-18
==================
 * fix(connection): properly support 'replSet' as well as 'replset' #3688 [taxilian](https://github.com/taxilian)
 * fix(document): single nested doc pre hooks called before nested doc array #3687 [aliatsis](https://github.com/aliatsis)
4.3.2 / 2015-12-17
==================
 * fix(document): .set() into single nested schemas #3686
 * fix(connection): support 'replSet' as well as 'replset' option #3685
 * fix(document): bluebird unhandled rejection when validating doc arrays #3681
 * fix(document): hooks for doc arrays in single nested schemas #3680
 * fix(document): post hooks for single nested schemas #3679
 * fix: remove unused npm module #3674 [sybarite](https://github.com/sybarite)
 * fix(model): don't swallow exceptions in nested doc save callback #3671
 * docs: update keepAlive info #3667 [ChrisZieba](https://github.com/ChrisZieba)
 * fix(document): strict 'throw' throws a specific mongoose error #3662
 * fix: flakey test #3332
 * fix(query): more robust check for RegExp #2969
4.3.1 / 2015-12-11
==================
 * feat(aggregate): `.sample()` helper #3665
 * fix(query): bitwise query operators with buffers #3663
 * docs(migration): clarify `new` option and findByIdAndUpdate #3661
4.3.0 / 2015-12-09
==================
 * feat(query): support for mongodb 3.2 bitwise query operators #3660
 * style: use comma-last style consistently #3657 [ChristianMurphy](https://github.com/ChristianMurphy)
 * feat: upgrade mongodb driver to 2.1.0 for full MongoDB 3.2 support #3656
 * feat(aggregate): `.lookup()` helper #3532
4.2.10 / 2015-12-08
===================
 * fixed; upgraded marked #3653 [ChristianMurphy](https://github.com/ChristianMurphy)
 * docs; cross-db populate #3648
 * docs; update mocha URL #3646 [ojhaujjwal](https://github.com/ojhaujjwal)
 * fixed; call close callback asynchronously #3645
 * docs; virtuals.html issue #3644 [Psarna94](https://github.com/Psarna94)
 * fixed; single embedded doc casting on init #3642
 * docs; validation docs improvements #3640
4.2.9 / 2015-12-02
==================
 * docs; defaults docs #3625
 * fix; nested numeric keys causing an embedded document crash #3623
 * fix; apply path getters before virtual getters #3618
 * fix; casting for arrays in single nested schemas #3616
4.2.8 / 2015-11-25
==================
 * docs; clean up README links #3612 [ReadmeCritic](https://github.com/ReadmeCritic)
 * fix; ESLint improvements #3605 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fix; assigning single nested subdocs #3601
 * docs; describe custom logging functions in `mongoose.set()` docs #3557
4.2.7 / 2015-11-20
==================
 * fixed; readPreference connection string option #3600
 * fixed; pulling from manually populated arrays #3598 #3579
 * docs; FAQ about OverwriteModelError #3597 [stcruy](https://github.com/stcruy)
 * fixed; setting single embedded schemas to null #3596
 * fixed; indexes for single embedded schemas #3594
 * docs; clarify projection for `findOne()` #3593 [gunar](https://github.com/gunar)
 * fixed; .ownerDocument() method on single embedded schemas #3589
 * fixed; properly throw casterror for query on single embedded schema #3580
 * upgraded; mongodb driver -> 2.0.49 for reconnect issue fix #3481
4.2.6 / 2015-11-16
==================
 * fixed; ability to manually populate an array #3575
 * docs; clarify `isAsync` parameter to hooks #3573
 * fixed; use captureStackTrace if possible instead #3571
 * fixed; crash with buffer and update validators #3565 [johnpeb](https://github.com/johnpeb)
 * fixed; update casting with operators overwrite: true #3564
 * fixed; validation with single embedded docs #3562
 * fixed; inline docs inherit parents $type key #3560
 * docs; bad grammar in populate docs #3559 [amaurymedeiros](https://github.com/amaurymedeiros)
 * fixed; properly handle populate option for find() #2321
3.8.37 / 2015-11-16
===================
 * fixed; use retainKeyOrder for cloning update op #3572
4.2.5 / 2015-11-09
==================
 * fixed; handle setting fields in pre update hooks with exec #3549
 * upgraded; ESLint #3547 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; bluebird unhandled rejections with cast errors and .exec #3543
 * fixed; min/max validators handling undefined #3539
 * fixed; standalone mongos connections #3537
 * fixed; call `.toObject()` when setting a single nested doc #3535
 * fixed; single nested docs now have methods #3534
 * fixed; single nested docs with .create() #3533 #3521 [tusbar](https://github.com/tusbar)
 * docs; deep populate docs #3528
 * fixed; deep populate schema ref handling #3507
 * upgraded; mongodb driver -> 2.0.48 for sort overflow issue #3493
 * docs; clarify default ids for discriminators #3482
 * fixed; properly support .update(doc) #3221
4.2.4 / 2015-11-02
==================
 * fixed; upgraded `ms` package for security vulnerability #3524 [fhemberger](https://github.com/fhemberger)
 * fixed; ESlint rules #3517 [ChristianMurphy](https://github.com/ChristianMurphy)
 * docs; typo in aggregation docs #3513 [rafakato](https://github.com/rafakato)
 * fixed; add `dontThrowCastError` option to .update() for promises #3512
 * fixed; don't double-cast buffers in node 4.x #3510 #3496
 * fixed; population with single embedded schemas #3501
 * fixed; pre('set') hooks work properly #3479
 * docs; promises guide #3441
4.2.3 / 2015-10-26
==================
 * docs; remove unreferenced function in middleware.jade #3506
 * fixed; handling auth with no username/password #3500 #3498 #3484 [mleanos](https://github.com/mleanos)
 * fixed; more ESlint rules #3491 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; swallowing exceptions in save callback #3478
 * docs; fixed broken links in subdocs guide #3477
 * fixed; casting booleans to numbers #3475
 * fixed; report CastError for subdoc arrays in findOneAndUpdate #3468
 * fixed; geoNear returns ES6 promise #3458
4.2.2 / 2015-10-22
==================
 * fixed; go back to old pluralization code #3490
4.2.1 / 2015-10-22
==================
 * fixed; pluralization issues #3492 [ChristianMurphy](https://github.com/ChristianMurphy)
4.2.0 / 2015-10-22
==================
 * added; support for skipVersioning for document arrays #3467 [chazmo03](https://github.com/chazmo03)
 * added; ability to customize schema 'type' key #3459 #3245
 * fixed; writeConcern for index builds #3455
 * added; emit event when individual index build starts #3440 [objectiveSee](https://github.com/objectiveSee)
 * added; 'context' option for update validators #3430
 * refactor; pluralization now in separate pluralize-mongoose npm module #3415 [ChristianMurphy](https://github.com/ChristianMurphy)
 * added; customizable error validation messages #3406 [geronime](https://github.com/geronime)
 * added; support for passing 'minimize' option to update #3381
 * added; ability to customize debug logging format #3261
 * added; baseModelName property for discriminator models #3202
 * added; 'emitIndexErrors' option #3174
 * added; 'async' option for aggregation cursor to support buffering #3160
 * added; ability to skip validation for individual save() calls #2981
 * added; single embedded schema support #2689 #585
 * added; depopulate function #2509
4.1.12 / 2015-10-19
===================
 * docs; use readPreference instead of slaveOk for Query.setOptions docs #3471 [buunguyen](https://github.com/buunguyen)
 * fixed; more helpful error when regexp contains null bytes #3456
 * fixed; x509 auth issue #3454 [NoxHarmonium](https://github.com/NoxHarmonium)
3.8.36 / 2015-10-18
===================
 * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer)
4.1.11 / 2015-10-12
===================
 * fixed; update timestamps for update() if they're enabled #3450 [isayme](https://github.com/isayme)
 * fixed; unit test error on node 0.10 #3449 [isayme](https://github.com/isayme)
 * docs; timestamp option docs #3448 [isayme](https://github.com/isayme)
 * docs; fix unexpected indent #3443 [isayme](https://github.com/isayme)
 * fixed; use ES6 promises for Model.prototype.remove() #3442
 * fixed; don't use unused 'safe' option for index builds #3439
 * fixed; elemMatch casting bug #3437 #3435 [DefinitelyCarter](https://github.com/DefinitelyCarter)
 * docs; schema.index docs #3434
 * fixed; exceptions in save() callback getting swallowed on mongodb 2.4 #3371
4.1.10 / 2015-10-05
===================
 * docs; improve virtuals docs to explain virtuals schema option #3433 [zoyaH](https://github.com/zoyaH)
 * docs; MongoDB server version compatibility guide #3427
 * docs; clarify that findById and findByIdAndUpdate fire hooks #3422
 * docs; clean up Model.save() docs #3420
 * fixed; properly handle projection with just id #3407 #3412
 * fixed; infinite loop when database document is corrupted #3405
 * docs; clarify remove middleware #3388
4.1.9 / 2015-09-28
==================
 * docs; minlength and maxlength string validation docs #3368 #3413 [cosmosgenius](https://github.com/cosmosgenius)
 * fixed; linting for infix operators #3397 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; proper casting for $all #3394
 * fixed; unhandled rejection warnings with .create() #3391
 * docs; clarify update validators on paths that aren't explicitly set #3386
 * docs; custom validator examples #2778
4.1.8 / 2015-09-21
==================
 * docs; fixed typo in example #3390 [kmctown](https://github.com/kmctown)
 * fixed; error in toObject() #3387 [guumaster](https://github.com/guumaster)
 * fixed; handling for casting null dates #3383 [alexmingoia](https://github.com/alexmingoia)
 * fixed; passing composite ids to `findByIdAndUpdate` #3380
 * fixed; linting #3376 #3375 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; added NodeJS v4 to Travis #3374 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; casting $elemMatch inside of $not #3373 [gaguirre](https://github.com/gaguirre)
 * fixed; handle case where $slice is 0 #3369
 * fixed; avoid running getters if path is populated #3357
 * fixed; cast documents to objects when setting to a nested path #3346
4.1.7 / 2015-09-14
==================
 * docs; typos in SchemaType documentation #3367 [jasson15](https://github.com/jasson15)
 * fixed; MONGOOSE_DRIVER_PATH env variable again #3360
 * docs; added validateSync docs #3353
 * fixed; set findOne op synchronously in query #3344
 * fixed; handling for `.pull()` on a documentarray without an id #3341
 * fixed; use natural order for cloning update conditions #3338
 * fixed; issue with strict mode casting for mixed type updates #3337
4.1.6 / 2015-09-08
==================
 * fixed; MONGOOSE_DRIVER_PATH env variable #3345 [g13013](https://github.com/g13013)
 * docs; global autoIndex option #3335 [albertorestifo](https://github.com/albertorestifo)
 * docs; model documentation typos #3330
 * fixed; report reason for CastError #3320
 * fixed; .populate() no longer returns true after re-assigning #3308
 * fixed; discriminators with aggregation geoNear #3304
 * docs; discriminator docs #2743
4.1.5 / 2015-09-01
==================
 * fixed; document.remove() removing all docs #3326 #3325
 * fixed; connect() checks for rs_name in options #3299
 * docs; examples for schema.set() #3288
 * fixed; checkKeys issue with bluebird #3286 [gregthegeek](https://github.com/gregthegeek)
4.1.4 / 2015-08-31
==================
 * fixed; ability to set strict: false for update #3305
 * fixed; .create() properly uses ES6 promises #3297
 * fixed; pre hooks on nested subdocs #3291 #3284 [aliatsis](https://github.com/aliatsis)
 * docs; remove unclear text in .remove() docs #3282
 * fixed; pre hooks called twice for 3rd-level nested doc #3281
 * fixed; nested transforms #3279
 * upgraded; mquery -> 1.6.3 #3278 #3272
 * fixed; don't swallow callback errors by default #3273 #3222
 * fixed; properly get nested paths from nested schemas #3265
 * fixed; remove() with id undefined deleting all docs #3260 [thanpolas](https://github.com/thanpolas)
 * fixed; handling for non-numeric projections #3256
 * fixed; findById with id undefined returning first doc #3255
 * fixed; use retainKeyOrder for update #3215
 * added; passRawResult option to findOneAndUpdate for backwards compat #3173
4.1.3 / 2015-08-16
==================
 * fixed; getUpdate() in pre update hooks #3520 [gregthegeek](https://github.com/gregthegeek)
 * fixed; handleArray() ensures arg is an array #3238 [jloveridge](https://github.com/jloveridge)
 * fixed; refresh required path cache when recreating docs #3199
 * fixed; $ operator on unwind aggregation helper #3197
 * fixed; findOneAndUpdate() properly returns raw result as third arg to callback #3173
 * fixed; querystream with dynamic refs #3108
3.8.35 / 2015-08-14
===================
 * fixed; handling for minimize on nested objects #2930
 * fixed; don't crash when schema.path.options undefined #1824
4.1.2 / 2015-08-10
==================
 * fixed; better handling for Jade templates #3241 [kbadk](https://github.com/kbadk)
 * added; ESlint trailing spaces #3234 [ChristianMurphy](https://github.com/ChristianMurphy)
 * added; ESlint #3191 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; properly emit event on disconnect #3183
 * fixed; copy options properly using Query.toConstructor() #3176
 * fixed; setMaxListeners() issue in browser build #3170
 * fixed; node driver -> 2.0.40 to not store undefined keys as null #3169
 * fixed; update validators handle positional operator #3167
 * fixed; handle $all + $elemMatch query casting #3163
 * fixed; post save hooks don't swallow extra args #3155
 * docs; spelling mistake in index.jade #3154
 * fixed; don't crash when toObject() has no fields #3130
 * fixed; apply toObject() recursively for find and update queries #3086 [naoina](https://github.com/naoina)
4.1.1 / 2015-08-03
==================
 * fixed; aggregate exec() crash with no callback #3212 #3198 [jpgarcia](https://github.com/jpgarcia)
 * fixed; pre init hooks now properly synchronous #3207 [burtonjc](https://github.com/burtonjc)
 * fixed; updateValidators doesn't flatten dates #3206 #3194 [victorkohl](https://github.com/victorkohl)
 * fixed; default fields don't make document dirty between saves #3205 [burtonjc](https://github.com/burtonjc)
 * fixed; save passes 0 as numAffected rather than undefined when no change #3195 [burtonjc](https://github.com/burtonjc)
 * fixed; better handling for positional operator in update #3185
 * fixed; use Travis containers #3181 [ChristianMurphy](https://github.com/ChristianMurphy)
 * fixed; leaked variable #3180 [ChristianMurphy](https://github.com/ChristianMurphy)
4.1.0 / 2015-07-24
==================
 * added; `schema.queue()` now public #3193
 * added; raw result as third parameter to findOneAndX callback #3173
 * added; ability to run validateSync() on only certain fields #3153
 * added; subPopulate #3103 [timbur](https://github.com/timbur)
 * added; $isDefault function on documents #3077
 * added; additional properties for built-in validator messages #3063 [KLicheR](https://github.com/KLicheR)
 * added; getQuery() and getUpdate() functions for Query #3013
 * added; export DocumentProvider #2996
 * added; ability to remove path from schema #2993 [JohnnyEstilles](https://github.com/JohnnyEstilles)
 * added; .explain() helper for aggregate #2714
 * added; ability to specify which ES6-compatible promises library mongoose uses #2688
 * added; export Aggregate #1910
4.0.8 / 2015-07-20
==================
 * fixed; assignment with document arrays #3178 [rosston](https://github.com/rosston)
 * docs; remove duplicate paragraph #3164 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * docs; improve findOneAndXYZ parameter descriptions #3159 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * docs; add findOneAndRemove to list of supported middleware #3158
 * docs; clarify ensureIndex #3156
 * fixed; refuse to save/remove document without id #3118
 * fixed; hooks next() no longer accidentally returns promise #3104
 * fixed; strict mode for findOneAndUpdate #2947
 * added; .min.js.gz file for browser component #2806
3.8.34 / 2015-07-20
===================
 * fixed; allow using $rename #3171
 * fixed; no longer modifies update arguments #3008
4.0.7 / 2015-07-11
==================
 * fixed; documentarray id method when using object id #3157 [siboulet](https://github.com/siboulet)
 * docs; improve findById docs #3147
 * fixed; update validators handle null properly #3136 [odeke-em](https://github.com/odeke-em)
 * docs; jsdoc syntax errors #3128 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * docs; fix typo #3126 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * docs; proper formatting in queries.jade #3121 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * docs; correct example for string maxlength validator #3111 [rhmeeuwisse](https://github.com/rhmeeuwisse)
 * fixed; setDefaultsOnInsert with arrays #3107
 * docs; LearnBoost -> Automattic in package.json #3099
 * docs; pre update hook example #3094 [danpe](https://github.com/danpe)
 * docs; clarify query middleware example #3051
 * fixed; ValidationErrors in strict mode #3046
 * fixed; set findOneAndUpdate properties before hooks run #3024
3.8.33 / 2015-07-10
===================
 * upgraded; node driver -> 1.4.38
 * fixed; dont crash when `match` validator undefined
4.0.6 / 2015-06-21
==================
 * upgraded; node driver -> 2.0.34 #3087
 * fixed; apply setters on addToSet, etc #3067 [victorkohl](https://github.com/victorkohl)
 * fixed; missing semicolons #3065 [sokolikp](https://github.com/sokolikp)
 * fixed; proper handling for async doc hooks #3062 [gregthegeek](https://github.com/gregthegeek)
 * fixed; dont set failed populate field to null if other docs are successfully populated #3055 [eloytoro](https://github.com/eloytoro)
 * fixed; setDefaultsOnInsert with document arrays #3034 [taxilian](https://github.com/taxilian)
 * fixed; setters fired on array items #3032
 * fixed; stop validateSync() on first error #3025 [victorkohl](https://github.com/victorkohl)
 * docs; improve query docs #3016
 * fixed; always exclude _id when its deselected #3010
 * fixed; enum validator kind property #3009
 * fixed; mquery collection names #3005
 * docs; clarify mongos option #3000
 * docs; clarify that query builder has a .then() #2995
 * fixed; race condition in dynamic ref #2992
3.8.31 / 2015-06-20
===================
 * fixed; properly handle text search with discriminators and $meta #2166
4.0.5 / 2015-06-05
==================
 * fixed; ObjectIds and buffers when mongodb driver is a sibling dependency #3050 #3048 #3040 #3031 #3020 #2988 #2951
 * fixed; warn user when 'increment' is used in schema #3039
 * fixed; setDefaultsOnInsert with array in schema #3035
 * fixed; dont use default Object toString to cast to string #3030
 * added; npm badge #3020 [odeke-em](https://github.com/odeke-em)
 * fixed; proper handling for calling .set() with a subdoc #2782
 * fixed; dont throw cast error when using $rename on non-string path #1845
3.8.30 / 2015-06-05
===================
 * fixed; enable users to set all options with tailable() #2883
4.0.4 / 2015-05-28
==================
 * docs; findAndModify new parameter correct default value #3012 [JonForest](https://github.com/JonForest)
 * docs; clarify pluralization rules #2999 [anonmily](https://github.com/anonmily)
 * fix; discriminators with schema methods #2978
 * fix; make `isModified` a schema reserved keyword #2975
 * fix; properly fire setters when initializing path with object #2943
 * fix; can use `setDefaultsOnInsert` without specifying `runValidators` #2938
 * fix; always set validation errors `kind` property #2885
 * upgraded; node driver -> 2.0.33 #2865
3.8.29 / 2015-05-27
===================
 * fixed; Handle JSON.stringify properly for nested docs #2990
4.0.3 / 2015-05-13
==================
 * upgraded; mquery -> 1.5.1 #2983
 * docs; clarify context for query middleware #2974
 * docs; fix missing type -> kind rename in History.md #2961
 * fixed; broken ReadPreference include on Heroku #2957
 * docs; correct form for cursor aggregate option #2955
 * fixed; sync post hooks now properly called after function #2949 #2925
 * fixed; fix sub-doc validate() function #2929
 * upgraded; node driver -> 2.0.30 #2926
 * docs; retainKeyOrder for save() #2924
 * docs; fix broken class names #2913
 * fixed; error when using node-clone on a doc #2909
 * fixed; no more hard references to bson #2908 #2906
 * fixed; dont overwrite array values #2907 [naoina](https://github.com/naoina)
 * fixed; use readPreference=primary for findOneAndUpdate #2899 #2823
 * docs; clarify that update validators only run on $set and $unset #2889
 * fixed; set kind consistently for built-in validators #2885
 * docs; single field populated documents #2884
 * fixed; nested objects are now enumerable #2880 [toblerpwn](https://github.com/toblerpwn)
 * fixed; properly populate field when ref, lean, stream used together #2841
 * docs; fixed migration guide jade error #2807
3.8.28 / 2015-05-12
===================
 * fixed; proper handling for toJSON options #2910
 * fixed; dont attach virtuals to embedded docs in update() #2046
4.0.2 / 2015-04-23
==================
 * fixed; error thrown when calling .validate() on subdoc not in an array #2902
 * fixed; rename define() to play nice with webpack #2900 [jspears](https://github.com/jspears)
 * fixed; pre validate called twice with discriminators #2892
 * fixed; .inspect() on mongoose.Types #2875
 * docs; correct callback params for Model.update #2872
 * fixed; setDefaultsOnInsert now works when runValidators not specified #2870
 * fixed; Document now wraps EventEmitter.addListener #2867
 * fixed; call non-hook functions in schema queue #2856
 * fixed; statics can be mocked out for tests #2848 [ninelb](https://github.com/ninelb)
 * upgraded; mquery 1.4.0 for bluebird bug fix #2846
 * fixed; required validators run first #2843
 * docs; improved docs for new option to findAndMody #2838
 * docs; populate example now uses correct field #2837 [swilliams](https://github.com/swilliams)
 * fixed; pre validate changes causing VersionError #2835
 * fixed; get path from correct place when setting CastError #2832
 * docs; improve docs for Model.update() function signature #2827 [irnc](https://github.com/irnc)
 * fixed; populating discriminators #2825 [chetverikov](https://github.com/chetverikov)
 * fixed; discriminators with nested schemas #2821
 * fixed; CastErrors with embedded docs #2819
 * fixed; post save hook context #2816
 * docs; 3.8.x -> 4.x migration guide #2807
 * fixed; proper _distinct copying for query #2765 [cdelauder](https://github.com/cdelauder)
3.8.27 / 2015-04-22
===================
 * fixed; dont duplicate db calls on Q.ninvoke() #2864
 * fixed; Model.find arguments naming in docs #2828
 * fixed; Support ipv6 in connection strings #2298
3.8.26 / 2015-04-07
===================
 * fixed; TypeError when setting date to undefined #2833
 * fixed; handle CastError properly in distinct() with no callback #2786
 * fixed; broken links in queries docs #2779
 * fixed; dont mark buffer as modified when setting type initially #2738
 * fixed; dont crash when using slice with populate #1934
4.0.1 / 2015-03-28
==================
 * fixed; properly handle empty cast doc in update() with promises #2796
 * fixed; unstable warning #2794
 * fixed; findAndModify docs now show new option is false by default #2793
4.0.0 / 2015-03-25
==================
 * fixed; on-the-fly schema docs typo #2783 [artiifix](https://github.com/artiifix)
 * fixed; cast error validation handling #2775 #2766 #2678
 * fixed; discriminators with populate() #2773 #2719 [chetverikov](https://github.com/chetverikov)
 * fixed; increment now a reserved path #2709
 * fixed; avoid sending duplicate object ids in populate() #2683
 * upgraded; mongodb to 2.0.24 to properly emit reconnect event multiple times #2656
4.0.0-rc4 / 2015-03-14
======================
 * fixed; toObject virtuals schema option handled properly #2751
 * fixed; update validators work on document arrays #2733
 * fixed; check for cast errors on $set #2729
 * fixed; instance field set for all schema types #2727 [csdco](https://github.com/csdco)
 * fixed; dont run other validators if required fails #2725
 * fixed; custom getters execute on ref paths #2610
 * fixed; save defaults if they were set when doc was loaded from db #2558
 * fixed; pre validate now runs before pre save #2462
 * fixed; no longer throws errors with --use_strict #2281
3.8.25 / 2015-03-13
===================
 * fixed; debug output reverses order of aggregation keys #2759
 * fixed; $eq is a valid query selector in 3.0 #2752
 * fixed; upgraded node driver to 1.4.32 for handling non-numeric poolSize #2682
 * fixed; update() with overwrite sets _id for nested docs #2658
 * fixed; casting for operators in $elemMatch #2199
4.0.0-rc3 / 2015-02-28
======================
 * fixed; update() pre hooks run before validators #2706
 * fixed; setters not called on arrays of refs #2698 [brandom](https://github.com/brandom)
 * fixed; use node driver 2.0.18 for nodejs 0.12 support #2685
 * fixed; comments reference file that no longer exists #2681
 * fixed; populated() returns _id of manually populated doc #2678
 * added; ability to exclude version key in toObject() #2675
 * fixed; dont allow setting nested path to a string #2592
 * fixed; can cast objects with _id field to ObjectIds #2581
 * fixed; on-the-fly schema getters #2360
 * added; strict option for findOneAndUpdate() #1967
3.8.24 / 2015-02-25
===================
 * fixed; properly apply child schema transforms #2691
 * fixed; make copy of findOneAndUpdate options before modifying #2687
 * fixed; apply defaults when parent path is selected #2670 #2629
 * fixed; properly get ref property for nested paths #2665
 * fixed; node driver makes copy of authenticate options before modifying them #2619
 * fixed; dont block process exit when auth fails #2599
 * fixed; remove redundant clone in update() #2537
4.0.0-rc2 / 2015-02-10
======================
 * added; io.js to travis build
 * removed; browser build dependencies not installed by default
 * added; dynamic refpaths #2640 [chetverikov](https://github.com/chetverikov)
 * fixed; dont call child schema transforms on parent #2639 [chetverikov](https://github.com/chetverikov)
 * fixed; get rid of remove option if new is set in findAndModify #2598
 * fixed; aggregate all document array validation errors #2589
 * fixed; custom setters called when setting value to undefined #1892
3.8.23 / 2015-02-06
===================
 * fixed; unset opts.remove when upsert is true #2519
 * fixed; array saved as object when path is object in array #2442
 * fixed; inline transforms #2440
 * fixed; check for callback in count() #2204
 * fixed; documentation for selecting fields #1534
4.0.0-rc1 / 2015-02-01
======================
 * fixed; use driver 2.0.14
 * changed; use transform: true by default #2245
4.0.0-rc0 / 2015-01-31
===================
 * fixed; wrong order for distinct() params #2628
 * fixed; handling no query argument to remove() #2627
 * fixed; createModel and discriminators #2623 [ashaffer](https://github.com/ashaffer)
 * added; pre('count') middleware #2621
 * fixed; double validation calls on document arrays #2618
 * added; validate() catches cast errors #2611
 * fixed; respect replicaSet parameter in connection string #2609
 * added; can explicitly exclude paths from versioning #2576 [csabapalfi](https://github.com/csabapalfi)
 * upgraded; driver to 2.0.15 #2552
 * fixed; save() handles errors more gracefully in ES6 #2371
 * fixed; undefined is now a valid argument to findOneAndUpdate #2272
 * changed; `new` option to findAndModify ops is false by default #2262
3.8.22 / 2015-01-24
===================
 * upgraded; node-mongodb-native to 1.4.28 #2587 [Climax777](https://github.com/Climax777)
 * added; additional documentation for validators #2449
 * fixed; stack overflow when creating massive arrays #2423
 * fixed; undefined is a valid id for queries #2411
 * fixed; properly create nested schema index when same schema used twice #2322
 * added; link to plugin generator in docs #2085 [huei90](https://github.com/huei90)
 * fixed; optional arguments documentation for findOne() #1971 [nachinius](https://github.com/nachinius)
3.9.7 / 2014-12-19
===================
 * added; proper cursors for aggregate #2539 [changyy](https://github.com/changyy)
 * added; min/max built-in validators for dates #2531 [bshamblen](https://github.com/bshamblen)
 * fixed; save and validate are now reserved keywords #2380
 * added; basic documentation for browser component #2256
 * added; find and findOne hooks (query middleware) #2138
 * fixed; throw a DivergentArrayError when saving positional operator queries #2031
 * added; ability to use options as a document property #1416
 * fixed; document no longer inherits from event emitter and so domain and _events are no longer reserved #1351
 * removed; setProfiling #1349
3.8.21 / 2014-12-18
===================
 * fixed; syntax in index.jade #2517 [elderbas](https://github.com/elderbas)
 * fixed; writable statics #2510 #2528
 * fixed; overwrite and explicit $set casting #2515
3.9.6 / 2014-12-05
===================
 * added; correctly run validators on each element of array when entire array is modified #661 #1227
 * added; castErrors in validation #1013 [jondavidjohn](https://github.com/jondavidjohn)
 * added; specify text indexes in schema fields #1401 [sr527](https://github.com/sr527)
 * added; ability to set field with validators to undefined #1594 [alabid](https://github.com/alabid)
 * added; .create() returns an array when passed an array #1746 [alabid](https://github.com/alabid)
 * added; test suite and docs for use with co and yield #2177 #2474
 * fixed; subdocument toObject() transforms #2447 [chmanie](https://github.com/chmanie)
 * fixed; Model.create() with save errors #2484
 * added; pass options to .save() and .remove() #2494 [jondavidjohn](https://github.com/jondavidjohn)
3.8.20 / 2014-12-01
===================
 * fixed; recursive readPref #2490 [kjvalencik](https://github.com/kjvalencik)
 * fixed; make sure to copy parameters to update() before modifying #2406 [alabid](https://github.com/alabid)
 * fixed; unclear documentation about query callbacks #2319
 * fixed; setting a schema-less field to an empty object #2314 [alabid](https://github.com/alabid)
 * fixed; registering statics and methods for discriminators #2167 [alabid](https://github.com/alabid)
3.9.5 / 2014-11-10
===================
 * added; ability to disable autoIndex on a per-connection basis #1875 [sr527](https://github.com/sr527)
 * fixed; `geoNear()` no longer enforces legacy coordinate pairs - supports GeoJSON #1987 [alabid](https://github.com/alabid)
 * fixed; browser component works when minified with mangled variable names #2302
 * fixed; `doc.errors` now cleared before `validate()` called #2302
 * added; `execPopulate()` function to make `doc.populate()` compatible with promises #2317
 * fixed; `count()` no longer throws an error when used with `sort()` #2374
 * fixed; `save()` no longer recursively calls `save()` on populated fields #2418
3.8.19 / 2014-11-09
===================
 * fixed; make sure to not override subdoc _ids on find #2276 [alabid](https://github.com/alabid)
 * fixed; exception when comparing two documents when one lacks _id #2333 [slawo](https://github.com/slawo)
 * fixed; getters for properties with non-strict schemas #2439 [alabid](https://github.com/alabid)
 * fixed; inconsistent URI format in docs #2414 [sr527](https://github.com/sr527)
3.9.4 / 2014-10-25
==================
 * fixed; statics no longer can be overwritten #2343 [nkcmr](https://github.com/chetverikov)
 * added; ability to set single populated paths to documents #1530
 * added; setDefaultsOnInsert and runValidator options for findOneAndUpdate() #860
3.8.18 / 2014-10-22
==================
 * fixed; Dont use all toObject options in save #2340 [chetverikov](https://github.com/chetverikov)
3.9.3 / 2014-10-01
=================
 * added; support for virtuals that return objects #2294
 * added; ability to manually hydrate POJOs into mongoose objects #2292
 * added; setDefaultsOnInsert and runValidator options for update() #860
3.8.17 / 2014-09-29
==================
 * fixed; use schema options retainKeyOrder in save() #2274
 * fixed; fix skip in populate when limit is set #2252
 * fixed; fix stack overflow when passing MongooseArray to findAndModify #2214
 * fixed; optimize .length usage in populate #2289
3.9.2 / 2014-09-08
==================
 * added; test coverage for browser component #2255
 * added; in-order execution of validators #2243
 * added; custom fields for validators #2132
 * removed; exception thrown when find() used with count() #1950
3.8.16 / 2014-09-08
==================
 * fixed; properly remove modified array paths if array has been overwritten #1638
 * fixed; key check errors #1884
 * fixed; make sure populate on an array always returns a Mongoose array #2214
 * fixed; SSL connections with node 0.11 #2234
 * fixed; return sensible strings for promise errors #2239
3.9.1 / 2014-08-17
==================
 * added; alpha version of browser-side schema validation #2254
 * added; support passing a function to schemas `required` field #2247
 * added; support for setting updatedAt and createdAt timestamps #2227
 * added; document.validate() returns a promise #2131
3.8.15 / 2014-08-17
==================
 * fixed; Replica set connection string example in docs #2246
 * fixed; bubble up parseError event #2229
 * fixed; removed buggy populate cache #2176
 * fixed; dont $inc versionKey if its being $set #1933
 * fixed; cast $or and $and in $pull #1932
 * fixed; properly cast to schema in stream() #1862
 * fixed; memory leak in nested objects #1565 #2211 [devongovett](https://github.com/devongovett)
3.8.14 / 2014-07-26
==================
 * fixed; stringifying MongooseArray shows nested arrays #2002
 * fixed; use populated doc schema in toObject and toJSON by default #2035
 * fixed; dont crash on arrays containing null #2140
 * fixed; model.update w/ upsert has same return values on .exec and promise #2143
 * fixed; better handling for populate limit with multiple documents #2151
 * fixed; dont prevent users from adding weights to text index #2183
 * fixed; helper for aggregation cursor #2187
 * updated; node-mongodb-native to 1.4.7
3.8.13 / 2014-07-15
==================
 * fixed; memory leak with isNew events #2159
 * fixed; docs for overwrite option for update() #2144
 * fixed; storeShard() handles dates properly #2127
 * fixed; sub-doc changes not getting persisted to db after save #2082
 * fixed; populate with _id: 0 actually removes _id instead of setting to undefined #2123
 * fixed; save versionKey on findOneAndUpdate w/ upsert #2122
 * fixed; fix typo in 2.8 docs #2120 [shakirullahi](https://github.com/shakirullahi)
 * fixed; support maxTimeMs #2102 [yuukinajima](https://github.com/yuukinajima)
 * fixed; support $currentDate #2019
 * fixed; $addToSet handles objects without _ids properly #1973
 * fixed; dont crash on invalid nearSphere query #1874
3.8.12 / 2014-05-30
==================
 * fixed; single-server reconnect event fires #1672
 * fixed; sub-docs not saved when pushed into populated array #1794
 * fixed; .set() sometimes converts embedded docs to pojos #1954 [archangel-irk](https://github.com/archangel-irk)
 * fixed; sub-doc changes not getting persisted to db after save #2082
 * fixed; custom getter might cause mongoose to mistakenly think a path is dirty #2100 [pgherveou](https://github.com/pgherveou)
 * fixed; chainable helper for allowDiskUse option in aggregation #2114
3.9.0 (unstable) / 2014-05-22
==================
 * changed; added `domain` to reserved keywords #1338 #2052 [antoinepairet](https://github.com/antoinepairet)
 * added; asynchronous post hooks #1977 #2081 [chopachom](https://github.com/chopachom) [JasonGhent](https://github.com/JasonGhent)
 * added; using model for population, cross-db populate [mihai-chiorean](https://github.com/mihai-chiorean)
 * added; can define a type for schema validators
 * added; `doc.remove()` returns a promise #1619 [refack](https://github.com/refack)
 * added; internal promises for hooks, pre-save hooks run in parallel #1732 [refack](https://github.com/refack)
 * fixed; geoSearch hanging when no results returned #1846 [ghartnett](https://github.com/ghartnett)
 * fixed; do not set .type property on ValidationError, use .kind instead #1323
3.8.11 / 2014-05-22
==================
 * updated; node-mongodb-native to 1.4.5
 * reverted; #2052, fixes #2097
3.8.10 / 2014-05-20
==================
 * updated; node-mongodb-native to 1.4.4
 * fixed; _.isEqual false negatives bug in js-bson #2070
 * fixed; missing check for schema.options #2014
 * fixed; missing support for $position #2024
 * fixed; options object corruption #2049
 * fixed; improvements to virtuals docs #2055
 * fixed; added `domain` to reserved keywords #2052 #1338
3.8.9 / 2014-05-08
==================
 * updated; mquery to 0.7.0
 * updated; node-mongodb-native to 1.4.3
 * fixed; $near failing against MongoDB 2.6
 * fixed; relying on .options() to determine if collection exists
 * fixed; $out aggregate helper
 * fixed; all test failures against MongoDB 2.6.1, with caveat #2065
3.8.8 / 2014-02-22
==================
 * fixed; saving Buffers #1914
 * updated; expose connection states for user-land #1926 [yorkie](https://github.com/yorkie)
 * updated; mquery to 0.5.3
 * updated; added get / set to reserved path list #1903 [tstrimple](https://github.com/tstrimple)
 * docs; README code highlighting, syntax fixes #1930 [IonicaBizau](https://github.com/IonicaBizau)
 * docs; fixes link in the doc at #1925 [kapeels](https://github.com/kapeels)
 * docs; add a missed word 'hook' for the description of the post-hook api #1924 [ipoval](https://github.com/ipoval)
3.8.7 / 2014-02-09
==================
 * fixed; sending safe/read options in Query#exec #1895
 * fixed; findOneAnd..() with sort #1887
3.8.6 / 2014-01-30
==================
 * fixed; setting readPreferences #1895
3.8.5 / 2014-01-23
==================
 * fixed; ssl setting when using URI #1882
 * fixed; findByIdAndUpdate now respects the overwrite option #1809 [owenallenaz](https://github.com/owenallenaz)
3.8.4 / 2014-01-07
==================
 * updated; mongodb driver to 1.3.23
 * updated; mquery to 0.4.1
 * updated; mpromise to 0.4.3
 * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981)
 * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett)
 * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov)
3.8.3 / 2013-12-17
==================
 * fixed; setting empty array with model.update #1838
 * docs; fix url
3.8.2 / 2013-12-14
==================
 * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang)
 * fixed; global var leak #1803
 * fixed; post remove now fires on subdocs #1810
 * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87)
 * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j)
 * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin)
 * tests; improve shard error handling
3.8.1 / 2013-11-19
==================
 * fixed; mishandling of Dates with minimize/getters #1764
 * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack)
 * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung)
 * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung)
 * docs; fix Query api exposure
 * docs; fix return description
 * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman)
 * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69)
3.8.0 / 2013-10-31
==================
 * updated; warn when using an unstable version
 * updated; error message returned in doc.save() #1595
 * updated; mongodb driver to 1.3.19 (fix error swallowing behavior)
 * updated; mquery to 0.3.2
 * updated; mocha to 1.12.0
 * updated; mpromise 0.3.0
 * updated; sliced 0.0.5
 * removed; mongoose.Error.DocumentError (never used)
 * removed; namedscope (undocumented and broken) #679 #642 #455 #379
 * changed; no longer offically supporting node 0.6.x
 * changed; query.within getter is now a method -> query.within()
 * changed; query.intersects getter is now a method -> query.intersects()
 * added; custom error msgs for built-in validators #747
 * added; discriminator support #1647 #1003 [j](https://github.com/j)
 * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack)
 * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing)
 * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing)
 * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing)
 * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing)
 * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing)
 * added; promise support to model.mapReduce()
 * added; promise support to model.ensureIndexes()
 * added; promise support to model.populate()
 * added; benchmarks [ebensing](https://github.com/ebensing)
 * added; publicly exposed connection states #1585
 * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing)
 * added; query method chain validation
 * added; model.update `overwrite` option
 * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing)
 * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing)
 * added; MongooseBuffer#subtype()
 * added; model.create() now returns a promise #1340
 * added; support for `awaitdata` query option
 * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner)
 * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard)
 * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson)
 * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino)
 * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack)
 * fixed; repopulating modified populated paths #1697
 * fixed; doc.equals() when _id option is set to false #1687
 * fixed; strict mode warnings #1686
 * fixed; $near GeoJSON casting #1683
 * fixed; nearSphere GeoJSON query builder
 * fixed; population field selection w/ strings #1669
 * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing)
 * fixed; handle another versioning edge case #1520
 * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing)
 * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann)
 * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing)
 * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing)
 * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j)
 * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing)
 * fixed; model.remove() removes only what is necessary #1649
 * fixed; update() now only runs with cb or explicit true #1644
 * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing)
 * fixed; model.update "overwrite" option works as documented
 * fixed; query#remove() works as documented
 * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing)
 * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing)
 * fixed; benchmarks to actually output valid json
 * deprecated; promise#addBack (use promise#onResolve)
 * deprecated; promise#complete (use promise#fulfill)
 * deprecated; promise#addCallback (use promise#onFulFill)
 * deprecated; promise#addErrback (use promise#onReject)
 * deprecated; query.nearSphere() (use query.near)
 * deprecated; query.center() (use query.circle)
 * deprecated; query.centerSphere() (use query.circle)
 * deprecated; query#slaveOk (use query#read)
 * docs; custom validator messages
 * docs; 10gen -> MongoDB
 * docs; add Date method caveats #1598
 * docs; more validation details
 * docs; state which branch is stable/unstable
 * docs; mention that middleware does not run on Models
 * docs; promise.fulfill()
 * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis)
 * docs; fixed up the README and examples [ebensing](https://github.com/ebensing)
 * website; add "show code" for properties
 * website; move "show code" links down
 * website; update guide
 * website; add unstable docs
 * website; many improvements
 * website; fix copyright #1439
 * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin)
 * tests; refactor 1703
 * tests; add test generator
 * tests; validate formatMessage() throws
 * tests; add script for continuously running tests
 * tests; fixed versioning tests
 * tests; race conditions in tests
 * tests; added for nested and/or queries
 * tests; close some test connections
 * tests; validate db contents
 * tests; remove .only
 * tests; close some test connections
 * tests; validate db contents
 * tests; remove .only
 * tests; replace deprecated method names
 * tests; convert id to string
 * tests; fix sharding tests for MongoDB 2.4.5
 * tests; now 4-5 seconds faster
 * tests; fix race condition
 * make; suppress warning msg in test
 * benchmarks; updated for pull requests
 * examples; improved and expanded [ebensing](https://github.com/ebensing)
3.7.4 (unstable) / 2013-10-01
=============================
 * updated; mquery to 0.3.2
 * removed; mongoose.Error.DocumentError (never used)
 * added; custom error msgs for built-in validators #747
 * added; discriminator support #1647 #1003 [j](https://github.com/j)
 * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack)
 * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack)
 * fixed; repopulating modified populated paths #1697
 * fixed; doc.equals() when _id option is set to false #1687
 * fixed; strict mode warnings #1686
 * fixed; $near GeoJSON casting #1683
 * fixed; nearSphere GeoJSON query builder
 * fixed; population field selection w/ strings #1669
 * docs; custom validator messages
 * docs; 10gen -> MongoDB
 * docs; add Date method caveats #1598
 * docs; more validation details
 * website; add "show code" for properties
 * website; move "show code" links down
 * tests; refactor 1703
 * tests; add test generator
 * tests; validate formatMessage() throws
3.7.3 (unstable) / 2013-08-22
=============================
  * updated; warn when using an unstable version
  * updated; mquery to 0.3.1
  * updated; mocha to 1.12.0
  * updated; mongodb driver to 1.3.19 (fix error swallowing behavior)
  * changed; no longer offically supporting node 0.6.x
  * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing)
  * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing)
  * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing)
  * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing)
  * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing)
  * fixed; handle another versioning edge case #1520
  * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing)
  * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann)
  * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing)
  * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing)
  * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j)
  * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing)
  * make; suppress warning msg in test
  * docs; state which branch is stable/unstable
  * docs; mention that middleware does not run on Models
  * tests; add script for continuously running tests
  * tests; fixed versioning tests
  * benchmarks; updated for pull requests
3.7.2 (unstable) / 2013-08-15
==================
  * fixed; model.remove() removes only what is necessary #1649
  * fixed; update() now only runs with cb or explicit true #1644
  * tests; race conditions in tests
  * website; update guide
3.7.1 (unstable) / 2013-08-13
=============================
  * updated; driver to 1.3.18 (fixes memory leak)
  * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing)
  * added; promise support to model.mapReduce()
  * added; promise support to model.ensureIndexes()
  * added; promise support to model.populate()
  * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing)
  * fixed; model.update "overwrite" option works as documented
  * fixed; query#remove() works as documented
  * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing)
  * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing)
  * fixed; benchmarks to actually output valid json
  * tests; added for nested and/or queries
  * tests; close some test connections
  * tests; validate db contents
  * tests; remove .only
  * tests; close some test connections
  * tests; validate db contents
  * tests; remove .only
  * tests; replace deprecated method names
  * tests; convert id to string
  * docs; promise.fulfill()
3.7.0 (unstable) / 2013-08-05
===================
  * changed; query.within getter is now a method -> query.within()
  * changed; query.intersects getter is now a method -> query.intersects()
  * deprecated; promise#addBack (use promise#onResolve)
  * deprecated; promise#complete (use promise#fulfill)
  * deprecated; promise#addCallback (use promise#onFulFill)
  * deprecated; promise#addErrback (use promise#onReject)
  * deprecated; query.nearSphere() (use query.near)
  * deprecated; query.center() (use query.circle)
  * deprecated; query.centerSphere() (use query.circle)
  * deprecated; query#slaveOk (use query#read)
  * removed; namedscope (undocumented and broken) #679 #642 #455 #379
  * added; benchmarks [ebensing](https://github.com/ebensing)
  * added; publicly exposed connection states #1585
  * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing)
  * added; query method chain validation
  * added; model.update `overwrite` option
  * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing)
  * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing)
  * added; MongooseBuffer#subtype()
  * added; model.create() now returns a promise #1340
  * added; support for `awaitdata` query option
  * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner)
  * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard)
  * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing)
  * updated; error msg in doc.save() #1595
  * updated; bump driver to 1.3.15
  * updated; mpromise 0.3.0
  * updated; sliced 0.0.5
  * tests; fix sharding tests for MongoDB 2.4.5
  * tests; now 4-5 seconds faster
  * tests; fix race condition
  * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis)
  * docs; fixed up the README and examples [ebensing](https://github.com/ebensing)
  * website; add unstable docs
  * website; many improvements
  * website; fix copyright #1439
  * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin)
  * examples; improved and expanded [ebensing](https://github.com/ebensing)
3.6.20 (stable) / 2013-09-23
===================
 * fixed; repopulating modified populated paths #1697
 * fixed; doc.equals w/ _id false #1687
 * fixed; strict mode warning #1686
 * docs; near/nearSphere
3.6.19 (stable) / 2013-09-04
==================
  * fixed; population field selection w/ strings #1669
  * docs; Date method caveats #1598
3.6.18 (stable) / 2013-08-22
===================
  * updated; warn when using an unstable version of mongoose
  * updated; mocha to 1.12.0
  * updated; mongodb driver to 1.3.19 (fix error swallowing behavior)
  * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing)
  * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing)
  * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann)
  * website; update guide
  * website; added documentation for safe:false and versioning interaction
  * docs; mention that middleware dont run on Models
  * docs; fix indexes link
  * make; suppress warning msg in test
  * tests; moar
3.6.17 / 2013-08-13
===================
  * updated; driver to 1.3.18 (fixes memory leak)
  * fixed; casting ref docs on creation #1606
  * docs; query options
3.6.16 / 2013-08-08
===================
  * added; publicly expose connection states #1585
  * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing)
  * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing)
  * updated; MongoDB driver to 1.3.17
  * updated; sliced to 0.0.5
  * website; tweak homepage
  * tests; fixed + added
  * docs; fix some examples
  * docs; multi-mongos support details
  * docs; auto open browser after starting static server
3.6.15 / 2013-07-16
==================
  * added; mongos failover support #1037
  * updated; make schematype return vals return self #1580
  * docs; add note to model.update #571
  * docs; document third param to document.save callback #1536
  * tests; tweek mongos test timeout
3.6.14 / 2013-07-05
===================
  * updated; driver to 1.3.11
  * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing)
  * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt)
  * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano)
  * docs; note about toObject behavior during save()
  * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin)
3.6.13 / 2013-06-27
===================
  * fixed; calling model.distinct without conditions #1541
  * fixed; regression in Query#count() #1542
  * now working on 3.6.13
3.6.12 / 2013-06-25
===================
  * updated; driver to 1.3.10
  * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage)
  * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu)
  * fixed; docArray#id when doc.id is disabled #1492
  * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou)
  * website; fix example
  * website; improve _id disabling example
  * website; fix typo #1494 [dejj](https://github.com/dejj)
  * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon)
  * docs; improve subtypes description
  * docs; clarify _id disabling
  * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger)
  * tests; refactor isSelected checks
  * tests; remove pointless test
  * tests; fixed timeouts
3.6.11 / 2013-05-15
===================
  * updated; driver to 1.3.5
  * fixed; compat w/ Object.create(null) #1484 #1485
  * fixed; cloning objects w/ missing constructors
  * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako)
  * docs; add doc.increment() example
  * docs; add $size example
  * docs; add "distinct" example
3.6.10 / 2013-05-09
==================
  * update driver to 1.3.3
  * fixed; increment() works without other changes #1475
  * website; fix links to posterous
  * docs; fix link #1472
3.6.9 / 2013-05-02
==================
  * fixed; depopulation of mixed documents #1471
  * fixed; use of $options in array #1462
  * tests; fix race condition
  * docs; fix default example
3.6.8 / 2013-04-25
==================
  * updated; driver to 1.3.0
  * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex)
  * tests; 4-5 seconds faster
3.6.7 / 2013-04-19
==================
  * fixed; population regression in 3.6.6 #1444
3.6.6 / 2013-04-18
==================
  * fixed; saving populated new documents #1442
  * fixed; population regession in 3.6.5 #1441
  * website; fix copyright #1439
3.6.5 / 2013-04-15
==================
  * fixed; strict:throw edge case using .set(path, val)
  * fixed; schema.pathType() on some numbericAlpha paths
  * fixed; numbericAlpha path versioning
  * fixed; setting nested mixed paths #1418
  * fixed; setting nested objects with null prop #1326
  * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex)
  * fixed; read pref typos #1422 [kyano](https://github.com/kyano)
  * docs; fix method example
  * website; update faq
  * website; add more deep links
  * website; update poolSize docs
  * website; add 3.6 release notes
  * website; note about keepAlive
3.6.4 / 2013-04-03
==================
  * fixed; +field conflict with $slice #1370
  * fixed; nested deselection conflict #1333
  * fixed; RangeError in ValidationError.toString() #1296
  * fixed; do not save user defined transforms #1415
  * tests; fix race condition
3.6.3 / 2013-04-02
==================
  * fixed; setting subdocuments deeply nested fields #1394
  * fixed; regression: populated streams #1411
  * docs; mention hooks/validation with findAndModify
  * docs; mention auth
  * docs; add more links
  * examples; add document methods example
  * website; display "see" links for properties
  * website; clean up homepage
3.6.2 / 2013-03-29
==================
  * fixed; corrupted sub-doc array #1408
  * fixed; document#update returns a Query #1397
  * docs; readpref strategy
3.6.1 / 2013-03-27
==================
  * added; populate support to findAndModify varients #1395
  * added; text index type to schematypes
  * expose allowed index types as Schema.indexTypes
  * fixed; use of `setMaxListeners` as path
  * fixed; regression in node 0.6 on docs with > 10 arrays
  * fixed; do not alter schema arguments #1364
  * fixed; subdoc#ownerDocument() #1385
  * website; change search id
  * website; add search from google [jackdbernier](https://github.com/jackdbernier)
  * website; fix link
  * website; add 3.5.x docs release
  * website; fix link
  * docs; fix geometry
  * docs; hide internal constructor
  * docs; aggregation does not cast arguments #1399
  * docs; querystream options
  * examples; added for population
3.6.0 / 2013-03-18
==================
  * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach)
  * changed; Buffer arrays can now contain nulls
  * added; QueryStream transform option
  * added; support for authSource driver option
  * added; {mongoose,db}.modelNames()
  * added; $push w/ $slice,$sort support (MongoDB 2.4)
  * added; hashed index type (MongoDB 2.4)
  * added; support for mongodb 2.4 geojson (MongoDB 2.4)
  * added; value at time of validation error
  * added; support for object literal schemas
  * added; bufferCommands schema option
  * added; allow auth option in connections #1360 [geoah](https://github.com/geoah)
  * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9)
  * added; allow adding uncasted docs to populated arrays and properties #570
  * added; doc#populated(path) stores original populated _ids
  * added; lean population #1260
  * added; query.populate() now accepts an options object
  * added; document#populate(opts, callback)
  * added; Model.populate(docs, opts, callback)
  * added; support for rich nested path population
  * added; doc.array.remove(value) subdoc with _id value support #1278
  * added; optionally allow non-strict sets and updates
  * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise)
  * added; promise#then
  * added; promise#end
  * fixed; use of `model` as doc property
  * fixed; lean population #1382
  * fixed; empty object mixed defaults #1380
  * fixed; populate w/ deselected _id using string syntax
  * fixed; attempted save of divergent populated arrays #1334 related
  * fixed; better error msg when attempting toObject as property name
  * fixed; non population buffer casting from doc
  * fixed; setting populated paths #570
  * fixed; casting when added docs to populated arrays #570
  * fixed; prohibit updating arrays selected with $elemMatch #1334
  * fixed; pull / set subdoc combination #1303
  * fixed; multiple bg index creation #1365
  * fixed; manual reconnection to single mongod
  * fixed; Constructor / version exposure #1124
  * fixed; CastError race condition
  * fixed; no longer swallowing misuse of subdoc#invalidate()
  * fixed; utils.clone retains RegExp opts
  * fixed; population of non-schema property
  * fixed; allow updating versionKey #1265
  * fixed; add EventEmitter props to reserved paths #1338
  * fixed; can now deselect populated doc _ids #1331
  * fixed; properly pass subtype to Binary in MongooseBuffer
  * fixed; casting _id from document with non-ObjectId _id
  * fixed; specifying schema type edge case { path: [{type: "String" }] }
  * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock)
  * updated; driver to 1.2.14
  * updated; muri to 0.3.1
  * updated; mpromise to 0.2.1
  * updated; mocha 1.8.1
  * updated; mpath to 0.1.1
  * deprecated; pluralization will die in 4.x
  * refactor; rename private methods to something unusable as doc properties
  * refactor MongooseArray#remove
  * refactor; move expires index to SchemaDate #1328
  * refactor; internal document properties #1171 #1184
  * tests; added
  * docs; indexes
  * docs; validation
  * docs; populate
  * docs; populate
  * docs; add note about stream compatibility with node 0.8
  * docs; fix for private names
  * docs; Buffer -> mongodb.Binary #1363
  * docs; auth options
  * docs; improved
  * website; update FAQ
  * website; add more api links
  * website; add 3.5.x docs to prior releases
  * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier)
  * website; compat with node 0.10
  * website; add news section
  * website; use T for generic type
  * benchmark; make adjustable
3.6.0rc1 / 2013-03-12
======================
  * refactor; rename private methods to something unusable as doc properties
  * added; {mongoose,db}.modelNames()
  * added; $push w/ $slice,$sort support (MongoDB 2.4)
  * added; hashed index type (MongoDB 2.4)
  * added; support for mongodb 2.4 geojson (MongoDB 2.4)
  * added; value at time of validation error
  * added; support for object literal schemas
  * added; bufferCommands schema option
  * added; allow auth option in connections #1360 [geoah](https://github.com/geoah)
  * fixed; lean population #1382
  * fixed; empty object mixed defaults #1380
  * fixed; populate w/ deselected _id using string syntax
  * fixed; attempted save of divergent populated arrays #1334 related
  * fixed; better error msg when attempting toObject as property name
  * fixed; non population buffer casting from doc
  * fixed; setting populated paths #570
  * fixed; casting when added docs to populated arrays #570
  * fixed; prohibit updating arrays selected with $elemMatch #1334
  * fixed; pull / set subdoc combination #1303
  * fixed; multiple bg index creation #1365
  * fixed; manual reconnection to single mongod
  * fixed; Constructor / version exposure #1124
  * fixed; CastError race condition
  * fixed; no longer swallowing misuse of subdoc#invalidate()
  * fixed; utils.clone retains RegExp opts
  * fixed; population of non-schema property
  * fixed; allow updating versionKey #1265
  * fixed; add EventEmitter props to reserved paths #1338
  * fixed; can now deselect populated doc _ids #1331
  * updated; muri to 0.3.1
  * updated; driver to 1.2.12
  * updated; mpromise to 0.2.1
  * deprecated; pluralization will die in 4.x
  * docs; Buffer -> mongodb.Binary #1363
  * docs; auth options
  * docs; improved
  * website; add news section
  * benchmark; make adjustable
3.6.0rc0 / 2013-02-03
======================
  * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach)
  * changed; Buffer arrays can now contain nulls
  * fixed; properly pass subtype to Binary in MongooseBuffer
  * fixed; casting _id from document with non-ObjectId _id
  * fixed; specifying schema type edge case { path: [{type: "String" }] }
  * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock)
  * refactor; move expires index to SchemaDate #1328
  * refactor; internal document properties #1171 #1184
  * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9)
  * added; allow adding uncasted docs to populated arrays and properties #570
  * added; doc#populated(path) stores original populated _ids
  * added; lean population #1260
  * added; query.populate() now accepts an options object
  * added; document#populate(opts, callback)
  * added; Model.populate(docs, opts, callback)
  * added; support for rich nested path population
  * added; doc.array.remove(value) subdoc with _id value support #1278
  * added; optionally allow non-strict sets and updates
  * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise)
  * added; promise#then
  * added; promise#end
  * updated; mocha 1.8.1
  * updated; muri to 0.3.0
  * updated; mpath to 0.1.1
  * updated; docs
3.5.16 / 2013-08-13
===================
  * updated; driver to 1.3.18
3.5.15 / 2013-07-26
==================
  * updated; sliced to 0.0.5
  * updated; driver to 1.3.12
  * fixed; regression in Query#count() due to driver change
  * tests; fixed timeouts
  * tests; handle differing test uris
3.5.14 / 2013-05-15
===================
  * updated; driver to 1.3.5
  * fixed; compat w/ Object.create(null) #1484 #1485
  * fixed; cloning objects missing constructors
  * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako)
3.5.13 / 2013-05-09
==================
  * update driver to 1.3.3
  * fixed; use of $options in array #1462
3.5.12 / 2013-04-25
===================
  * updated; driver to 1.3.0
  * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex)
  * fixed; read pref typos #1422 [kyano](https://github.com/kyano)
3.5.11 / 2013-04-03
==================
  * fixed; +field conflict with $slice #1370
  * fixed; RangeError in ValidationError.toString() #1296
  * fixed; nested deselection conflict #1333
  * remove time from Makefile
3.5.10 / 2013-04-02
==================
  * fixed; setting subdocuments deeply nested fields #1394
  * fixed; do not alter schema arguments #1364
3.5.9 / 2013-03-15
==================
  * updated; driver to 1.2.14
  * added; support for authSource driver option (mongodb 2.4)
  * added; QueryStream transform option (node 0.10 helper)
  * fixed; backport for saving required populated buffers
  * fixed; pull / set subdoc combination #1303
  * fixed; multiple bg index creation #1365
  * test; added for saveable required populated buffers
  * test; added for #1365
  * test; add authSource test
3.5.8 / 2013-03-12
==================
  * added; auth option in connection [geoah](https://github.com/geoah)
  * fixed; CastError race condition
  * docs; add note about stream compatibility with node 0.8
3.5.7 / 2013-02-22
==================
  * updated; driver to 1.2.13
  * updated; muri to 0.3.1 #1347
  * fixed; utils.clone retains RegExp opts #1355
  * fixed; deepEquals RegExp support
  * tests; fix a connection test
  * website; clean up docs [afshinm](https://github.com/afshinm)
  * website; update homepage
  * website; migragtion: emphasize impact of strict docs #1264
3.5.6 / 2013-02-14
==================
  * updated; driver to 1.2.12
  * fixed; properly pass Binary subtype
  * fixed; add EventEmitter props to reserved paths #1338
  * fixed; use correct node engine version
  * fixed; display empty docs as {} in log output #953 follow up
  * improved; "bad $within $box argument" error message
  * populate; add unscientific benchmark
  * website; add stack overflow to help section
  * website; use better code font #1336 [risseraka](https://github.com/risseraka)
  * website; clarify where help is available
  * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas)
  * docs; be specific about _id schema option #1103
  * docs; add ensureIndex error handling example
  * docs; README
  * docs; CONTRIBUTING.md
3.5.5 / 2013-01-29
==================
  * updated; driver to 1.2.11
  * removed; old node < 0.6x shims
  * fixed; documents with Buffer _ids equality
  * fixed; MongooseBuffer properly casts numbers
  * fixed; reopening closed connection on alt host/port #1287
  * docs; fixed typo in Readme #1298 [rened](https://github.com/rened)
  * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn)
  * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq)
  * docs; updated
3.5.4 / 2013-01-07
==================
  * changed; "_pres" & "_posts" are now reserved pathnames #1261
  * updated; driver to 1.2.8
  * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan)
  * website; updated
3.5.3 / 2012-12-26
==================
  * added; support for geo object notation #1257
  * fixed; $within query casting with arrays
  * fixed; unix domain socket support #1254
  * updated; driver to 1.2.7
  * updated; muri to 0.0.5
3.5.2 / 2012-12-17
==================
  * fixed; using auth with replica sets #1253
3.5.1 / 2012-12-12
==================
  * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq)
  * fixed; safer db option checks
  * updated; driver to 1.2.5
  * website; add more examples
  * website; clean up old docs
  * website; fix prev release urls
  * docs; clarify streaming with HTTP responses
3.5.0 / 2012-12-10
==================
  * added; paths to CastErrors #1239
  * added; support for mongodb connection string spec #1187
  * added; post validate event
  * added; Schema#get (to retrieve schema options)
  * added; VersionError #1071
  * added; npmignore [hidekiy](https://github.com/hidekiy)
  * update; driver to 1.2.3
  * fixed; stackoverflow in setter #1234
  * fixed; utils.isObject()
  * fixed; do not clobber user specified driver writeConcern #1227
  * fixed; always pass current document to post hooks
  * fixed; throw error when user attempts to overwrite a model
  * fixed; connection.model only caches on connection #1209
  * fixed; respect conn.model() creation when matching global model exists #1209
  * fixed; passing model name + collection name now always honors collection name
  * fixed; setting virtual field to an empty object #1154
  * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx
  * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210
  * docs; add collection option to schema api docs #1222
  * docs; NOTE about db safe options
  * docs; add post hooks docs
  * docs; connection string options
  * docs; middleware is not executed with Model.remove #1241
  * docs; {g,s}etter introspection #777
  * docs; update validation docs
  * docs; add link to plugins page
  * docs; clarify error returned by unique indexes #1225
  * docs; more detail about disabling autoIndex behavior
  * docs; add homepage section to package (npm docs mongoose)
  * docs; more detail around collection name pluralization #1193
  * website; add .important css
  * website; update models page
  * website; update getting started
  * website; update quick start
3.4.0 / 2012-11-10
==================
  * added; support for generic toJSON/toObject transforms #1160 #1020 #1197
  * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER)
  * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro)
  * changed; adding invalid nested paths to non-objects throws 4216f14
  * changed; fixed; stop invalid function cloning (internal fix)
  * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri)
  * fixed; overwriting of query arguments #1176
  * docs; fix expires examples
  * docs; transforms
  * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge)
  * website; updated
  * tests; added
3.3.1 / 2012-10-11
==================
  * fixed; allow goose.connect(uris, dbname, opts) #1144
  * docs; persist API private checked state across page loads
3.3.0 / 2012-10-10
==================
  * fixed; passing options as 2nd arg to connect() #1144
  * fixed; race condition after no-op save #1139
  * fixed; schema field selection application in findAndModify #1150
  * fixed; directly setting arrays #1126
  * updated; driver to 1.1.11
  * updated; collection pluralization rules [mrickard](https://github.com/mrickard)
  * tests; added
  * docs; updated
3.2.2 / 2012-10-08
==================
  * updated; driver to 1.1.10 #1143
  * updated; use sliced 0.0.3
  * fixed; do not recast embedded docs unnecessarily
  * fixed; expires schema option helper #1132
  * fixed; built in string setters #1131
  * fixed; debug output for Dates/ObjectId properties #1129
  * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde)
  * docs; fix toJSON example #1137
  * docs; add ensureIndex production notes
  * docs; fix spelling
  * docs; add blogposts about v3
  * website; updated
  * removed; undocumented inGroupsOf util
  * tests; added
3.2.1 / 2012-09-28
==================
  * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651
  * docs; updated
  * website; updated
3.2.0 / 2012-09-27
==================
  * added; direct array index assignment with casting support `doc.array.set(index, value)`
  * fixed; QueryStream#resume within same tick as pause() #1116
  * fixed; default value validatation #1109
  * fixed; array splice() not casting #1123
  * fixed; default array construction edge case #1108
  * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti)
  * tests; added
  * website; more documentation
  * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX)
  * website; refactored [guille](https://github.com/guille)
3.1.2 / 2012-09-10
==================
  * added; ReadPreferrence schema option #1097
  * updated; driver to 1.1.7
  * updated; default query batchSize to 1000
  * fixed; we now cast the mapReduce query option #1095
  * fixed; $elemMatch+$in with field selection #1091
  * fixed; properly cast $elemMatch+$in conditions #1100
  * fixed; default field application of subdocs #1027
  * fixed; querystream prematurely dying #1092
  * fixed; querystream never resumes when paused at getMore boundries #1092
  * fixed; querystream occasionally emits data events after destroy #1092
  * fixed; remove unnecessary ObjectId creation in querystream
  * fixed; allow ne(boolean) again #1093
  * docs; add populate/field selection syntax notes
  * docs; add toObject/toJSON options detail
  * docs; `read` schema option
3.1.1 / 2012-08-31
==================
  * updated; driver to 1.1.6
3.1.0 / 2012-08-29
==================
  * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them)
  * added; read pref support (mongodb 2.2) 205a709c
  * added; aggregate support (mongodb 2.2) f3a5bd3d
  * added; virtual {g,s}etter introspection (#1070)
  * updated; docs [brettz9](https://github.com/brettz9)
  * updated; driver to 1.1.5
  * fixed; retain virtual setter return values (#1069)
3.0.3 / 2012-08-23
==================
  * fixed; use of nested paths beginning w/ numbers #1062
  * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy)
  * fixed; simultaneous top and sub level array modifications #1073
  * added; id and _id schema option aliases + tests
  * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc)
  * docs
3.0.2 / 2012-08-17
==================
  * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058)
  * fixed; replset fullsetup event emission
  * fixed; reconnected event for replsets
  * fixed; server reconnection setting discovery
  * fixed; compat with non-schema path props using positional notation (#1048)
  * fixed; setter/casting order (#665)
  * docs; updated
3.0.1 / 2012-08-11
==================
  * fixed; throw Error on bad validators (1044)
  * fixed; typo in EmbeddedDocument#parentArray [lackac]
  * fixed; repair mongoose.SchemaTypes alias
  * updated; docs
3.0.0 / 2012-08-07
==================
  * removed; old subdocument#commit method
  * fixed; setting arrays of matching docs [6924cbc2]
  * fixed; doc!remove event now emits in save order as save for consistency
  * fixed; pre-save hooks no longer fire on subdocuments when validation fails
  * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects
  * added; query#lean() helper
3.0.0rc0 / 2012-08-01
=====================
  * fixed; allow subdoc literal declarations containing "type" pathname (#993)
  * fixed; unsetting a default array (#758)
  * fixed; boolean $in queries (#998)
  * fixed; allow use of `options` as a pathname (#529)
  * fixed; `model` is again a permitted schema path name
  * fixed; field selection option on subdocs (#1022)
  * fixed; handle another edge case with subdoc saving (#975)
  * added; emit save err on model if listening
  * added; MongoDB TTL collection support (#1006)
  * added; $center options support
  * added; $nearSphere and $polygon support
  * updated; driver version to 1.1.2
3.0.0alpha2 / 2012-07-18
=========================
  * changed; index errors are now emitted on their model and passed to an optional callback (#984)
  * fixed; specifying index along with sparse/unique option no longer overwrites (#1004)
  * fixed; never swallow connection errors (#618)
  * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859)
  * fixed; stop needless validation of unchanged/unselected fields (#891)
  * fixed; document#equals behavior of objectids (#974)
  * fixed; honor the minimize schema option (#978)
  * fixed; provide helpful error msgs when reserved schema path is used (#928)
  * fixed; callback to conn#disconnect is optional (#875)
  * fixed; handle missing protocols in connection urls (#987)
  * fixed; validate args to query#where (#969)
  * fixed; saving modified/removed subdocs (#975)
  * fixed; update with $pull from Mixed array (#735)
  * fixed; error with null shard key value
  * fixed; allow unsetting enums (#967)
  * added; support for manual index creation (#984)
  * added; support for disabled auto-indexing (#984)
  * added; support for preserving MongooseArray#sort changes (#752)
  * added; emit state change events on connection
  * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz]
  * added; support for disabled versioning (#977)
  * added; implicit "new" support for models and Schemas
3.0.0alpha1 / 2012-06-15
=========================
  * removed; doc#commit (use doc#markModified)
  * removed; doc.modified getter (#950)
  * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead
  * removed; query alias methods 1149804c
  * removed; MongooseNumber
  * changed; now creating indexes in background by default
  * changed; strict mode now enabled by default (#952)
  * changed; doc#modifiedPaths is now a method (#950)
  * changed; getters no longer cast (#820); casting happens during set
  * fixed; no need to pass updateArg to findOneAndUpdate (#931)
  * fixed: utils.merge bug when merging nested non-objects. [treygriffith]
  * fixed; strict:throw should produce errors in findAndModify (#963)
  * fixed; findAndUpdate no longer overwrites document (#962)
  * fixed; setting default DocumentArrays (#953)
  * fixed; selection of _id with schema deselection (#954)
  * fixed; ensure promise#error emits instanceof Error
  * fixed; CursorStream: No stack overflow on any size result (#929)
  * fixed; doc#remove now passes safe options
  * fixed; invalid use of $set during $pop
  * fixed; array#{$pop,$shift} mirror MongoDB behavior
  * fixed; no longer test non-required vals in string match (#934)
  * fixed; edge case with doc#inspect
  * fixed; setter order (#665)
  * fixed; setting invalid paths in strict mode (#916)
  * fixed; handle docs without id in DocumentArray#id method (#897)
  * fixed; do not save virtuals during model.update (#894)
  * fixed; sub doc toObject virtuals application (#889)
  * fixed; MongooseArray#pull of ObjectId (#881)
  * fixed; handle passing db name with any repl set string
  * fixed; default application of selected fields (#870)
  * fixed; subdoc paths reported in validation errors (#725)
  * fixed; incorrect reported num of affected docs in update ops (#862)
  * fixed; connection assignment in Model#model (#853)
  * fixed; stringifying arrays of docs (#852)
  * fixed; modifying subdoc and parent array works (#842)
  * fixed; passing undefined to next hook (#785)
  * fixed; Query#{update,remove}() works without callbacks (#788)
  * fixed; set/updating nested objects by parent pathname (#843)
  * fixed; allow null in number arrays (#840)
  * fixed; isNew on sub doc after insertion error (#837)
  * fixed; if an insert fails, set isNew back to false [boutell]
  * fixed; isSelected when only _id is selected (#730)
  * fixed; setting an unset default value (#742)
  * fixed; query#sort error messaging (#671)
  * fixed; support for passing $options with $regex
  * added; array of object literal notation in schema creates DocumentArrays
  * added; gt,gte,lt,lte query support for arrays (#902)
  * added; capped collection support (#938)
  * added; document versioning support
  * added; inclusion of deselected schema path (#786)
  * added; non-atomic array#pop
  * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec
  * added; mapReduce support (#678)
  * added; support for a configurable minimize option #to{Object,JSON}(option) (#848)
  * added; support for strict: `throws` [regality]
  * added; support for named schema types (#795)
  * added; to{Object,JSON} schema options (#805)
  * added; findByIdAnd{Update,Remove}()
  * added; findOneAnd{Update,Remove}()
  * added; query.setOptions()
  * added; instance.update() (#794)
  * added; support specifying model in populate() [DanielBaulig]
  * added; `lean` query option [gitfy]
  * added; multi-atomic support to MongooseArray#nonAtomicPush
  * added; support for $set + other $atomic ops on single array
  * added; tests
  * updated; driver to 1.0.2
  * updated; query.sort() syntax to mirror query.select()
  * updated; clearer cast error msg for array numbers
  * updated; docs
  * updated; doc.clone 3x faster (#950)
  * updated; only create _id if necessary (#950)
2.7.3 / 2012-08-01
==================
  * fixed; boolean $in queries (#998)
  * fixed field selection option on subdocs (#1022)
2.7.2 / 2012-07-18
==================
  * fixed; callback to conn#disconnect is optional (#875)
  * fixed; handle missing protocols in connection urls (#987)
  * fixed; saving modified/removed subdocs (#975)
  * updated; tests
2.7.1 / 2012-06-26
===================
  * fixed; sharding: when a document holds a null as a value of the shard key
  * fixed; update() using $pull on an array of Mixed (gh-735)
  * deprecated; MongooseNumber#{inc, increment, decrement} methods
  * tests; now using mocha
2.7.0 / 2012-06-14
===================
  * added; deprecation warnings to methods being removed in 3.x
2.6.8 / 2012-06-14
===================
  * fixed; edge case when using 'options' as a path name (#961)
2.6.7 / 2012-06-08
===================
  * fixed; ensure promise#error always emits instanceof Error
  * fixed; selection of _id w/ another excluded path (#954)
  * fixed; setting default DocumentArrays (#953)
2.6.6 / 2012-06-06
===================
  * fixed; stack overflow in query stream with large result sets (#929)
  * added; $gt, $gte, $lt, $lte support to arrays (#902)
  * fixed; pass option `safe` along to doc#remove() calls
2.6.5 / 2012-05-24
===================
  * fixed; do not save virtuals in Model.update (#894)
  * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley]
  * fixed; setting invalid paths in strict mode (#916)
  * fixed; resetting isNew after insert failure (#837) [boutell]
2.6.4 / 2012-05-15
===================
  * updated; backport string regex $options to 2.x
  * updated; use driver 1.0.2 (performance improvements) (#914)
  * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897)
2.6.3 / 2012-05-03
===================
  * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1
  * updated; driver to 1.0.0
  * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889)
  * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881)
2.6.2 / 2012-04-30
===================
  * fixed; default field application of selected fields (#870)
2.6.1 / 2012-04-30
===================
  * fixed; connection assignment in mongoose#model (#853, #877)
  * fixed; incorrect reported num of affected docs in update ops (#862)
2.6.0 / 2012-04-19
===================
  * updated; hooks.js to 0.2.1
  * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting.
  * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof]
  * fixed; Query#{update,remove}() work without callbacks again (#788)
  * fixed; modifying subdoc along with parent array $atomic op (#842)
2.5.14 / 2012-04-13
===================
  * fixed; setting an unset default value (#742)
  * fixed; doc.isSelected(otherpath) when only _id is selected (#730)
  * updated; docs
2.5.13 / 2012-03-22
===================
  * fixed; failing validation of unselected required paths (#730,#713)
  * fixed; emitting connection error when only one listener (#759)
  * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman]
2.5.12 / 2012-03-21
===================
  * fixed; honor the `safe` option in all ensureIndex calls
  * updated; node-mongodb-native driver to 0.9.9-7
2.5.11 / 2012-03-15
===================
  * added; introspection for getters/setters (#745)
  * updated; node-mongodb-driver to 0.9.9-5
  * added; tailable method to Query (#769) [holic]
  * fixed; Number min/max validation of null (#764) [btamas]
  * added; more flexible user/password connection options (#738) [KarneAsada]
2.5.10 / 2012-03-06
===================
  * updated; node-mongodb-native driver to 0.9.9-4
  * added; Query#comment()
  * fixed; allow unsetting arrays
  * fixed; hooking the set method of subdocuments (#746)
  * fixed; edge case in hooks
  * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera]
  * added; default path selection to SchemaTypes
2.5.9 / 2012-02-22
===================
  * fixed; properly cast nested atomic update operators for sub-documents
2.5.8 / 2012-02-21
===================
  * added; post 'remove' middleware includes model that was removed (#729) [timoxley]
2.5.7 / 2012-02-09
===================
  * fixed; RegExp validators on node >= v0.6.x
2.5.6 / 2012-02-09
===================
  * fixed; emit errors returned from db.collection() on the connection (were being swallowed)
  * added; can add multiple validators in your schema at once (#718) [diogogmt]
  * fixed; strict embedded documents (#717)
  * updated; docs [niemyjski]
  * added; pass number of affected docs back in model.update/save
2.5.5 / 2012-02-03
===================
  * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714)
2.5.4 / 2012-02-03
===================
  * fixed; RangeError: maximum call stack exceed error (#714)
2.5.3 / 2012-02-02
===================
  * added; doc#isSelected(path)
  * added; query#equals()
  * added; beta sharding support
  * added; more descript error msgs (#700) [obeleh]
  * added; document.modifiedPaths (#709) [ljharb]
  * fixed; only functions can be added as getters/setters (#707,704) [ljharb]
2.5.2 / 2012-01-30
===================
  * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness)
  * deprecated; MongooseNumber (will be moved to a separate repo for 3.x)
  * added; init event is emitted on schemas
2.5.1 / 2012-01-27
===================
  * fixed; honor strict schemas in Model.update (#699)
2.5.0 / 2012-01-26
===================
  * added; doc.toJSON calls toJSON on embedded docs when exists [jerem]
  * added; populate support for refs of type Buffer (#686) [jerem]
  * added; $all support for ObjectIds and Dates (#690)
  * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis]
  * fixed; doc construction triggering getters (#685)
  * fixed; MongooseBuffer check in deepEquals (#688)
  * fixed; range error when using Number _ids with `instance.save()` (#691)
  * fixed; isNew on embedded docs edge case (#680)
  * updated; driver to 0.9.8-3
  * updated; expose `model()` method within static methods
2.4.10 / 2012-01-10
===================
  * added; optional getter application in .toObject()/.toJSON() (#412)
  * fixed; nested $operators in $all queries (#670)
  * added; $nor support (#674)
  * fixed; bug when adding nested schema (#662) [paulwe]
2.4.9 / 2012-01-04
===================
  * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes
2.4.8 / 2011-12-22
===================
  * updated; bump -native to 0.9.7.2-5
  * fixed; compatibility with date.js (#646) [chrisleishman]
  * changed; undocumented schema "lax" option to "strict"
  * fixed; default value population for strict schemas
  * updated; the nextTick helper for small performance gain. 1bee2a2
2.4.7 / 2011-12-16
===================
  * fixed; bug in 2.4.6 with path setting
  * updated; bump -native to 0.9.7.2-1
  * added; strict schema option [nw]
2.4.6 / 2011-12-16
===================
  * fixed; conflicting mods on update bug [sirlantis]
  * improved; doc.id getter performance
2.4.5 / 2011-12-14
===================
  * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4
2.4.4 / 2011-12-14
===================
  * fixed; MongooseArray#doAtomics throwing after sliced
2.4.3 / 2011-12-14
===================
  * updated; system.profile schema for MongoDB 2x
2.4.2 / 2011-12-12
===================
  * fixed; partially populating multiple children of subdocs (#639) [kenpratt]
  * fixed; allow Update of numbers to null (#640) [jerem]
2.4.1 / 2011-12-02
===================
  * added; options support for populate() queries
  * updated; -native driver to 0.9.7-1.4
2.4.0 / 2011-11-29
===================
  * added; QueryStreams (#614)
  * added; debug print mode for development
  * added; $within support to Array queries (#586) [ggoodale]
  * added; $centerSphere query support
  * fixed; $within support
  * added; $unset is now used when setting a path to undefined (#519)
  * added; query#batchSize support
  * updated; docs
  * updated; -native driver to 0.9.7-1.3 (provides Windows support)
2.3.13 / 2011-11-15
===================
  * fixed; required validation for Refs (#612) [ded]
  * added; $nearSphere support for Arrays (#610)
2.3.12 / 2011-11-09
===================
  * fixed; regression, objects passed to Model.update should not be changed (#605)
  * fixed; regression, empty Model.update should not be executed
2.3.11 / 2011-11-08
===================
  * fixed; using $elemMatch on arrays of Mixed types (#591)
  * fixed; allow using $regex when querying Arrays (#599)
  * fixed; calling Model.update with no atomic keys (#602)
2.3.10 / 2011-11-05
===================
  * fixed; model.update casting for nested paths works (#542)
2.3.9 / 2011-11-04
==================
  * fixed; deepEquals check for MongooseArray returned false
  * fixed; reset modified flags of embedded docs after save [gitfy]
  * fixed; setting embedded doc with identical values no longer marks modified [gitfy]
  * updated; -native driver to 0.9.6.23 [mlazarov]
  * fixed; Model.update casting (#542, #545, #479)
  * fixed; populated refs no longer fail required validators (#577)
  * fixed; populating refs of objects with custom ids works
  * fixed; $pop & $unset work with Model.update (#574)
  * added; more helpful debugging message for Schema#add (#578)
  * fixed; accessing .id when no _id exists now returns null (#590)
2.3.8 / 2011-10-26
==================
  * added; callback to query#findOne is now optional (#581)
2.3.7 / 2011-10-24
==================
  * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors
2.3.6 / 2011-10-21
==================
  * fixed; exclusion of embedded doc _id from query results (#541)
2.3.5 / 2011-10-19
==================
  * fixed; calling queries without passing a callback works (#569)
  * fixed; populate() works with String and Number _ids too (#568)
2.3.4 / 2011-10-18
==================
  * added; Model.create now accepts an array as a first arg
  * fixed; calling toObject on a DocumentArray with nulls no longer throws
  * fixed; calling inspect on a DocumentArray with nulls no longer throws
  * added; MongooseArray#unshift support
  * fixed; save hooks now fire on embedded documents [gitfy] (#456)
  * updated; -native driver to 0.9.6-22
  * fixed; correctly pass $addToSet op instead of $push
  * fixed; $addToSet properly detects dates
  * fixed; $addToSet with multiple items works
  * updated; better node 0.6 Buffer support
2.3.3 / 2011-10-12
==================
  * fixed; population conditions in multi-query settings [vedmalex] (#563)
  * fixed; now compatible with Node v0.5.x
2.3.2 / 2011-10-11
==================
  * fixed; population of null subdoc properties no longer hangs (#561)
2.3.1 / 2011-10-10
==================
  * added; support for Query filters to populate() [eneko]
  * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey]
  * updated; version of -native driver to 0.9.6-21
  * fixed; prevent query callbacks that throw errors from corrupting -native connection state
2.3.0 / 2011-10-04
==================
  * fixed; nulls as default values for Boolean now works as expected
  * updated; version of -native driver to 0.9.6-20
2.2.4 / 2011-10-03
==================
  * fixed; populate() works when returned array contains undefined/nulls
2.2.3 / 2011-09-29
==================
  * updated; version of -native driver to 0.9.6-19
2.2.2 / 2011-09-28
==================
  * added; $regex support to String [davidandrewcope]
  * added; support for other contexts like repl etc (#535)
  * fixed; clear modified state properly after saving
  * added; $addToSet support to Array
2.2.1 / 2011-09-22
==================
  * more descript error when casting undefined to string
  * updated; version of -native driver to 0.9.6-18
2.2.0 / 2011-09-22
==================
  * fixed; maxListeners warning on schemas with many arrays (#530)
  * changed; return / apply defaults based on fields selected in query (#423)
  * fixed; correctly detect Mixed types within schema arrays (#532)
2.1.4 / 2011-09-20
==================
  * fixed; new private methods that stomped on users code
  * changed; finished removing old "compat" support which did nothing
2.1.3 / 2011-09-16
==================
  * updated; version of -native driver to 0.9.6-15
  * added; emit `error` on connection when open fails [edwardhotchkiss]
  * added; index support to Buffers (thanks justmoon for helping track this down)
  * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting)
2.1.2 / 2011-09-07
==================
  * fixed; Query#find with no args no longer throws
2.1.1 / 2011-09-07
==================
  * added; support Model.count(fn)
  * fixed; compatibility with node >=0.4.0 < 0.4.3
  * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone]
  * added; support for $type queries
  * added; support for Query#or
  * added; more tests
  * optimized populate queries
2.1.0 / 2011-09-01
==================
  * changed; document#validate is a public method
  * fixed; setting number to same value no longer marks modified (#476) [gitfy]
  * fixed; Buffers shouldn't have default vals
  * added; allow specifying collection name in schema (#470) [ixti]
  * fixed; reset modified paths and atomics after saved (#459)
  * fixed; set isNew on embedded docs to false after save
  * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone]
2.0.4 / 2011-08-29
==================
  * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs)
  * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it)
2.0.3 / 2011-08-28
==================
  * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477)
  * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481)
2.0.2 / 2011-08-25
==================
  * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints)
2.0.1 / 2011-08-25
==================
  * Fixed; do not over-write the doc when no valide props exist in Model.update (#473)
2.0.0 / 2011-08-24
===================
  * Added; support for Buffers [justmoon]
  * Changed; improved error handling [maelstrom]
  * Removed: unused utils.erase
  * Fixed; support for passing other context object into Schemas (#234) [Sija]
  * Fixed; getters are no longer circular refs to themselves (#366)
  * Removed; unused compat.js
  * Fixed; getter/setter scopes are set properly
  * Changed; made several private properties more obvious by prefixing _
  * Added; DBRef support [guille]
  * Changed; removed support for multiple collection names per model
  * Fixed; no longer applying setters when document returned from db
  * Changed; default auto_reconnect to true
  * Changed; Query#bind no longer clones the query
  * Fixed; Model.update now accepts $pull, $inc and friends (#404)
  * Added; virtual type option support [nw]
1.8.4 / 2011-08-21
===================
  * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy]
1.8.3 / 2011-08-19
===================
  * Fixed; regression in connection#open [jshaw86]
1.8.2 / 2011-08-17
===================
  * fixed; reset connection.readyState after failure [tomseago]
  * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc)
  * fixed; embedded document query casting
  * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago]
1.8.1 / 2011-08-10
===================
  * fixed; ObjectIds were always marked modified
  * fixed; can now query using document instances
  * fixed; can now query/update using documents with subdocs
1.8.0 / 2011-08-04
===================
  * fixed; can now use $all with String and Number
  * fixed; can query subdoc array with $ne: null
  * fixed; instance.subdocs#id now works with custom _ids
  * fixed; do not apply setters when doc returned from db (change in bad behavior)
1.7.4 / 2011-07-25
===================
  * fixed; sparse now a valid seperate schema option
  * fixed; now catching cast errors in queries
  * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija]
  * fixed; String enum was disallowing null
  * fixed; Find by nested document _id now works (#389)
1.7.3 / 2011-07-16
===================
  * fixed; MongooseArray#indexOf now works with ObjectIds
  * fixed; validation scope now set properly (#418)
  * fixed; added missing colors dependency (#398)
1.7.2 / 2011-07-13
===================
  * changed; node-mongodb-native driver to v0.9.6.7
1.7.1 / 2011-07-12
===================
  * changed; roll back node-mongodb-native driver to v0.9.6.4
1.7.0 / 2011-07-12
===================
  * fixed; collection name misspelling [mathrawka]
  * fixed; 2nd param is required for ReplSetServers [kevinmarvin]
  * fixed; MongooseArray behaves properly with Object.keys
  * changed; node-mongodb-native driver to v0.9.6.6
  * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407)
      - This means invalid data passed to the ObjectId constructor will now error
1.6.0 / 2011-07-07
===================
  * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc
  * fixed; errors occurring when creating indexes now properly emit on db
  * added; $maxDistance support to MongooseArrays
  * fixed; RegExps now work with $all
  * changed; node-mongodb-native driver to v0.9.6.4
  * fixed; model names are now accessible via .modelName
  * added; Query#slaveOk support
1.5.0 / 2011-06-27
===================
  * changed; saving without a callback no longer ignores the error (@bnoguchi)
  * changed; hook-js version bump to 0.1.9
  * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't
             return an error, null is no longer passed.
  * fixed; two memory leaks (@justmoon)
  * added; sparse index support
  * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso)
  * added; options are now passed in model#remote (@JerryLuke)
1.4.0 / 2011-06-10
===================
  * bumped hooks-js dependency (fixes issue passing null as first arg to next())
  * fixed; document#inspect now works properly with nested docs
  * fixed; 'set' now works as a schema attribute (GH-365)
  * fixed; _id is now set properly within pre-init hooks (GH-289)
  * added; Query#distinct / Model#distinct support (GH-155)
  * fixed; embedded docs now can use instance methods (GH-249)
  * fixed; can now overwrite strings conflicting with schema type
1.3.7 / 2011-06-03
===================
  * added MongooseArray#splice support
  * fixed; 'path' is now a valid Schema pathname
  * improved hooks (utilizing https://github.com/bnoguchi/hooks-js)
  * fixed; MongooseArray#$shift now works (never did)
  * fixed; Document.modified no longer throws
  * fixed; modifying subdoc property sets modified paths for subdoc and parent doc
  * fixed; marking subdoc path as modified properly persists the value to the db
  * fixed; RexExps can again be saved ( #357 )
1.3.6 / 2011-05-18
===================
  * fixed; corrected casting for queries against array types
  * added; Document#set now accepts Document instances
1.3.5 / 2011-05-17
===================
  * fixed; $ne queries work properly with single vals
  * added; #inspect() methods to improve console.log output
1.3.4 / 2011-05-17
===================
  * fixed; find by Date works as expected (#336)
  * added; geospatial 2d index support
  * added; support for $near (#309)
  * updated; node-mongodb-native driver
  * fixed; updating numbers work (#342)
  * added; better error msg when try to remove an embedded doc without an _id (#307)
  * added; support for 'on-the-fly' schemas (#227)
  * changed; virtual id getters can now be skipped
  * fixed; .index() called on subdoc schema now works as expected
  * fixed; db.setProfile() now buffers until the db is open (#340)
1.3.3 / 2011-04-27
===================
  * fixed; corrected query casting on nested mixed types
1.3.2 / 2011-04-27
===================
  * fixed; query hints now retain key order
1.3.1 / 2011-04-27
===================
  * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310)
  * fixed; setting nested properties works when sibling prop is named "type"
  * fixed; isModified is now much finer grained when .set() is used (GH-323)
  * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305)
  * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317)
  * fixed; .lowercase() -> .toLowerCase() in pluralize()
  * fixed; updating an embedded document by index works (GH-334)
  * changed; .save() now passes the instance to the callback (GH-294, GH-264)
  * added; can now query system.profile and system.indexes collections
  * added; db.model('system.profile') is now included as a default Schema
  * added; db.setProfiling(level, ms, callback)
  * added; Query#hint() support
  * added; more tests
  * updated node-mongodb-native to 0.9.3
1.3.0 / 2011-04-19
===================
  * changed; save() callbacks now fire only once on failed validation
  * changed; Errors returned from save() callbacks now instances of ValidationError
  * fixed; MongooseArray#indexOf now works properly
1.2.0 / 2011-04-11
===================
  * changed; MongooseNumber now casts empty string to null
1.1.25 / 2011-04-08
===================
  * fixed; post init now fires at proper time
1.1.24 / 2011-04-03
===================
  * fixed; pushing an array onto an Array works on existing docs
1.1.23 / 2011-04-01
===================
  * Added Model#model
1.1.22 / 2011-03-31
===================
  * Fixed; $in queries on mixed types now work
1.1.21 / 2011-03-31
===================
  * Fixed; setting object root to null/undefined works
1.1.20 / 2011-03-31
===================
  * Fixed; setting multiple props on null field works
1.1.19 / 2011-03-31
===================
  * Fixed; no longer using $set on paths to an unexisting fields
1.1.18 / 2011-03-30
===================
  * Fixed; non-mixed type object setters work after initd from null
1.1.17 / 2011-03-30
===================
  * Fixed; nested object property access works when root initd with null value
1.1.16 / 2011-03-28
===================
  * Fixed; empty arrays are now saved
1.1.15 / 2011-03-28
===================
  * Fixed; `null` and `undefined` are set atomically.
1.1.14 / 2011-03-28
===================
  * Changed; more forgiving date casting, accepting '' as null.
1.1.13 / 2011-03-26
===================
  * Fixed setting values as `undefined`.
1.1.12 / 2011-03-26
===================
  * Fixed; nested objects now convert to JSON properly
  * Fixed; setting nested objects directly now works
  * Update node-mongodb-native
1.1.11 / 2011-03-25
===================
  * Fixed for use of `type` as a key.
1.1.10 / 2011-03-23
===================
  * Changed; Make sure to only ensure indexes while connected
1.1.9 / 2011-03-2
==================
  * Fixed; Mixed can now default to empty arrays
  * Fixed; keys by the name 'type' are now valid
  * Fixed; null values retrieved from the database are hydrated as null values.
  * Fixed repeated atomic operations when saving a same document twice.
1.1.8 / 2011-03-23
==================
  * Fixed 'id' overriding. [bnoguchi]
1.1.7 / 2011-03-22
==================
  * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi]
  * Fixed getters/setters for nested virtualsl. [bnoguchi]
1.1.6 / 2011-03-22
==================
  * Only doValidate when path exists in Schema [aheckmann]
  * Allow function defaults for Array types [aheckmann]
  * Fix validation hang [aheckmann]
  * Fix setting of isRequired of SchemaType [aheckmann]
  * Fix SchemaType#required(false) filter [aheckmann]
  * More backwards compatibility [aheckmann]
  * More tests [aheckmann]
1.1.5 / 2011-03-14
==================
  * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets.
  * Improved/extended replica set tests.
1.1.4 / 2011-03-09
==================
  * Fixed; running an empty Query doesn't throw. [aheckmann]
  * Changed; Promise#addBack returns promise. [aheckmann]
  * Added streaming cursor support. [aheckmann]
  * Changed; Query#update defaults to use$SetOnSave now. [brian]
  * Added more docs.
1.1.3 / 2011-03-04
==================
  * Added Promise#resolve [aheckmann]
  * Fixed backward compatibility with nulls [aheckmann]
  * Changed; Query#{run,exec} return promises [aheckmann]
1.1.2 / 2011-03-03
==================
  * Restored Query#exec and added notion of default operation [brian]
  * Fixed ValidatorError messages [brian]
1.1.1 / 2011-03-01
==================
  * Added SchemaType String `lowercase`, `uppercase`, `trim`.
  * Public exports (`Model`, `Document`) and tests.
  * Added ObjectId casting support for `Document`s.
1.1.0 / 2011-02-25
==================
  * Added support for replica sets.
1.0.16 / 2011-02-18
===================
  * Added $nin as another whitelisted $conditional for SchemaArray [brian]
  * Changed #with to #where [brian]
  * Added ability to use $in conditional with Array types [brian]
1.0.15 / 2011-02-18
===================
  * Added `id` virtual getter for documents to easily access the hexString of
  the `_id`.
1.0.14 / 2011-02-17
===================
  * Fix for arrays within subdocuments [brian]
1.0.13 / 2011-02-16
===================
  * Fixed embedded documents saving.
1.0.12 / 2011-02-14
===================
  * Minor refactorings [brian]
1.0.11 / 2011-02-14
===================
  * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian]
  * Named scopes sugar [brian]
1.0.10 / 2011-02-11
===================
  * Updated node-mongodb-native driver [thanks John Allen]
1.0.9 / 2011-02-09
==================
  * Fixed single member arrays as defaults [brian]
1.0.8 / 2011-02-09
==================
  * Fixed for collection-level buffering of commands [gitfy]
  * Fixed `Document#toJSON` [dalejefferson]
  * Fixed `Connection` authentication [robrighter]
  * Fixed clash of accessors in getters/setters [eirikurn]
  * Improved `Model#save` promise handling
1.0.7 / 2011-02-05
==================
  * Fixed memory leak warnings for test suite on 0.3
  * Fixed querying documents that have an array that contain at least one
  specified member. [brian]
  * Fixed default value for Array types (fixes GH-210). [brian]
  * Fixed example code.
1.0.6 / 2011-02-03
==================
  * Fixed `post` middleware
  * Fixed; it's now possible to instantiate a model even when one of the paths maps
  to an undefined value [brian]
1.0.5 / 2011-02-02
==================
  * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian]
  * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian]
  * Fixed; $pullAll now removes said members from array before save (so it acts just
  like pushAll) [brian]
  * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll.
  Moreover, $pull now modifies the array before save to reflect the immediate
  change [brian]
  * Added tests for nested shortcut getters [brian]
  * Added tests that show that Schemas with nested Arrays don't apply defaults
  [brian]
1.0.4 / 2011-02-02
==================
  * Added MongooseNumber#toString
  * Added MongooseNumber unit tests
1.0.3 / 2011-02-02
==================
  * Make sure safe mode works with Model#save
  * Changed Schema options: safe mode is now the default
  * Updated node-mongodb-native to HEAD
1.0.2 / 2011-02-02
==================
  * Added a Model.create shortcut for creating documents. [brian]
  * Fixed; we can now instantiate models with hashes that map to at least one
  null value. [brian]
  * Fixed Schema with more than 2 nested levels. [brian]
1.0.1 / 2011-02-02
==================
  * Improved `MongooseNumber`, works almost like the native except for `typeof`
  not being `'number'`.

+ 322 - 0
src/server/node_modules/mongoose/README.md

@ -0,0 +1,322 @@
# Mongoose
Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
[![Slack Status](http://slack.mongoosejs.io/badge.svg)](http://slack.mongoosejs.io)
[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose)
[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
[![Dependency Status](https://gemnasium.com/Automattic/mongoose.svg)](https://gemnasium.com/Automattic/mongoose)
[![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/vkarpov?utm_source=github&utm_medium=button&utm_term=vkarpov&utm_campaign=github)
## Documentation
[mongoosejs.com](http://mongoosejs.com/)
## Support
  - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
  - [Bug Reports](https://github.com/Automattic/mongoose/issues/)
  - [Mongoose Slack Channel](http://slack.mongoosejs.io/)
  - [Help Forum](http://groups.google.com/group/mongoose-orm)
  - [MongoDB Support](https://docs.mongodb.org/manual/support/)
## Plugins
Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community.
Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin).
## Contributors
View all 200+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md) too!
## Live Examples
<a href="http://code.runnable.com/mongoose" target="_blank"><img src="http://i.imgur.com/4yNYDLI.png"></a>
## Installation
First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then:
```sh
$ npm install mongoose
```
## Stability
The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The [3.8.x docs](http://mongoosejs.com/docs/3.8.x/) are still available.
## Overview
### Connecting to MongoDB
First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
```js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
```
Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._
**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
### Defining a Model
Models are defined through the `Schema` interface.
```js
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
    author    : ObjectId,
    title     : String,
    body      : String,
    date      : Date
});
```
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
* [Middleware](http://mongoosejs.com/docs/middleware.html)
* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
* [Plugins](http://mongoosejs.com/docs/plugins.html)
* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
The following example shows some of these features:
```js
var Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});
// a setter
Comment.path('name').set(function (v) {
  return capitalize(v);
});
// middleware
Comment.pre('save', function (next) {
  notify(this.get('email'));
  next();
});
```
Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
### Accessing a Model
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
```js
var myModel = mongoose.model('ModelName');
```
Or just do it all at once
```js
var MyModel = mongoose.model('ModelName', mySchema);
```
The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use
```js
var MyModel = mongoose.model('Ticket', mySchema);
```
Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection.
Once we have our model, we can then instantiate it, and save it:
```js
var instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
  //
});
```
Or we can find documents from the same collection
```js
MyModel.find({}, function (err, docs) {
  // docs.forEach
});
```
You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
```js
var conn = mongoose.createConnection('your connection string'),
    MyModel = conn.model('ModelName', schema),
    m = new MyModel;
m.save(); // works
```
vs
```js
var conn = mongoose.createConnection('your connection string'),
    MyModel = mongoose.model('ModelName', schema),
    m = new MyModel;
m.save(); // does not work b/c the default connection object was never connected
```
### Embedded Documents
In the first example snippet, we defined a key in the Schema that looks like:
```
comments: [Comment]
```
Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
```js
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
// create a blog post
var post = new BlogPost();
// create a comment
post.comments.push({ title: 'My comment' });
post.save(function (err) {
  if (!err) console.log('Success!');
});
```
The same goes for removing them:
```js
BlogPost.findById(myId, function (err, post) {
  if (!err) {
    post.comments[0].remove();
    post.save(function (err) {
      // do something
    });
  }
});
```
Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap!
### Middleware
See the [docs](http://mongoosejs.com/docs/middleware.html) page.
#### Intercepting and mutating method arguments
You can intercept method arguments via middleware.
For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
```js
schema.pre('set', function (next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);
  // Pass control to the next pre
  next();
});
```
Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
```js
.pre(method, function firstPre (next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next("altered-" + methodArg1.toString(), methodArg2);
});
// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'
  console.log(methodArg2);
  // => 'originalValOfMethodArg2'
  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});
```
#### Schema gotcha
`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
```js
new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});
new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});
```
### Driver Access
Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
notable exception that `YourModel.collection` still buffers
commands. As such, `YourModel.collection.find()` will **not**
return a cursor.
## API Docs
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox)
and [acquit](https://github.com/vkarpov15/acquit).
## License
Copyright (c) 2010 LearnBoost &lt;dev@learnboost.com&gt;
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.

+ 41 - 0
src/server/node_modules/mongoose/examples/README.md

@ -0,0 +1,41 @@
This directory contains runnable sample mongoose programs.
To run:
  - first install [Node.js](http://nodejs.org/)
  - from the root of the project, execute `npm install -d`
  - in the example directory, run `npm install -d`
  - from the command line, execute: `node example.js`, replacing "example.js" with the name of a program.
Goal is to show:
- ~~global schemas~~
- ~~GeoJSON schemas / use (with crs)~~
- text search (once MongoDB removes the "Experimental/beta" label)
- ~~lean queries~~
- ~~statics~~
- methods and statics on subdocs
- custom types
- ~~querybuilder~~
- ~~promises~~
- accessing driver collection, db
- ~~connecting to replica sets~~
- connecting to sharded clusters
- enabling a fail fast mode
- on the fly schemas
- storing files
- ~~map reduce~~
- ~~aggregation~~
- advanced hooks
- using $elemMatch to return a subset of an array
- query casting
- upserts
- pagination
- express + mongoose session handling
- ~~group by (use aggregation)~~
- authentication
- schema migration techniques
- converting documents to plain objects (show transforms)
- how to $unset

+ 103 - 0
src/server/node_modules/mongoose/examples/aggregate/aggregate.js

@ -0,0 +1,103 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
    gender: 'Male',
    likes: ['movies', 'games', 'dogs']
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
    gender: 'Female',
    likes: ['movies', 'birds', 'cats']
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
    gender: 'Male',
    likes: ['tv', 'games', 'rabbits']
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
    gender: 'Female',
    likes: ['books', 'cats', 'dogs']
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
    gender: 'Male',
    likes: ['glasses', 'wine', 'the night']
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) throw err;
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
      // handle error
    }
    // run an aggregate query that will get all of the people who like a given
    // item. To see the full documentation on ways to use the aggregate
    // framework, see http://docs.mongodb.org/manual/core/aggregation/
    Person.aggregate(
      // select the fields we want to deal with
      {$project: {name: 1, likes: 1}},
      // unwind 'likes', which will create a document for each like
      {$unwind: '$likes'},
      // group everything by the like and then add each name with that like to
      // the set for the like
      {$group: {
        _id: {likes: '$likes'},
        likers: {$addToSet: '$name'}
      }},
      function(err, result) {
        if (err) throw err;
        console.log(result);
         /* [
         { _id: { likes: 'the night' }, likers: [ 'alucard' ] },
         { _id: { likes: 'wine' }, likers: [ 'alucard' ] },
         { _id: { likes: 'books' }, likers: [ 'lilly' ] },
         { _id: { likes: 'glasses' }, likers: [ 'alucard' ] },
         { _id: { likes: 'birds' }, likers: [ 'mary' ] },
         { _id: { likes: 'rabbits' }, likers: [ 'bob' ] },
         { _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] },
         { _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] },
         { _id: { likes: 'tv' }, likers: [ 'bob' ] },
         { _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] },
         { _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] }
         ] */
        cleanup();
      });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/aggregate/package.json

@ -0,0 +1,14 @@
{
  "name": "aggregate-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for aggregate example",
  "main": "aggregate.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 17 - 0
src/server/node_modules/mongoose/examples/aggregate/person.js

@ -0,0 +1,17 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date,
    gender: String,
    likes: [String]
  });
  mongoose.model('Person', PersonSchema);
};

+ 77 - 0
src/server/node_modules/mongoose/examples/doc-methods.js

@ -0,0 +1,77 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Schema
 */
var CharacterSchema = Schema({
  name: {
    type: String,
    required: true
  },
  health: {
    type: Number,
    min: 0,
    max: 100
  }
});
/**
 * Methods
 */
CharacterSchema.methods.attack = function() {
  console.log('%s is attacking', this.name);
};
/**
 * Character model
 */
var Character = mongoose.model('Character', CharacterSchema);
/**
 * Connect to the database on localhost with
 * the default port (27017)
 */
var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
var uri = 'mongodb://localhost/' + dbname;
console.log('connecting to %s', uri);
mongoose.connect(uri, function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  example();
});
/**
 * Use case
 */
function example() {
  Character.create({name: 'Link', health: 100}, function(err, link) {
    if (err) return done(err);
    console.log('found', link);
    link.attack(); // 'Link is attacking'
    done();
  });
}
/**
 * Clean up
 */
function done(err) {
  if (err) console.error(err);
  mongoose.connection.db.dropDatabase(function() {
    mongoose.disconnect();
  });
}

+ 1 - 0
src/server/node_modules/mongoose/examples/express/README.md

@ -0,0 +1 @@
Mongoose + Express examples

+ 6 - 0
src/server/node_modules/mongoose/examples/express/connection-sharing/README.md

@ -0,0 +1,6 @@
To run:
- Execute `npm install` from this directory
- Execute `node app.js`
- Navigate to `localhost:8000`

+ 17 - 0
src/server/node_modules/mongoose/examples/express/connection-sharing/app.js

@ -0,0 +1,17 @@
var express = require('express');
var mongoose = require('../../../lib');
var uri = 'mongodb://localhost/mongoose-shared-connection';
global.db = mongoose.createConnection(uri);
var routes = require('./routes');
var app = express();
app.get('/', routes.home);
app.get('/insert', routes.insert);
app.get('/name', routes.modelName);
app.listen(8000, function() {
  console.log('listening on http://localhost:8000');
});

+ 5 - 0
src/server/node_modules/mongoose/examples/express/connection-sharing/modelA.js

@ -0,0 +1,5 @@
var Schema = require('../../../lib').Schema;
var mySchema = Schema({name: String});
/* global db */
module.exports = db.model('MyModel', mySchema);

+ 14 - 0
src/server/node_modules/mongoose/examples/express/connection-sharing/package.json

@ -0,0 +1,14 @@
{
  "name": "connection-sharing",
  "private": "true",
  "version": "0.0.0",
  "description": "ERROR: No README.md file found!",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "express": "3.1.1" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 20 - 0
src/server/node_modules/mongoose/examples/express/connection-sharing/routes.js

@ -0,0 +1,20 @@
var model = require('./modelA');
exports.home = function(req, res, next) {
  model.find(function(err, docs) {
    if (err) return next(err);
    res.send(docs);
  });
};
exports.modelName = function(req, res) {
  res.send('my model name is ' + model.modelName);
};
exports.insert = function(req, res, next) {
  model.create({name: 'inserting ' + Date.now()}, function(err, doc) {
    if (err) return next(err);
    res.send(doc);
  });
};

+ 22 - 0
src/server/node_modules/mongoose/examples/geospatial/geoJSONSchema.js

@ -0,0 +1,22 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  // NOTE : This object must conform *precisely* to the geoJSON specification
  // you cannot embed a geoJSON doc inside a model or anything like that- IT
  // MUST BE VANILLA
  var LocationObject = new Schema({
    loc: {
      type: {type: String},
      coordinates: []
    }
  });
  // define the index
  LocationObject.index({loc: '2dsphere'});
  mongoose.model('Location', LocationObject);
};

+ 56 - 0
src/server/node_modules/mongoose/examples/geospatial/geoJSONexample.js

@ -0,0 +1,56 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./geoJSONSchema.js')();
var Location = mongoose.model('Location');
// define some dummy data
// note: the type can be Point, LineString, or Polygon
var data = [
  {loc: {type: 'Point', coordinates: [-20.0, 5.0]}},
  {loc: {type: 'Point', coordinates: [6.0, 10.0]}},
  {loc: {type: 'Point', coordinates: [34.0, -50.0]}},
  {loc: {type: 'Point', coordinates: [-100.0, 70.0]}},
  {loc: {type: 'Point', coordinates: [38.0, 38.0]}}
];
mongoose.connect('mongodb://localhost/locations', function(err) {
  if (err) {
    throw err;
  }
  Location.on('index', function(err) {
    if (err) {
      throw err;
    }
    // create all of the dummy locations
    async.each(data, function(item, cb) {
      Location.create(item, cb);
    }, function(err) {
      if (err) {
        throw err;
      }
      // create the location we want to search for
      var coords = {type: 'Point', coordinates: [-5, 5]};
      // search for it
      Location.find({loc: {$near: coords}}).limit(1).exec(function(err, res) {
        if (err) {
          throw err;
        }
        console.log('Closest to %s is %s', JSON.stringify(coords), res);
        cleanup();
      });
    });
  });
});
function cleanup() {
  Location.remove(function() {
    mongoose.disconnect();
  });
}

+ 100 - 0
src/server/node_modules/mongoose/examples/geospatial/geospatial.js

@ -0,0 +1,100 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
    gender: 'Male',
    likes: ['movies', 'games', 'dogs'],
    loc: [0, 0]
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
    gender: 'Female',
    likes: ['movies', 'birds', 'cats'],
    loc: [1, 1]
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
    gender: 'Male',
    likes: ['tv', 'games', 'rabbits'],
    loc: [3, 3]
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
    gender: 'Female',
    likes: ['books', 'cats', 'dogs'],
    loc: [6, 6]
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
    gender: 'Male',
    likes: ['glasses', 'wine', 'the night'],
    loc: [10, 10]
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) {
    throw err;
  }
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
      // handler error
    }
    // let's find the closest person to bob
    Person.find({name: 'bob'}, function(err, res) {
      if (err) {
        throw err;
      }
      res[0].findClosest(function(err, closest) {
        if (err) {
          throw err;
        }
        console.log('%s is closest to %s', res[0].name, closest);
        // we can also just query straight off of the model. For more
        // information about geospatial queries and indexes, see
        // http://docs.mongodb.org/manual/applications/geospatial-indexes/
        var coords = [7, 7];
        Person.find({loc: {$nearSphere: coords}}).limit(1).exec(function(err, res) {
          console.log('Closest to %s is %s', coords, res);
          cleanup();
        });
      });
    });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/geospatial/package.json

@ -0,0 +1,14 @@
{
  "name": "geospatial-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for geospatial example",
  "main": "geospatial.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 27 - 0
src/server/node_modules/mongoose/examples/geospatial/person.js

@ -0,0 +1,27 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date,
    gender: String,
    likes: [String],
    // define the geospatial field
    loc: {type: [Number], index: '2d'}
  });
  // define a method to find the closest person
  PersonSchema.methods.findClosest = function(cb) {
    return this.model('Person').find({
      loc: {$nearSphere: this.loc},
      name: {$ne: this.name}
    }).limit(1).exec(cb);
  };
  mongoose.model('Person', PersonSchema);
};

+ 47 - 0
src/server/node_modules/mongoose/examples/globalschemas/gs_example.js

@ -0,0 +1,47 @@
var mongoose = require('../../lib');
// import the global schema, this can be done in any file that needs the model
require('./person.js')();
// grab the person model object
var Person = mongoose.model('Person');
// connect to a server to do a quick write / read example
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) {
    throw err;
  }
  Person.create({
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25))
  }, function(err, bill) {
    if (err) {
      throw err;
    }
    console.log('People added to db: %s', bill.toString());
    Person.find({}, function(err, people) {
      if (err) {
        throw err;
      }
      people.forEach(function(person) {
        console.log('People in the db: %s', person.toString());
      });
      // make sure to clean things up after we're done
      setTimeout(function() {
        cleanup();
      }, 2000);
    });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/globalschemas/person.js

@ -0,0 +1,14 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date
  });
  mongoose.model('Person', PersonSchema);
};

+ 84 - 0
src/server/node_modules/mongoose/examples/lean/lean.js

@ -0,0 +1,84 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
    gender: 'Male',
    likes: ['movies', 'games', 'dogs']
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
    gender: 'Female',
    likes: ['movies', 'birds', 'cats']
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
    gender: 'Male',
    likes: ['tv', 'games', 'rabbits']
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
    gender: 'Female',
    likes: ['books', 'cats', 'dogs']
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
    gender: 'Male',
    likes: ['glasses', 'wine', 'the night']
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) throw err;
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
      // handle error
    }
    // lean queries return just plain javascript objects, not
    // MongooseDocuments. This makes them good for high performance read
    // situations
    // when using .lean() the default is true, but you can explicitly set the
    // value by passing in a boolean value. IE. .lean(false)
    var q = Person.find({age: {$lt: 1000}}).sort('age').limit(2).lean();
    q.exec(function(err, results) {
      if (err) throw err;
      console.log('Are the results MongooseDocuments?: %s', results[0] instanceof mongoose.Document);
      console.log(results);
      cleanup();
    });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/lean/package.json

@ -0,0 +1,14 @@
{
  "name": "lean-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for lean example",
  "main": "lean.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 16 - 0
src/server/node_modules/mongoose/examples/lean/person.js

@ -0,0 +1,16 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date,
    gender: String,
    likes: [String]
  });
  mongoose.model('Person', PersonSchema);
};

+ 100 - 0
src/server/node_modules/mongoose/examples/mapreduce/mapreduce.js

@ -0,0 +1,100 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
    gender: 'Male'
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
    gender: 'Female'
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
    gender: 'Male'
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
    gender: 'Female'
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
    gender: 'Male'
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) throw err;
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
      // handle error
    }
    // alright, simple map reduce example. We will find the total ages of each
    // gender
    // create the options object
    var o = {};
    o.map = function() {
      // in this function, 'this' refers to the current document being
      // processed. Return the (gender, age) tuple using
      /* global emit */
      emit(this.gender, this.age);
    };
    // the reduce function receives the array of ages that are grouped by the
    // id, which in this case is the gender
    o.reduce = function(id, ages) {
      return Array.sum(ages);
    };
    // other options that can be specified
    // o.query = { age : { $lt : 1000 }}; // the query object
    // o.limit = 3; // max number of documents
    // o.keeptemp = true; // default is false, specifies whether to keep temp data
    // o.finalize = someFunc; // function called after reduce
    // o.scope = {}; // the scope variable exposed to map/reduce/finalize
    // o.jsMode = true; // default is false, force execution to stay in JS
    o.verbose = true; // default is false, provide stats on the job
    // o.out = {}; // objects to specify where output goes, by default is
                   // returned, but can also be stored in a new collection
                   // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce
    Person.mapReduce(o, function(err, results, stats) {
      console.log('map reduce took %d ms', stats.processtime);
      console.log(results);
      cleanup();
    });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/mapreduce/package.json

@ -0,0 +1,14 @@
{
  "name": "map-reduce-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for map reduce example",
  "main": "mapreduce.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 16 - 0
src/server/node_modules/mongoose/examples/mapreduce/person.js

@ -0,0 +1,16 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date,
    gender: String
  });
  mongoose.model('Person', PersonSchema);
};

+ 134 - 0
src/server/node_modules/mongoose/examples/population/population-across-three-collections.js

@ -0,0 +1,134 @@
var assert = require('assert');
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Types.ObjectId;
/**
 * Connect to the db
 */
var dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random();
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function() {
  console.error('connection error', arguments);
});
/**
 * Schemas
 */
var user = new Schema({
  name: String,
  friends: [{
    type: Schema.ObjectId,
    ref: 'User'
  }]
});
var User = mongoose.model('User', user);
var blogpost = Schema({
  title: String,
  tags: [String],
  author: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});
var BlogPost = mongoose.model('BlogPost', blogpost);
/**
 * example
 */
mongoose.connection.on('open', function() {
  /**
   * Generate data
   */
  var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId];
  var users = [];
  users.push({
    _id: userIds[0],
    name: 'mary',
    friends: [userIds[1], userIds[2], userIds[3]]
  });
  users.push({
    _id: userIds[1],
    name: 'bob',
    friends: [userIds[0], userIds[2], userIds[3]]
  });
  users.push({
    _id: userIds[2],
    name: 'joe',
    friends: [userIds[0], userIds[1], userIds[3]]
  });
  users.push({
    _id: userIds[3],
    name: 'sally',
    friends: [userIds[0], userIds[1], userIds[2]]
  });
  User.create(users, function(err) {
    assert.ifError(err);
    var blogposts = [];
    blogposts.push({
      title: 'blog 1',
      tags: ['fun', 'cool'],
      author: userIds[3]
    });
    blogposts.push({
      title: 'blog 2',
      tags: ['cool'],
      author: userIds[1]
    });
    blogposts.push({
      title: 'blog 3',
      tags: ['fun', 'odd'],
      author: userIds[2]
    });
    BlogPost.create(blogposts, function(err) {
      assert.ifError(err);
      /**
       * Population
       */
      BlogPost
      .find({tags: 'fun'})
      .lean()
      .populate('author')
      .exec(function(err, docs) {
        assert.ifError(err);
        /**
         * Populate the populated documents
         */
        var opts = {
          path: 'author.friends',
          select: 'name',
          options: {limit: 2}
        };
        BlogPost.populate(docs, opts, function(err, docs) {
          assert.ifError(err);
          console.log('populated');
          var s = require('util').inspect(docs, {depth: null, colors: true});
          console.log(s);
          done();
        });
      });
    });
  });
});
function done(err) {
  if (err) console.error(err.stack);
  mongoose.connection.db.dropDatabase(function() {
    mongoose.connection.close();
  });
}

+ 103 - 0
src/server/node_modules/mongoose/examples/population/population-basic.js

@ -0,0 +1,103 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Console schema
 */
var consoleSchema = Schema({
  name: String,
  manufacturer: String,
  released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
 * Game schema
 */
var gameSchema = Schema({
  name: String,
  developer: String,
  released: Date,
  consoles: [{
    type: Schema.Types.ObjectId,
    ref: 'Console'
  }]
});
var Game = mongoose.model('Game', gameSchema);
/**
 * Connect to the console database on localhost with
 * the default port (27017)
 */
mongoose.connect('mongodb://localhost/console', function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  createData();
});
/**
 * Data generation
 */
function createData() {
  Console.create(
    {
      name: 'Nintendo 64',
      manufacturer: 'Nintendo',
      released: 'September 29, 1996'
    },
    function(err, nintendo64) {
      if (err) return done(err);
      Game.create({
        name: 'Legend of Zelda: Ocarina of Time',
        developer: 'Nintendo',
        released: new Date('November 21, 1998'),
        consoles: [nintendo64]
      },
      function(err) {
        if (err) return done(err);
        example();
      });
    }
  );
}
/**
 * Population
 */
function example() {
  Game
  .findOne({name: /^Legend of Zelda/})
  .populate('consoles')
  .exec(function(err, ocinara) {
    if (err) return done(err);
    console.log(
      '"%s" was released for the %s on %s',
      ocinara.name,
      ocinara.consoles[0].name,
      ocinara.released.toLocaleDateString()
    );
    done();
  });
}
function done(err) {
  if (err) console.error(err);
  Console.remove(function() {
    Game.remove(function() {
      mongoose.disconnect();
    });
  });
}

+ 109 - 0
src/server/node_modules/mongoose/examples/population/population-of-existing-doc.js

@ -0,0 +1,109 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Console schema
 */
var consoleSchema = Schema({
  name: String,
  manufacturer: String,
  released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
 * Game schema
 */
var gameSchema = Schema({
  name: String,
  developer: String,
  released: Date,
  consoles: [{
    type: Schema.Types.ObjectId,
    ref: 'Console'
  }]
});
var Game = mongoose.model('Game', gameSchema);
/**
 * Connect to the console database on localhost with
 * the default port (27017)
 */
mongoose.connect('mongodb://localhost/console', function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  createData();
});
/**
 * Data generation
 */
function createData() {
  Console.create(
    {
      name: 'Nintendo 64',
      manufacturer: 'Nintendo',
      released: 'September 29, 1996'
    },
    function(err, nintendo64) {
      if (err) return done(err);
      Game.create({
        name: 'Legend of Zelda: Ocarina of Time',
        developer: 'Nintendo',
        released: new Date('November 21, 1998'),
        consoles: [nintendo64]
      },
      function(err) {
        if (err) return done(err);
        example();
      });
    }
  );
}
/**
 * Population
 */
function example() {
  Game
  .findOne({name: /^Legend of Zelda/})
  .exec(function(err, ocinara) {
    if (err) return done(err);
    console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]);
    // population of existing document
    ocinara.populate('consoles', function(err) {
      if (err) return done(err);
      console.log(
        '"%s" was released for the %s on %s',
        ocinara.name,
        ocinara.consoles[0].name,
        ocinara.released.toLocaleDateString()
      );
      done();
    });
  });
}
function done(err) {
  if (err) console.error(err);
  Console.remove(function() {
    Game.remove(function() {
      mongoose.disconnect();
    });
  });
}

+ 124 - 0
src/server/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js

@ -0,0 +1,124 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Console schema
 */
var consoleSchema = Schema({
  name: String,
  manufacturer: String,
  released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
 * Game schema
 */
var gameSchema = Schema({
  name: String,
  developer: String,
  released: Date,
  consoles: [{
    type: Schema.Types.ObjectId,
    ref: 'Console'
  }]
});
var Game = mongoose.model('Game', gameSchema);
/**
 * Connect to the console database on localhost with
 * the default port (27017)
 */
mongoose.connect('mongodb://localhost/console', function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  createData();
});
/**
 * Data generation
 */
function createData() {
  Console.create(
    {
      name: 'Nintendo 64',
      manufacturer: 'Nintendo',
      released: 'September 29, 1996'
    },
    {
      name: 'Super Nintendo',
      manufacturer: 'Nintendo',
      released: 'August 23, 1991'
    },
    function(err, nintendo64, superNintendo) {
      if (err) return done(err);
      Game.create(
        {
          name: 'Legend of Zelda: Ocarina of Time',
          developer: 'Nintendo',
          released: new Date('November 21, 1998'),
          consoles: [nintendo64]
        },
        {
          name: 'Mario Kart',
          developer: 'Nintendo',
          released: 'September 1, 1992',
          consoles: [superNintendo]
        },
        function(err) {
          if (err) return done(err);
          example();
        }
      );
    }
  );
}
/**
 * Population
 */
function example() {
  Game
  .find({})
  .exec(function(err, games) {
    if (err) return done(err);
    console.log('found %d games', games.length);
    var options = {path: 'consoles', select: 'name released -_id'};
    Game.populate(games, options, function(err, games) {
      if (err) return done(err);
      games.forEach(function(game) {
        console.log(
          '"%s" was released for the %s on %s',
          game.name,
          game.consoles[0].name,
          game.released.toLocaleDateString()
        );
      });
      done();
    });
  });
}
function done(err) {
  if (err) console.error(err);
  Console.remove(function() {
    Game.remove(function() {
      mongoose.disconnect();
    });
  });
}

+ 138 - 0
src/server/node_modules/mongoose/examples/population/population-options.js

@ -0,0 +1,138 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Console schema
 */
var consoleSchema = Schema({
  name: String,
  manufacturer: String,
  released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
 * Game schema
 */
var gameSchema = Schema({
  name: String,
  developer: String,
  released: Date,
  consoles: [{
    type: Schema.Types.ObjectId,
    ref: 'Console'
  }]
});
var Game = mongoose.model('Game', gameSchema);
/**
 * Connect to the console database on localhost with
 * the default port (27017)
 */
mongoose.connect('mongodb://localhost/console', function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  createData();
});
/**
 * Data generation
 */
function createData() {
  Console.create(
    {
      name: 'Nintendo 64',
      manufacturer: 'Nintendo',
      released: 'September 29, 1996'
    },
    {
      name: 'Super Nintendo',
      manufacturer: 'Nintendo',
      released: 'August 23, 1991'
    },
    {
      name: 'XBOX 360',
      manufacturer: 'Microsoft',
      released: 'November 22, 2005'
    },
    function(err, nintendo64, superNintendo, xbox360) {
      if (err) return done(err);
      Game.create(
        {
          name: 'Legend of Zelda: Ocarina of Time',
          developer: 'Nintendo',
          released: new Date('November 21, 1998'),
          consoles: [nintendo64]
        },
        {
          name: 'Mario Kart',
          developer: 'Nintendo',
          released: 'September 1, 1992',
          consoles: [superNintendo]
        },
        {
          name: 'Perfect Dark Zero',
          developer: 'Rare',
          released: 'November 17, 2005',
          consoles: [xbox360]
        },
        function(err) {
          if (err) return done(err);
          example();
        }
      );
    }
  );
}
/**
 * Population
 */
function example() {
  Game
  .find({})
  .populate({
    path: 'consoles',
    match: {manufacturer: 'Nintendo'},
    select: 'name',
    options: {comment: 'population'}
  })
  .exec(function(err, games) {
    if (err) return done(err);
    games.forEach(function(game) {
      console.log(
        '"%s" was released for the %s on %s',
        game.name,
        game.consoles.length ? game.consoles[0].name : '??',
        game.released.toLocaleDateString()
      );
    });
    return done();
  });
}
/**
 * Clean up
 */
function done(err) {
  if (err) console.error(err);
  Console.remove(function() {
    Game.remove(function() {
      mongoose.disconnect();
    });
  });
}

+ 106 - 0
src/server/node_modules/mongoose/examples/population/population-plain-objects.js

@ -0,0 +1,106 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
 * Console schema
 */
var consoleSchema = Schema({
  name: String,
  manufacturer: String,
  released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
 * Game schema
 */
var gameSchema = Schema({
  name: String,
  developer: String,
  released: Date,
  consoles: [{
    type: Schema.Types.ObjectId,
    ref: 'Console'
  }]
});
var Game = mongoose.model('Game', gameSchema);
/**
 * Connect to the console database on localhost with
 * the default port (27017)
 */
mongoose.connect('mongodb://localhost/console', function(err) {
  // if we failed to connect, abort
  if (err) throw err;
  // we connected ok
  createData();
});
/**
 * Data generation
 */
function createData() {
  Console.create(
    {
      name: 'Nintendo 64',
      manufacturer: 'Nintendo',
      released: 'September 29, 1996'
    },
    function(err, nintendo64) {
      if (err) return done(err);
      Game.create(
        {
          name: 'Legend of Zelda: Ocarina of Time',
          developer: 'Nintendo',
          released: new Date('November 21, 1998'),
          consoles: [nintendo64]
        },
        function(err) {
          if (err) return done(err);
          example();
        }
      );
    }
  );
}
/**
 * Population
 */
function example() {
  Game
  .findOne({name: /^Legend of Zelda/})
  .populate('consoles')
  .lean() // just return plain objects, not documents wrapped by mongoose
  .exec(function(err, ocinara) {
    if (err) return done(err);
    console.log(
      '"%s" was released for the %s on %s',
      ocinara.name,
      ocinara.consoles[0].name,
      ocinara.released.toLocaleDateString()
    );
    done();
  });
}
function done(err) {
  if (err) console.error(err);
  Console.remove(function() {
    Game.remove(function() {
      mongoose.disconnect();
    });
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/promises/package.json

@ -0,0 +1,14 @@
{
  "name": "promise-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for promise example",
  "main": "promise.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 15 - 0
src/server/node_modules/mongoose/examples/promises/person.js

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date
  });
  mongoose.model('Person', PersonSchema);
};

+ 94 - 0
src/server/node_modules/mongoose/examples/promises/promise.js

@ -0,0 +1,94 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25))
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30))
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21))
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26))
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000))
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) {
    throw err;
  }
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
      // handle error
    }
    // create a promise (get one from the query builder)
    var prom = Person.find({age: {$lt: 1000}}).exec();
    // add a callback on the promise. This will be called on both error and
    // complete
    prom.addBack(function() {
      console.log('completed');
    });
    // add a callback that is only called on complete (success) events
    prom.addCallback(function() {
      console.log('Successful Completion!');
    });
    // add a callback that is only called on err (rejected) events
    prom.addErrback(function() {
      console.log('Fail Boat');
    });
    // you can chain things just like in the promise/A+ spec
    // note: each then() is returning a new promise, so the above methods
    // that we defined will all fire after the initial promise is fulfilled
    prom.then(function(people) {
      // just getting the stuff for the next query
      var ids = people.map(function(p) {
        return p._id;
      });
      // return the next promise
      return Person.find({_id: {$nin: ids}}).exec();
    }).then(function(oldest) {
      console.log('Oldest person is: %s', oldest);
    }).then(cleanup);
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/querybuilder/package.json

@ -0,0 +1,14 @@
{
  "name": "query-builder-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for query builder example",
  "main": "querybuilder.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 15 - 0
src/server/node_modules/mongoose/examples/querybuilder/person.js

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date
  });
  mongoose.model('Person', PersonSchema);
};

+ 79 - 0
src/server/node_modules/mongoose/examples/querybuilder/querybuilder.js

@ -0,0 +1,79 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25))
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30))
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21))
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26))
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000))
  }
];
mongoose.connect('mongodb://localhost/persons', function(err) {
  if (err) throw err;
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) throw err;
    // when querying data, instead of providing a callback, you can instead
    // leave that off and get a query object returned
    var query = Person.find({age: {$lt: 1000}});
    // this allows you to continue applying modifiers to it
    query.sort('birthday');
    query.select('name');
    // you can chain them together as well
    // a full list of methods can be found:
    // http://mongoosejs.com/docs/api.html#query-js
    query.where('age').gt(21);
    // finally, when ready to execute the query, call the exec() function
    query.exec(function(err, results) {
      if (err) throw err;
      console.log(results);
      cleanup();
    });
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 14 - 0
src/server/node_modules/mongoose/examples/replicasets/package.json

@ -0,0 +1,14 @@
{
  "name": "replica-set-example",
  "private": "true",
  "version": "0.0.0",
  "description": "deps for replica set example",
  "main": "querybuilder.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { "async": "*" },
  "repository": "",
  "author": "",
  "license": "BSD"
}

+ 15 - 0
src/server/node_modules/mongoose/examples/replicasets/person.js

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
  // define schema
  var PersonSchema = new Schema({
    name: String,
    age: Number,
    birthday: Date
  });
  mongoose.model('Person', PersonSchema);
};

+ 71 - 0
src/server/node_modules/mongoose/examples/replicasets/replica-sets.js

@ -0,0 +1,71 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./person.js')();
var Person = mongoose.model('Person');
// define some dummy data
var data = [
  {
    name: 'bill',
    age: 25,
    birthday: new Date().setFullYear((new Date().getFullYear() - 25))
  },
  {
    name: 'mary',
    age: 30,
    birthday: new Date().setFullYear((new Date().getFullYear() - 30))
  },
  {
    name: 'bob',
    age: 21,
    birthday: new Date().setFullYear((new Date().getFullYear() - 21))
  },
  {
    name: 'lilly',
    age: 26,
    birthday: new Date().setFullYear((new Date().getFullYear() - 26))
  },
  {
    name: 'alucard',
    age: 1000,
    birthday: new Date().setFullYear((new Date().getFullYear() - 1000))
  }
];
// to connect to a replica set, pass in the comma delimited uri and optionally
// any connection options such as the rs_name.
var opts = {
  replSet: {rs_name: 'rs0'}
};
mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function(err) {
  if (err) throw err;
  // create all of the dummy people
  async.each(data, function(item, cb) {
    Person.create(item, cb);
  }, function(err) {
    if (err) {
        // handle error
    }
      // create and delete some data
    var prom = Person.find({age: {$lt: 1000}}).exec();
    prom.then(function(people) {
      console.log('young people: %s', people);
    }).then(cleanup);
  });
});
function cleanup() {
  Person.remove(function() {
    mongoose.disconnect();
  });
}

+ 119 - 0
src/server/node_modules/mongoose/examples/schema/schema.js

@ -0,0 +1,119 @@
/**
 * Module dependencies.
 */
var mongoose = require('../../lib'),
    Schema = mongoose.Schema;
/**
 * Schema definition
 */
// recursive embedded-document schema
var Comment = new Schema();
Comment.add({
  title: {
    type: String,
    index: true
  },
  date: Date,
  body: String,
  comments: [Comment]
});
var BlogPost = new Schema({
  title: {
    type: String,
    index: true
  },
  slug: {
    type: String,
    lowercase: true,
    trim: true
  },
  date: Date,
  buf: Buffer,
  comments: [Comment],
  creator: Schema.ObjectId
});
var Person = new Schema({
  name: {
    first: String,
    last: String
  },
  email: {
    type: String,
    required: true,
    index: {
      unique: true,
      sparse: true
    }
  },
  alive: Boolean
});
/**
 * Accessing a specific schema type by key
 */
BlogPost.path('date')
.default(function() {
  return new Date();
})
.set(function(v) {
  return v === 'now' ? new Date() : v;
});
/**
 * Pre hook.
 */
BlogPost.pre('save', function(next, done) {
  /* global emailAuthor */
  emailAuthor(done); // some async function
  next();
});
/**
 * Methods
 */
BlogPost.methods.findCreator = function(callback) {
  return this.db.model('Person').findById(this.creator, callback);
};
BlogPost.statics.findByTitle = function(title, callback) {
  return this.find({title: title}, callback);
};
BlogPost.methods.expressiveQuery = function(creator, date, callback) {
  return this.find('creator', creator).where('date').gte(date).run(callback);
};
/**
 * Plugins
 */
function slugGenerator(options) {
  options = options || {};
  var key = options.key || 'title';
  return function slugGenerator(schema) {
    schema.path(key).set(function(v) {
      this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, '');
      return v;
    });
  };
}
BlogPost.plugin(slugGenerator());
/**
 * Define model.
 */
mongoose.model('BlogPost', BlogPost);
mongoose.model('Person', Person);

+ 0 - 0
src/server/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js


Some files were not shown because too many files changed in this diff